<?php session_start();
ini_set('max_execution_time', '30000');
$company="oast";

//$con=mysqli_connect("localhost", "enrepco_stmadmacc", "gCV^Aj@ky}19","enrepco_".$GLOBALS['company']) or die(mysqli_error($GLOBALS['con'])); //PROD
//$GLOBALS['path']='/home/enrepco/'.$GLOBALS['company'].'.enrep.co.uk'; 
$con=mysqli_connect("localhost", "dasoint_kelso", "carvan855","reporting_".$company) or die(mysqli_error($GLOBALS['con']));  //DEV
$GLOBALS['path']='../../';//dev
echo "PROCESSING AUTO-UPDATE FOR <b>".$company."-".date('d-m-Y')."</b><br></<br>";

function countdown($renewal){
    $renewal_date = date('d-m-Y',$renewal); 
    $current_date = date("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==0 && (date('m',$renewal)==date("m"))){return '<div class="alert alert-success text-center" style="padding:8px">Renewal due todays ('.$renewal_date.')</div>';}
    elseif(($days<30 && $days>0) && (date('m',$renewal)==date("m")) ){return '<div class="alert alert-warning text-center" style="padding:8px">Renewal due '.$day.' ('.$renewal_date.')</div>';}
    elseif(date('m-Y',$renewal)==date("m-Y")){return '<div class="alert alert-danger text-center" style="padding:8px">Renewal due '.$day.' ('.$renewal_date.')</div>';}
    else{return 'NULL';}
    }

function locationReports(){
$cnt=0;
$record=file_get_contents($GLOBALS['path'].'/framework/dashboard_functions/location_report.txt');
$record=explode("|",$record);
if(strtotime($record[0]) < strtotime('today')){    

function checkInsp6($cnb,$cn,$l,$ln,$p){
$now=strtotime('now');
$count=0;
$then=strtotime('now +1 month');

$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`duedate` FROM `itemdetails`  WHERE clientnumber='".$cnb."' AND  statuslive='1' AND `locnumber`='".$l."' ORDER BY abs(duedate) ASC  LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$ic=$stmt->get_result();$stmt->close();
$c=mysqli_num_rows($ic);
if($c<1){}
else{
$id=mysqli_fetch_array($ic);
if ($id['duedate'] > time() + (30 * 24 * 60 * 60)) {
   $status='<td class="text-success text-center text-strong">'.date('d-m-Y',$id['duedate']).' CLEAR</td>';
} 

// 2. Between now and 30 days in the future
if ($id['duedate'] >= time() && $idc['duedate'] < time() + (30 * 24 * 60 * 60)) {
   $status='<td class="text-warning text-center text-strong">'.date('d-m-Y',$id['duedate']).' DUE</td>';
}

// 3. Past now
if ($id['duedate'] < time()) {
   $status='<td class="text-danger text-center text-strong">'.date('d-m-Y',$id['duedate']).' PAST</td>';
}



$data='<tr>
<td><span style="display:none">'.$cn.'</span><a href="index.php?t=includes/master&p=location_report.php&mode=client&clientnumber='.$cnb.'">'.$cn.'</a></td>
<td>'.$ln.'</td>
<td>'.$p.'</td>
<td><span class="hidden noprint noExport" style="display:none">'.date('Y-m-d',$id['duedate']).'</span>'.date('d-m-Y',$id['duedate']).'</td>
'.$status.'
<td><a href="index.php?t=includes/master&amp;p=client.php&amp;clientnumber='.$cnb.'&amp;view=asset" class="btn btn-secondary noprint m-0 px-3 py-2 waves-effect" data-toggle="tooltip" data-placement="top" data-original-title="View Schedule"><i class="fad fa-th-list"></i></a></td>
</tr>';
return $data;
}
}

$i=0;
$start = microtime(true);
$stmt = $GLOBALS['con']->prepare("SELECT 
a.clientnumber,
a.locnumber,
a.locname,
a.postcode,
a.statuslive,
b.clientname,
b.statuslive,
b.clientnumber
FROM locations a JOIN clientdetails b ON a.clientnumber=b.clientnumber WHERE b.statuslive='1'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$iv=$stmt->get_result();$stmt->close();
$data=array();
while($list=mysqli_fetch_assoc($iv)){$data[]=$list;}
mysqli_free_result($iv);
$output='';
foreach($data as $l){$cnt++;$output.=checkInsp6($l['clientnumber'],$l['clientname'],$l['locnumber'],$l['locname'],$l['postcode']);}

$dueFile = fopen($GLOBALS['path'].'/framework/dashboard_functions/location_report.txt', 'w');
fwrite($dueFile, date('d-m-Y')."|".$output);
fclose($dueFile);
}
echo "Processing location_report Complete<br>";
}

############################################################################

function reportsNotSent(){
$cnt=0;
$record=file_get_contents($GLOBALS['path'].'/framework/dashboard_functions/reports.txt');
$record=explode("|",$record);
if(strtotime($record[0]) < strtotime('today')){

############################################################################

function listOutstandingReports2($item){
$output='';

$stmt = $GLOBALS['con']->prepare("SELECT `repitem` FROM `reportitems` WHERE `delivery`='0' AND `itemnumber`='".$item."' ORDER BY abs(repitem) ASC LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$iv=$stmt->get_result();$stmt->close();
return mysqli_num_rows($iv);
}

############################################################################

$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1' ORDER BY `clientname` ASC")or die(mysqli_error($GLOBALS['con']));$stmt->execute();$client=$stmt->get_result();$stmt->close();?>

<?php while($cdata=mysqli_fetch_assoc($client)){
$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber` FROM `itemdetails` WHERE `clientnumber`='".$cdata['clientnumber']."' AND `statuslive`='1'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$items=$stmt->get_result();$stmt->close();
$itemCount=0;
$data='';
while($idata=mysqli_fetch_assoc($items)){
$cnt++;
$num=listOutstandingReports2($idata['itemnumber']);
if($num==0){}
else{$itemCount++;
}}

if($itemCount>0){
$cdata['clientname']=preg_replace("/[^a-zA-Z]/", " ", $cdata['clientname']);
$data.='<tr id="R'.$list['clientnumber'].'">
<td>'.$cdata['clientname'].'</td>
<td>'.$itemCount.'</td>
<td>
<a href="index.php?t=includes/master/&p=reports_outstanding.php&clientnumber='.$cdata['clientnumber'].'" class="btn btn-secondary m-0 px-3 py-2 waves-effect float-right" data-toggle="tooltip" data-placement="bottom" title="View Reports" data-original-title="View Reports"><i class="fad fa-eye"></i></a>
</td>
</tr>';
}}

}

$reportFile = fopen($GLOBALS['path'].'/framework/dashboard_functions/reports.txt', 'w');
fwrite($reportFile, date('d-m-Y')."|".$data);
fclose($reportFile);
locationReports();
echo "Processing reportsNotSent Complete<br>";

}

function InspectionsDue(){
$cnt=0;
$record=file_get_contents($GLOBALS['path'].'/framework/dashboard_functions/insepections_due.txt');
$record=explode("|",$record);
if(strtotime($record[0]) < strtotime('today')){



function checkInsp2($t,$m,$c,$n){
$now=strtotime('now');
$count=0;
$then=strtotime('now +1 month');

$stmt = $GLOBALS['con']->prepare("SELECT `duedate`,`itemnumber` FROM `itemdetails` WHERE `duedate`>'$now' AND `duedate`<'$then' AND `statuslive`='1'  AND `clientnumber`='".$c."' LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$ic=$stmt->get_result();$stmt->close();
$id=mysqli_num_rows($ic);
$rowdata=mysqli_fetch_array($ic);
$count=$id;

if($count!=0){
$data='<tr><th>'.$n.'</th>
<td>'.date("d-m-Y",$rowdata['duedate']).'</td>
<td>
<div class="btn-group" role="group" style="float:right">
<a href="index.php?t=includes/master&p=client.php&clientnumber='.$c.'&view=asset&search=Pending" class="btn btn-secondary noprint m-0 px-3 py-2 waves-effect" data-toggle="tooltip" data-placement="top" data-original-title="View Schedule"><i class="fad fa-th-list"></i></a>
</div>
</td></tr>';
}
return $$m;

}
$i=0;
$start = microtime(true);
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$iv=$stmt->get_result();$stmt->close();
while($list=mysqli_fetch_assoc($iv)){$data[]=$list;}
mysqli_free_result($iv);

foreach($data as $l){$cnt++;$output.=checkInsp2('due','data',$l['clientnumber'],$l['clientname']);}

$dueFile = fopen($GLOBALS['path'].'/framework/dashboard_functions/insepections_due.txt', 'w');
fwrite($dueFile, date('d-m-Y')."|".$output);
fclose($dueFile);
}
echo "Processing InspectionsDue Complete<br>";
reportsNotSent();
}

function renewalsDue(){
$record=file_get_contents($GLOBALS['path'].'/framework/dashboard_functions/renewals_due.txt');
$record=explode("|",$record);
if(strtotime($record[0]) < strtotime('today')){    

    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` ORDER BY abs(renewal_date) ASC")or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();$iv=$stmt->get_result();$stmt->close();
    while($list=mysqli_fetch_array($iv)){
    if($list['renewal_date']!=="" && $list['renewal_status']!="LAPSED"){
    $status=countdown($list['renewal_date']);
    

if($status=="NULL"){}else{
$output.='<tr id="R'.$list['clientnumber'].'">
<th>'.$list['clientname'].'</th>
<td>'.$status.'</td>
<td><a href="javascript:void(0)" onClick="setRenew(\''.$list['clientnumber'].'\',\''.$list['clientname'].'\')" class="btn btn-secondary m-0 px-3 py-2 waves-effect float-right" data-toggle="tooltip" data-placement="bottom" title="Confirm Contract Renewal" data-original-title="Confirm Contract Renewal"><i class="fad fa-hands-helping"></i></a></td>
</tr>';
}
}
}
$renewalFile = fopen($GLOBALS['path'].'/framework/dashboard_functions/renewals_due.txt', 'w');
fwrite($renewalFile, date('d-m-Y')."|".$output);
fclose($renewalFile);

}
InspectionsDue();
echo "Processing renewalsDue Complete<br>";
}

function getOverdue(){
$record=file_get_contents($GLOBALS['path'].'/framework/dashboard_functions/insepections_overdue.txt');
$record=explode("|",$record);

if(strtotime($record[0]) < strtotime('today')){

function checkInsp3($t,$m,$c,$n){
$now=strtotime('now');
$count=0;
$then=strtotime('now +1 month');



$stmt = $GLOBALS['con']->prepare("SELECT `duedate`,`itemnumber` FROM `itemdetails` WHERE `statuslive`='1' AND `duedate` < '$now' AND `clientnumber`='".$c."' LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$ic=$stmt->get_result();$stmt->close();
$id=mysqli_num_rows($ic);
$rowdata=mysqli_fetch_array($ic);
$count=$id;

if($count!=0){
$data='<tr><th>'.$n.'</th>
<td>'.date("d-m-Y",$rowdata['duedate']).'</td>
<td>
<div class="btn-group" role="group" style="float:right">
<a href="index.php?t=includes/master&p=client.php&clientnumber='.$c.'&view=asset&search=Overdue" class="btn btn-secondary noprint m-0 px-3 py-2 waves-effect" data-toggle="tooltip" data-placement="top" data-original-title="View Schedule"><i class="fad fa-th-list"></i></a>
</div>
</td></tr>';
}
return $$m;
}


$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'")or die(mysqli_error("GET_INV_NO: ".$GLOBALS['con']));
$stmt->execute();$iv=$stmt->get_result();$stmt->close();
while($list=mysqli_fetch_assoc($iv)){$data[]=$list;}
mysqli_free_result($iv);

foreach($data as $l){$output.=checkInsp3('clientOver','data',$l['clientnumber'],$l['clientname']);}

$overdueFile = fopen($GLOBALS['path'].'/framework/dashboard_functions/insepections_overdue.txt', 'w');
fwrite($overdueFile, date('d-m-Y')."|".$output);
fclose($overdueFile);
}
echo "Processing getOverdue Complete<br>";
renewalsDue();
}

getOverdue();

echo "<br><br>All processing functions completed successfully<br>";

?>