<?php
$tenant = preg_replace('/[^A-Za-z0-9._\/-]/', '', (string)($_REQUEST['tenant'] ?? ''));
$tenantRoot = '../../..' . $tenant;

if (file_exists($tenantRoot . '/config.php')) {
    require_once($tenantRoot . '/config.php');
}

if (file_exists('/config.php')) {
    require_once('/config.php');
}

$clientAccess = [];
$clientAccessLookup = [];
$mode = '';
$sessionUserId = (int)($_SESSION['userid'] ?? 0);

if ($sessionUserId > 0) {
    $accessQuery = "SELECT clientnumbers FROM admin_access WHERE admin_id = ?";
    $stmt = $GLOBALS['con']->prepare($accessQuery);
    $stmt->bind_param('i', $sessionUserId);
    $stmt->execute();
    $result = $stmt->get_result();
    $accessRow = $result->fetch_assoc();
    if ($accessRow) {
        $clientAccessArray = json_decode($accessRow['clientnumbers'] ?? '[]', true);
        if (is_array($clientAccessArray)) {
            $clientAccess = array_values(array_unique(array_filter(array_map('intval', $clientAccessArray))));
            $clientAccessLookup = array_flip($clientAccess);
        }
    } else {
        $mode = "elevated";
    }
    $stmt->close();
}

$record = '';
$contractorNumber = trim((string)($_REQUEST['contractorNumber'] ?? ''));
if ($contractorNumber !== '') {
    $stmt = $GLOBALS['con']->prepare("SELECT `contractor_name` FROM `contractors` WHERE `contractor_number` = ? LIMIT 1");
    $stmt->bind_param("s", $contractorNumber);
    $stmt->execute();
    $sd = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $contractorName = str_replace(" ", "_", (string)($sd['contractor_name'] ?? ''));
    $cacheFile = $tenantRoot . '/framework/dashboard_functions/' . $contractorName . '_insepections_due.txt';
} else {
    $cacheFile = $tenantRoot . '/framework/dashboard_functions/insepections_due.txt';
}

if (!empty($cacheFile) && is_file($cacheFile)) {
    $record = (string)file_get_contents($cacheFile);
}

$record = explode("|", $record, 2);
$record[1] = $record[1] ?? '';
$dest=ROOT_URL.'/includes/locations/location_report.php?search=due&tenant='.TENANT_URL;

$rows = explode('</tr>', $record[1]); // Split based on the row end tag
$output='';

foreach ($rows as $row) {
    if($mode=="elevated"){$output.= $row . '</tr>';}
    else{
    // Match the clientnumber pattern (e.g. clientnumber=437)
    if (preg_match('/clientnumber=(\d+)/', $row, $matches)) {
        $clientNumber = (int)$matches[1]; // Extract the client number as an integer

        // If the client number is in the allowed array, output the row
        if (isset($clientAccessLookup[$clientNumber])) {
            $output.= $row . '</tr>'; // Echo the row and add back the closing </tr> tag
        }
    }
    }
}
?>

<div class="col-md-6 mb-3">
    <div class="card">
        <div class="card-header">Inspections Due this month <?php if(empty($_SESSION['contractorNumber'])){?>
            <a class="float-end text-light" href="javascript:void(0)" onclick="loadModalContent('<?=$dest?>', 'inspDue', 'modal-xl', 1060, 'true','Inspections Due','close');">View all</a>
            <?php }?>
        </div>
        <div class="card-body" style="max-height:200px; overflow: auto">
            <table class="table table-sm table-striped">
                <?php
if(empty($record[1])){
    echo "<tr><td>No inspection cache available.</td></tr>";
}
elseif($_SESSION['access']==999){echo $record[1];}
else{
echo $output;
}
//printf("Total time cached query: %.6fs\n", microtime(true) - $start);
?>
            </table>
        </div>
        <div class="card-footer border-0"></div>
    </div>
</div>
