<?php
require_once(ROOT_URL . '/includes/surveyor/surveyor_capacity.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`, `access` FROM `surveyor` WHERE `statuslive` = '1' $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, with linked EnRep owners excluded from slot usage
$capacity_snapshot = enrep_surveyor_capacity_snapshot($GLOBALS['con'], $admin_con ?? null);
$active_surveyors = (int)$capacity_snapshot['slot_active'];
$active_surveyors_total = (int)$capacity_snapshot['active_total'];
$linked_owner_bypass_count = (int)$capacity_snapshot['linked_owner_active'];

/* ---------------------------
   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
   (Updated: lock until midnight of activation day)
----------------------------*/
$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;
    }
}

function surveyorSecurityLevelName($access)
{
    switch ((int)$access) {
        case 0:
            return 'Suspended';
        case 1:
            return 'Full';
        case 2:
            return 'Elevated';
        case 3:
            return 'Assigned';
        default:
            return 'Unknown';
    }
}
?>

<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">Active 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 Surveyor Slots
            <?= $capacityLabel ?><?= $boost_note ?>
            <?php if ($linked_owner_bypass_count > 0): ?>
            <span class="badge bg-secondary ms-1"><?= $linked_owner_bypass_count ?> External Owner Bypass</span>
            <span class="ms-2 text-muted"><small><?= $active_surveyors_total ?> total active</small></span>
            <?php endif; ?>
            <?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">
        <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 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=archive" class="btn btn-secondary btn-sm ms-2"
            data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="View archived surveyors">
            <i class="fad fa-archive" aria-hidden="true"></i> Archived 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>Surveyors:</strong>
            <small> Manage system access. If assigned, set which clients and/or assets are visible when they log
                in.</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>Security Level</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 = [
                'clientNumber' => '0',
                'clientName' => $cd['forename'] . ' ' . $cd['surname'],
                'primaryEmail' => $cd['email'],
                'secondaryEmail' => '',
                'subject' => '',
                'message' => '',
                'filePath' => '',
                'fileName' => ''
            ];
            $email64_values = base64_encode(json_encode($email_values));

            // Lock indicator: only if activated today, show time remaining until midnight
            $lockout_icon = '';
            if (!empty($cd['live_since'])) {
                $lsTs = strtotime($cd['live_since']);
                if ($lsTs && date('Y-m-d', $lsTs) === date('Y-m-d')) {
                    $until = strtotime('tomorrow') - 1; // today 23:59:59
                    $rem   = max(0, $until - $current_time);
                    if ($rem > 0) {
                        $hours   = floor($rem / 3600);
                        $minutes = floor(($rem % 3600) / 60);
                        $lockout_icon = '<span data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Locked until midnight: ' . $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>';
                }
            }

            $linked_owner_icon = '';
            if (enrep_surveyor_email_is_linked_owner($admin_con ?? null, $cd['email'] ?? '', $tenant_client_id)) {
                $linked_owner_icon = '<span class="badge bg-secondary ms-1" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Owner of another EnRep tenant - does not use a surveyor slot"><i class="fad fa-link me-1"></i>Free Seat</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 ?>
                <?= $linked_owner_icon ?>
            </td>
            <td><?= htmlspecialchars($cd['phone1']) ?></td>
            <td><?= htmlspecialchars($cd['email']) ?></td>
            <td><?= htmlspecialchars(surveyorSecurityLevelName($cd['access'] ?? null)) ?></td>
            <td id="AS<?= (int)$cd['id'] ?>">
                <?= ((int)($cd['access'] ?? 0) === 3) ? 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="<?= htmlspecialchars($email64_values, ENT_QUOTES) ?>"
                        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 me-2"><i class="fad fa-info-circle"></i></a>

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

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

<?php if ($active_surveyors >= $effective_limit): ?>
<div class="text-danger mt-2">
    <small>Limit reached for standard surveyors. Owners of other EnRep tenants can still be added.</small>
</div>
<?php endif; ?>

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