<?php
// Contractor filter
if (!empty($_SESSION['contractorNumber'])) {
    $filter = "AND `contractor`='" . $_SESSION['contractorNumber'] . "'";
} else {
    $filter = '';
}

/* ---------------------------
   Tenant base limit + counts
----------------------------*/
// Fetch active surveyors list
$cc = mysqli_query($GLOBALS['con'], "SELECT `id`, `esname`, `forename`, `surname`, `phone1`, `email`, `live_since` FROM `surveyor` WHERE `statuslive` = '0' $filter") or die(mysqli_error($GLOBALS['con']));

// Base limit from tenant subscription
$subscription_query = mysqli_query($GLOBALS['con'], "SELECT surveyor_limit, client_id FROM subscription_params");
$subscription_data  = mysqli_fetch_assoc($subscription_query);
$surveyor_limit     = (int)$subscription_data['surveyor_limit'];
$tenant_client_id   = isset($subscription_data['client_id']) ? (int)$subscription_data['client_id'] : 0;

// Current active surveyors
$active_surveyors_query = mysqli_query($GLOBALS['con'], "SELECT COUNT(*) as active_count FROM surveyor WHERE statuslive = 1");
$active_surveyors_data  = mysqli_fetch_assoc($active_surveyors_query);
$active_surveyors       = (int)$active_surveyors_data['active_count'];

/* ---------------------------
   Active boost from admin DB
----------------------------*/
$boost_qty = 0;
$boost_note = '';
$effective_limit = $surveyor_limit;

