<?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');
}

$cacheFile = $tenantRoot . '/framework/dashboard_functions/renewals_due.txt';
$record = is_file($cacheFile) ? (string)file_get_contents($cacheFile) : '';
$record = explode("|", $record, 2);
$record[1] = $record[1] ?? '';

$clientAccess = [];
$clientAccessLookup = [];
$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();
    $accessResult = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $clientAccessArray = json_decode($accessResult['clientnumbers'] ?? '[]', true);

    if (is_array($clientAccessArray)) {
        $clientAccess = array_values(array_unique(array_filter(array_map('intval', $clientAccessArray))));
        $clientAccessLookup = array_flip($clientAccess);
    }
}
$output='';
$rows = explode('</tr>', $record[1]); // Split based on the row end tag

// Loop through each row and check if it contains a client number that is allowed
foreach ($rows as $row) {
    // Match the row ID pattern (e.g. id="R1027")
    if (preg_match("/id=\"R(\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; // Echo the row (no need to add </tr> as it's already part of the row)
        }
    }
}
?>

<div class="col-md-6">
    <div class="card">
        <div class="card-header">Renewals this month</div>
        <div class="card-body" style="max-height:200px; overflow: auto">
            <table id="datatable" class="table table-sm table-striped" style="display: table">
                <?php
if(empty($record[1])){
    echo "<tr><td>No renewals 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>
