<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php');}
switch($_REQUEST['FUNCTION']){
default:break;

case "remove":
$data=urldecode($_REQUEST['dataSet']);$d=explode("|",$data);
$client=$d[0];
$item=$d[2];

$stmt = $GLOBALS['con']->prepare("SELECT `olddate`,`result`, `repnumber` FROM `reportitems` WHERE `repitem`='".$_REQUEST['rep']."'")or die(mysqli_error($e=$GLOBALS['con']));
$stmt->execute();$r=$stmt->get_result();$stmt->close();
$repOld=mysqli_fetch_array($r);

$stmt = $GLOBALS['con']->prepare("DELETE  FROM `reportitems` WHERE `repitem`='".$_REQUEST['rep']."'")or die(mysqli_error($e=$GLOBALS['con']));
$stmt->execute();$stmt->close();
unlink('../../../'.TENANT_URL.'/output/reports/'.$client.'/'.$repOld['repnumber'].'_'.$item.'.pdf');

if($repOld['olddate']=="Not Known" || $repOld['olddate']==""){$oldDate='';}
else{$oldDate=$repOld['olddate'];}

//check for last report
$query = "SELECT `result` FROM reportitems WHERE itemnumber = $item ORDER BY repitem DESC LIMIT 1";
$resultData = $con->query($query);
if (!$resultData) {
    echo "Query Error: " . $con->error;
}
if ($resultData && $resultData->num_rows > 0) {
    $row = $resultData->fetch_assoc();
    $result = $row['result'];
    //echo "found and updated";
} else {
    $result = null; // Explicitly set to null if no rows are found
    //echo "not found and updated";
}

$stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `duedate`='".$repOld['olddate']."', `lastReport`='".$result."' WHERE `itemnumber`='".$item."'")or die(mysqli_error($e=$GLOBALS['con']));
$stmt->execute();$stmt->close();


break;

}
?>