if (isset($admin_con) && $admin_con instanceof mysqli && $tenant_client_id > 0) {
    // Sum of all active boosts for this client
    $stmt = $admin_con->prepare("SELECT COALESCE(SUM(qty),0) AS qty_sum, MIN(expires_at) AS next_expiry
                                 FROM boost_requests
                                 WHERE client_id=? AND status='active'");
    if ($stmt) {
        $stmt->bind_param('i', $tenant_client_id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && ($row = $res->fetch_assoc())) {
            $boost_qty = (int)$row['qty_sum'];
            $next_exp  = $row['next_expiry'];
            if ($boost_qty > 0) {
                $effective_limit = $surveyor_limit + $boost_qty;
                $boost_note = ' <span class="badge bg-info">Boost +' . $boost_qty . ($next_exp ? (' until ' . date('d-m-Y H:i', strtotime($next_exp))) : '') . '</span>';
            }
        }
        $stmt->close();
    }
}

/* ---------------------------
   Capacity label (effective)
----------------------------*/
$capacityLabel = '';
if ($active_surveyors > $effective_limit) {
    $capacityLabel = '<span class="badge bg-danger">Over Capacity</span>';
} elseif ($active_surveyors == $effective_limit) {
    $capacityLabel = '<span class="badge bg-warning">At Capacity</span>';
} elseif ($active_surveyors >= (int)floor($effective_limit * 0.9)) {
    $capacityLabel = '<span class="badge bg-warning">Close to Capacity</span>';
} else {
    $capacityLabel = '<span class="badge bg-success">Within Capacity</span>';
}

/* ---------------------------
   Lockout timing display
----------------------------*/
$lockout_period = 24 * 60 * 60; // seconds
$current_time   = time();

/* ---------------------------
   Assigned inline helper
----------------------------*/
function surverorAssignedInline($surveyor, $mode)
{
    $clients = '0';
    $locs = '0';
    $itemData = array();
    $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `client_id` FROM `surveyor_assignments` WHERE `surveyor`=? ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $surveyor);
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    while ($id = mysqli_fetch_array($ic)) {
        $itemData[] = $id;
    }
    $clients = mysqli_num_rows($ic);
    foreach ($itemData as $data) {
        $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `site_id` FROM `surveyor_assignments` WHERE `surveyor`=? AND `client_id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $surveyor, $data['client_id']);
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        $c = mysqli_num_rows($ic);
        $locs += $c;
    }

    switch ($mode) {
        default:
            return '<a href="javascript:void(0)" onclick="loadAssignments(\'' . $surveyor . '\')"><span><b>' . $clients . '</b> Clients assigned with <b>' . $locs . '</b> locations in total</a></span>';
        case "total":
            return $clients + $locs;
    }
}
?>

<script>
document.getElementById('navBox').innerHTML = `
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=surveyor.php&view=list">Surveyors</a>
        <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i>
    </li>
    <li class="breadcrumb-item active">Archive List</li>`;

function loadAssignments(surveyor) {
    var dest = ROOT_URL + "/includes/surveyor/surveyorAssigned.php?s=" + surveyor + "&tenant=" + TENANT_URL;
    loadModalContent(dest, "popupBox", "modal-xl", 1050, "true");
}

function openBoostRequest() {
    // Inline modal for requesting a boost. The target script will be provided next.
    var dest = encodeURI(ROOT_URL + "/includes/surveyor/boost_request.php?tenant=" + TENANT_URL +
        "&client_id=<?= (int)$tenant_client_id ?>");
    loadModalContent(dest, "popupBox", "modal-md", 1060, "true", "Request Boost", "cancelBoost", function() {});
}
</script>

<div class="row">
    <div class="col-12">
        <div class="alert alert-info">
            <strong>Surveyor Capacity:</strong>
            <?= $active_surveyors ?> / <?= $effective_limit ?> Active Surveyors
            <?= $capacityLabel ?><?= $boost_note ?>
            <?php if ($boost_qty === 0): ?>
            <span class="ms-2 text-muted"><small>Base limit: <?= (int)$surveyor_limit ?></small></span>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12 col-md-4 order-md-2 order-1 text-end mb-3">
        <?php if ($active_surveyors < $effective_limit): ?>
        <a href="index.php?t=includes/master&p=surveyor.php&view=new" class="btn btn-secondary btn-sm"
            data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Create a new surveyor">
            <i class="fad fa-plus" aria-hidden="true"></i> New Surveyor
        </a>
        <?php else: ?>
        <span class="text-danger d-block mb-2"><small>Limit reached. Deactivate a slot or request a
                boost.</small></span>
        <?php endif; ?>

        <?php if ($active_surveyors >= $surveyor_limit): ?>
        <button type="button" class="btn btn-info btn-sm ms-0" onclick="openBoostRequest()" data-mdb-tooltip-init
            data-mdb-placement="bottom" data-mdb-trigger="hover" title="Request a temporary capacity boost">
            <i class="fad fa-rocket-launch"></i> Request Boost
        </button>
        <?php endif; ?>

        <a href="index.php?t=includes/master&p=surveyor.php&view=list" class="btn btn-secondary btn-sm"><i
                class="fad fa-user-hard-hat"></i> Active Surveyors</a>
    </div>

    <div class="col-12 col-md-8 order-md-1 order-2 mb-3">
        <div class="note note-secondary mb-3">
            <strong>Archived Surveyors:</strong>
            <small> Reinstate surveyors, a 24hour lock will engage on the reinstated supplier to prevent hot swapping
                .</small>
        </div>
    </div>
</div>

<div id="loadingObject">
    <h1 class="text-center">
        <i class="fad fa-flux-capacitor fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>
        Loading Surveyors <br><small>Please wait</small>
    </h1>
</div>

<table id="datatable" class="table table-striped table-sm table-bordered table-hover responsive nowrap" width="100%"
    style="display:none">
    <thead>
        <tr>
            <th width="50" class="no-sort noExport"></th>
            <th>Name</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Assigned</th>
            <th class="no-sort noExport"></th>
        </tr>
    </thead>
    <tbody>
        <?php

        $tenant_client_id = 0;
        if ($r = $con->query("SELECT client_id FROM subscription_params LIMIT 1")) {
            if ($row = $r->fetch_assoc()) $tenant_client_id = (int)$row['client_id'];
        }
        $boosted_map = [];
        if (isset($admin_con) && $admin_con instanceof mysqli && $tenant_client_id > 0) {
            $stmt = $admin_con->prepare("
                SELECT bsu.surveyor_id, br.expires_at
                FROM boost_request_surveyors bsu
                JOIN boost_requests br ON br.id = bsu.boost_id
                WHERE br.client_id = ? AND br.status = 'active'
            ");
            $stmt->bind_param('i', $tenant_client_id);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $boosted_map[(int)$row['surveyor_id']] = $row['expires_at'];
            }
            $stmt->close();
        }
        while ($cd = mysqli_fetch_array($cc)) {
            $email_values = [
                0 => '0', // client
                1 => $cd['forename'] . ' ' . $cd['surname'], // type
                2 => $cd['email'], // recipient
                3 => '', // subject
                4 => '', // message
                5 => '', // attachment
                6 => '' // source
            ];
            $email64_values = base64_encode(json_encode($email_values));

            // 24-hour lockout indicator
            $lockout_icon = '';
            if (!empty($cd['live_since'])) {
                $live_since_timestamp = strtotime($cd['live_since']);
                if ($live_since_timestamp) {
                    $time_remaining = $lockout_period - ($current_time - $live_since_timestamp);
                    if ($time_remaining > 0) {
                        $hours   = floor($time_remaining / 3600);
                        $minutes = floor(($time_remaining % 3600) / 60);
                        $lockout_icon = '<span data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Restriction active: ' . $hours . 'h ' . $minutes . 'm remaining"><i class="fad fa-lock text-danger"></i></span>';
                    }
                }
            }

            $boost_icon = '';
            if (isset($boosted_map[(int)$cd['id']])) {
                $expTs = strtotime($boosted_map[(int)$cd['id']]);
                $rem   = $expTs - $current_time;
                if ($expTs && $rem > 0) {
                    $days = floor($rem / 86400);
                    $hours = floor(($rem % 86400) / 3600);
                    $minutes = floor(($rem % 3600) / 60);
                    $label = $days > 0 ? "{$days}d {$hours}h" : "{$hours}h {$minutes}m";
                    $boost_icon = '<span class="ms-1" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Boost expires in ' . $label . '"><i class="fad fa-rocket-launch text-warning"></i></span>';
                } else {
                    $boost_icon = '<span class="ms-1" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Boost expired pending cleanup"><i class="fad fa-rocket-launch text-secondary"></i></span>';
                }
            }
        ?>
        <tr>
            <td>
                <?php if (file_exists('images/profile/' . $cd['id'] . '.jpg')) { ?>
                <img src="images/profile/<?= $cd['id'] ?>.jpg?<?= rand() ?>" alt="Avatar"
                    class="img-fluid img-thumbnail">
                <?php } else { ?>
                <img src="images/profile/noimage.png?<?= rand() ?>" alt="Avatar" class="img-fluid img-thumbnail">
                <?php } ?>
            </td>
            <td><?= htmlspecialchars($cd['forename'] . ' ' . $cd['surname']) ?> <?= $lockout_icon ?> <?= $boost_icon ?>
            </td>
            <td><?= htmlspecialchars($cd['phone1']) ?></td>
            <td><?= htmlspecialchars($cd['email']) ?></td>
            <td id="AS<?= (int)$cd['id'] ?>"><?= surverorAssignedInline((int)$cd['id'], ''); ?></td>
            <td class="text-end">
                <div class="btn-group" role="group">
                    <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Manage access"
                        href="index.php?t=includes/master&p=surveyor.php&id=<?= (int)$cd['id'] ?>&view=assign"
                        class="btn btn-secondary noprint me-2"><i class="fad fa-arrow-right-to-arc"></i></a>

                    <?php if (!empty($cd['phone1'])) { ?>
                    <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Dial surveyor"
                        href="tel:<?= htmlspecialchars($cd['phone1']) ?>" class="btn btn-secondary noprint me-2"><i
                            class="fad fa-phone"></i></a>
                    <?php } ?>

                    <?php if (!empty($cd['email']) && !filter_var($cd['email'], FILTER_VALIDATE_EMAIL) === false) { ?>
                    <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Email surveyor"
                        href="javascript:void(0)" class="btn btn-secondary noprint emailButton me-2"
                        data-values="<?= $email64_values ?>" data-href="<?= ROOT_URL ?>/includes/master/mailer.php"><i
                            class="fad fa-envelope"></i></a>
                    <?php } ?>

                    <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="View details"
                        href="index.php?t=includes/master&p=surveyor.php&id=<?= (int)$cd['id'] ?>&view=edit"
                        class="btn btn-secondary noprint"><i class="fad fa-info-circle"></i></a>

                    <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
                        title="Reinstate Surveyor" href="javascript:void(0)"
                        onClick="reinstateSurveyor('surveyor','id','<?= $cd['id'] ?>','surveyor_functions.php','reinstateSupplier')"
                        class="btn btn-secondary"><i class="fad fa-upload"></i></a>

                </div>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>

<?php
$table = "datatable";
$dateTarget = "";
$sortTarget = "1";
$length = "25";
$sortCell = "nth-child(2)";
$logo = "yes";
$scroller = "";
require(ROOT_URL . "/includes/tables/single_table.php");