<?php 


if(file_exists('../../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }


function countdown($renewal, $limiter){
    $now = new DateTime();
    $renewal_date = date('d-m-Y',$renewal); 
    $current_date = $now->format('d-m-Y');    
    $onemonth = $now->sub(new DateInterval('P1M'));
    //$twomonth = $now->sub(new DateInterval('P2M'));
    $om=$onemonth->format('d-m-Y');
    //$tm=$twomonth->format('d-m-Y');

    $datetime1 = new DateTime($current_date ); 
    $datetime2 = new DateTime($renewal_date);
    $difference = $datetime1->diff($datetime2);
    
    $days=$difference->format("%r%a");
    if (strpos($days,'-')!== false) {$day=$difference->format("%a").' days ago';}
    else{$day='in '.$days.' days';}
   
    if($days<60 && $days>0 && date('m-Y',$renewal)!=date("m-Y")){$ret= '<div class="alert alert-info text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}    

    elseif($days==0 && (date('m',$renewal)==date("m"))){$ret= '<div class="alert alert-success text-center m-0" style="padding:3px">Renewal due today ('.$renewal_date.')'.$om.'</div>';}

    elseif(($days<30 && $days>0) && (date('m',$renewal)==date("m")) ){$ret= '<div class="alert alert-warning text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}

    elseif(date('m-Y',$renewal)==date("m-Y")){$ret= '<div class="alert alert-danger text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}

    elseif(date('m-Y',$renewal)==date("m-Y",strtotime($om))){$ret= '<div class="alert alert-dark text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}

    //elseif(date('m-Y',$renewal)==date("m-Y",strtotime($twomonth))){$ret= '<div class="alert alert-dark text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}

    else{$ret= 'NULL';}
    
    return $ret;
}

function countdownAdditional($renewal, $limiter){
    $now = new DateTime();
    $renewal_date = date('d-m-Y',$renewal); 
    $current_date = $now->format('d-m-Y');    
    $onemonth = $now->sub(new DateInterval('P1M'));
    //$twomonth = $now->sub(new DateInterval('P2M'));
    $om=$onemonth->format('d-m-Y');
    //$tm=$twomonth->format('d-m-Y');

    $datetime1 = new DateTime($current_date ); 
    $datetime2 = new DateTime($renewal_date);
    $difference = $datetime1->diff($datetime2);
    
    $days=$difference->format("%r%a");
    if (strpos($days,'-')!== false) {$day=$difference->format("%a").' days ago';}
    else{$day='in '.$days.' days';}
   
    if($days<60 && $days<-30){$ret= '<div class="alert alert-info text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}    

    else{$ret= 'NULL';}
    
    return $ret;
}
           
            $ret='<div class="mb-3">';
            if($_REQUEST['rMode']=="older"){
                $ret.='<p class="lead">Older Renewals</p>';
                    }
                    if($_REQUEST['rMode']=="current"){
                        $ret.='<p class="lead">Renewals this month</p>';
                            }
                           
            $ret.='<table id="datatable" class="table table-sm table-striped table-hover">
            <thead><th width="300">Client</th><th>Renewal</th><th class="no-sort" width="250"></th></thead>
            <tbody>';

            $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `statuslive`='1' ORDER BY abs(renewal_date) DESC")or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();$iv=$stmt->get_result();$stmt->close();
            while($list=mysqli_fetch_array($iv)){
                if(empty($list['renewal_date'])){}
                else{
            if($list['renewal_date']!=="0" && $list['renewal_status']!="LAPSED"){
                if($_REQUEST['rMode']=="older"){
                $status=countdownAdditional($list['renewal_date'],"no");
                }
                if($_REQUEST['rMode']=="current"){
                    $status=countdown($list['renewal_date'],"no");
                        }
            $renewOptions=json_decode($list['renewOptions'],true);
             $rn=mysqli_query($GLOBALS['con'],"SELECT * FROM `renewals` WHERE `clientnumber`='".$list['clientnumber']."' AND `status`='0' ")or die(mysqli_error($GLOBALS['con']));
            $rnCount=mysqli_num_rows($rn);

            switch($renewOptions['notice']){
            default:$renewMode="unset";break;
            case "0": $renewMode="client"; 
                $renewId=$list['clientnumber'];
                $name=$list['clientname'];
                $name=str_replace("&","and",$name);
                $name=str_replace("'&'","",$name);
                $email1=$list['billing_email'] ?? null;
                $email2=$list['email'] ?? null;
                $autoIcon = ' <span class="position-absolute end-0 top-0 me-n3 bg-dark text-light small z-1 px-1 text-center d-flex align-items-center justify-content-center" style="font-size: 0.6rem; border-radius: 2px; min-width: 12px; height: 100%;">C</span>';           
            break;
            case "1": $renewMode="agent"; 
                $renewId=$list['agent_number']; 
                $bc=mysqli_query($GLOBALS['con'],"SELECT * FROM `agents` WHERE `agent_number`='".$list['agent_number']."' ")or die(mysqli_error($GLOBALS['con']));
                $nameData=mysqli_fetch_array($bc);
                $name=$nameData['agent_name'] ?? null;
                $name=str_replace("&","and",$name);
                $name=str_replace("'&'","",$name);
                $email1=$nameData['billing_email'] ?? null;
                $email2=$nameData['email'] ?? null;
                $autoIcon = ' <span class="position-absolute end-0 top-0 me-n3 bg-dark text-light small z-1 px-1 text-center d-flex align-items-center justify-content-center" style="font-size: 0.6rem; border-radius: 2px; min-width: 12px; height: 100%;">A</span>';           
            break;
            case "2": $renewMode="broker"; 
                $renewId=$list['broker_number'];
                $bc=mysqli_query($GLOBALS['con'],"SELECT * FROM `brokers` WHERE `broker_number`='".$list['broker_number']."' ")or die(mysqli_error($GLOBALS['con']));
                $nameData=mysqli_fetch_array($bc);
                $name=isset($nameData['broker_name']) ? $nameData['broker_name'] : '';
                $name=str_replace("&","and",$name);
                $name=str_replace("'&'","",$name);
                $email1=$nameData['billing_email'] ?? null;
                $email2=$nameData['email'] ?? null;
                $autoIcon = ' <span class="position-absolute end-0 top-0 me-n3 bg-dark text-light small z-1 px-1 text-center d-flex align-items-center justify-content-center" style="font-size: 0.6rem; border-radius: 2px; min-width: 12px; height: 100%;">B</span>';
            break;
            }

            $clientname=str_replace("&","and",$list['clientname']);
               
            $clientname=htmlspecialchars($clientname, ENT_QUOTES, 'UTF-8');

            if($status=="NULL"){}else{
                $ret.='<tr id="R'.$list['clientnumber'].'">
                <td>'.$list['clientname'].'</td>
                <td>'.$status.'</td>

                    <td class="align-middle text-end">

                                <button type="button" class="btn btn-secondary btn-sm m-0 px-3 py-2 me-3"
                                        onclick="loadModalContent(\''.ROOT_URL.'/includes/finance/renewals/renewal-client.php?clientnumber='.$list['clientnumber'].'&tenant='.TENANT_URL.'\',\'popupBox\',\'modal-xl\',1060,true,\'Client Information\')"
                                        data-toggle="tooltip"
                                        data-placement="top"
                                        title="View information"
                                        data-values="'.$list['clientnumber'].'">
                                    <i class="fad fa-circle-info"></i>
                                </button>

                                <a href="javascript:void(0)" 
                                onclick="loadModalContent(\''.ROOT_URL.'/includes/client/location-client.php?clientnumber='.$list['clientnumber'].'&tenant='.TENANT_URL.'\',\'popupBox\',\'modal-xl\',1060,true,\'Plant Summary\')"
                                style="z-index:999"
                                   class="text-light btn btn-secondary btn-sm m-0 px-3 py-2 me-3"
                                   data-toggle="tooltip"
                                   data-placement="bottom"
                                   title="Client Plant Summary">
                                    <i class="fad fa-clipboard-list"></i>
                                </a>';

                                if($renewMode=="unset"){
                                    $ret.='<a style="position:relative" href="?t=includes/master&p=client.php&clientnumber='.$list['clientnumber'].'&view=edit" id="renewButton'.$list['clientnumber'].'"
                                    class="btn btn-danger btn-sm m-0 px-3 py-2 me-3"
                                    data-toggle="tooltip"
                                    data-placement="top"
                                    title="Renewal Setup Incomplete">
                                        <i class="fad fa-person-walking-arrow-loop-left"></i>
                                    </a>';
                                    }
                                    else{
                                    if($rnCount==1){
                                        $rndata=mysqli_fetch_array($rn);
                                        $buttonColor="success sentButton";$buttonText="Renewal Sent";
                                        $ret.='<button type="button" id="A'.$list['clientnumber'].'" class="btn btn-'.$buttonColor.' btn-sm m-0 px-3 py-2 me-3 position-relative text-dark"
                                            data-client="'.$list['clientnumber'].'"
                                            data-clientname="'.$clientname.'"
                                            data-mode="'.$renewMode.'"
                                            data-name="'.$name.'"
                                            data-date="'.date('d-m-Y',$rndata['date']).'"
                                            data-rendate="'.date('d-m-Y',$list['renewal_date']).'"
                                            data-email1="'.$email1.'"
                                            data-email2="'.$email2.'"
                                            data-id="'.$rndata['id'].'"
                                            data-file="'.$rndata['invoiceName'].'"
                                            data-toggle="tooltip"
                                            data-placement="top"
                                            title="'.$buttonText.'">
                                            <i class="fad fa-person-walking-arrow-loop-left"></i>
                                            '.$autoIcon.'
                                    </button>';
                                     }
                                    else{
                                        $rndata=mysqli_fetch_array($rn);
                                        $invoiceFile=isset($rndata['invoiceName']) ? $rndata['invoiceName'] : '';
                                        $buttonColor="secondary renewButton";$buttonText="Send ".$renewMode." Renewal";
                                        $ret.='<button type="button"
        id="A'.$list['clientnumber'].'"
        class="btn btn-'.$buttonColor.' btn-sm m-0 px-3 py-2 me-3 position-relative text-dark"
        data-client="'.$list['clientnumber'].'"
        data-clientname="'.$clientname.'"
        data-mode="'.$renewMode.'"
        data-name="'.$name.'"
        data-contract="'.$list['contract_number'].'" 
        data-fee="'.$list['rate_per_hour'].'" 
        data-date="'.date('d-m-Y',$rndata['date']).'"
        data-rendate="'.date('d-m-Y',$list['renewal_date']).'"
        data-email1="'.$email1.'"
        data-email2="'.$email2.'"
        data-id="'.$rndata['id'].'"
        data-file="'.$rndata['invoiceName'].'"
        data-mdb-tooltip-init
        data-mdb-placement="top"
        data-mdb-trigger="hover"
        title="'.$buttonText.'">
    <i class="fad fa-person-walking-arrow-loop-left"></i>
    '.$autoIcon.'
</button>';
                                 }

                                 }
                                 $ret.='
                   
                    </td>
                    </tr>';
                    }
                    }
                    }}
                
                $ret.='</tbody></table>
                </div>';
                $table="datatable";
                        $dateTarget="5";        
        $length="50";
        $sortTarget="1";
        $sortCell="";
        $logo="yes";
        $scroller="";
        $printTarget='exportDiv';
        $printHeader='Outstanding Payments';
        $popup="false";
                require_once('../../tables/single_table.php');
                if($_REQUEST['rMode']=="older"){
                    $ret.='<div class="col-12 text-center"><a class="btn btn-secondary btn-sm" onclick="getRenewals(\'current\')">Current Renewals</a></div>';
                        }
                        if($_REQUEST['rMode']=="current"){
                            $ret.='<div class="col-12 text-center"><a class="btn btn-secondary btn-sm" onclick="getRenewals(\'older\')">Older Renewals</a></div>';
                                }
                echo $ret;