<?php 
require_once __DIR__ . '/../../functions/logging.php';
require_once __DIR__ . '/surveyor_capacity.php';
// Load tenant config
if (!empty($_REQUEST['tenant']) && file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
function isTodayLockActive(?string $liveSince): bool {
    if (!$liveSince) return false;
    $ts = strtotime($liveSince);
    if ($ts === false) return false;
    if (date('Y-m-d', $ts) !== date('Y-m-d')) return false;
    return time() < (strtotime('tomorrow') - 1);
}

/**
 * Call this ONLY when flipping 0 -> 1.
 * Keeps existing live_since if already set today.
 */
function setLiveSinceOnActivate(mysqli $con, int $surveyorId): void {
    $id = (int)$surveyorId;
    $row = $con->query("SELECT live_since FROM surveyor WHERE id={$id}")->fetch_assoc();
    $cur = $row['live_since'] ?? null;

    $needsSet = true;
    if ($cur) {
        $ts = strtotime($cur);
        if ($ts && date('Y-m-d', $ts) === date('Y-m-d')) $needsSet = false;
    }
    if ($needsSet) {
        $stmt = $con->prepare("UPDATE surveyor SET live_since=NOW() WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
    }
}

function surveyorColumnExists(mysqli $con, string $column): bool {
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'surveyor' AND COLUMN_NAME = ? LIMIT 1");
    if (!$stmt) return false;
    $stmt->bind_param('s', $column);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

function normaliseSurveyorDayStartTime($value): ?string {
    $value = trim((string)$value);
    if ($value === '') return null;
    if (preg_match('/^([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/', $value, $matches)) {
        return sprintf('%02d:%02d:00', (int)$matches[1], (int)$matches[2]);
    }
    return null;
}

function surveyorBindParams(mysqli_stmt $stmt, string $types, array &$params): bool {
    $refs = [$types];
    foreach ($params as $key => &$value) {
        $refs[] = &$value;
    }
    return call_user_func_array([$stmt, 'bind_param'], $refs);
}
/* =========================
   BOOST HELPERS
   ========================= */

if (!function_exists('boost_effective_limit')) {
  function boost_effective_limit(mysqli $con, mysqli $admin_con): array {
    $client_id = 0; $base = 0; $boost = 0;
    if ($r = $con->query("SELECT client_id, surveyor_limit FROM subscription_params LIMIT 1")) {
      if ($row = $r->fetch_assoc()) { $client_id=(int)$row['client_id']; $base=(int)$row['surveyor_limit']; }
    }
    if ($client_id > 0 && $admin_con instanceof mysqli) {
      if ($s = $admin_con->prepare("SELECT COALESCE(SUM(qty),0) FROM boost_requests WHERE client_id=? AND status='active'")) {
        $s->bind_param('i',$client_id); $s->execute(); $s->bind_result($boost); $s->fetch(); $s->close();
      }
    }
    return [$client_id, $base, $base + (int)$boost];
  }
}

if (!function_exists('boost_active_boost_id')) {
  function boost_active_boost_id(mysqli $admin_con, int $client_id): ?int {
    if ($client_id <= 0 || !($admin_con instanceof mysqli)) return null;
    $id = null;
    if ($stmt = $admin_con->prepare("SELECT id FROM boost_requests WHERE client_id=? AND status='active' ORDER BY activated_at DESC LIMIT 1")) {
      $stmt->bind_param('i',$client_id); $stmt->execute();
      $res = $stmt->get_result(); if ($res && ($row=$res->fetch_assoc())) $id = (int)$row['id'];
      $stmt->close();
    }
    return $id;
  }
}

if (!function_exists('boost_tag_action')) {
  function boost_tag_action(mysqli $con, mysqli $admin_con, int $surveyorId, string $action): void {
    $client_id = 0;
    if ($r = $con->query("SELECT client_id FROM subscription_params LIMIT 1")) {
      if ($row = $r->fetch_assoc()) $client_id = (int)$row['client_id'];
    }
    if ($client_id <= 0 || !($admin_con instanceof mysqli)) return;
    $boost_id = boost_active_boost_id($admin_con, $client_id);
    if (!$boost_id) return;

    if ($stmt = $admin_con->prepare("INSERT IGNORE INTO boost_request_surveyors (boost_id, client_id, surveyor_id, action) VALUES (?,?,?,?)")) {
      $stmt->bind_param('iiis', $boost_id, $client_id, $surveyorId, $action);
      $stmt->execute(); $stmt->close();
    }
  }
}

if (!function_exists('boost_maybe_tag')) {
  function boost_maybe_tag(mysqli $con, mysqli $admin_con, int $surveyorId, bool $wasReinstated): void {
    boost_tag_action($con, $admin_con, $surveyorId, $wasReinstated ? 'reinstated' : 'created');
  }
}

enrep_log_request_completion('surveyors', 'FUNCTION', [
    'insert' => ['action' => 'created', 'message' => 'Created surveyor', 'entity_type' => 'surveyor'],
    'update' => ['action' => 'updated', 'message' => 'Updated surveyor', 'entity_type' => 'surveyor'],
    'remSur' => ['action' => 'assignment_removed', 'message' => 'Removed surveyor assignment', 'entity_type' => 'surveyor_assignments'],
    'archiveSupplier' => ['action' => 'archived', 'message' => 'Archived surveyor', 'entity_type' => 'surveyor'],
    'reinstateSupplier' => ['action' => 'reinstated', 'message' => 'Reinstated surveyor', 'entity_type' => 'surveyor'],
    'setSiteSurveyor' => ['action' => 'site_assigned', 'message' => 'Assigned surveyor to site', 'entity_type' => 'surveyor_assignments'],
    'setAssetSurveyor' => ['action' => 'asset_assigned', 'message' => 'Assigned surveyor to asset', 'entity_type' => 'surveyor_assignments'],
    'revokeSurveyor' => ['action' => 'access_revoked', 'message' => 'Revoked surveyor access', 'entity_type' => 'surveyor_assignments'],
    'revokeSurveyorSite' => ['action' => 'site_access_revoked', 'message' => 'Revoked surveyor site access', 'entity_type' => 'surveyor_assignments'],
    'activateSite' => ['action' => 'site_access_activated', 'message' => 'Activated surveyor site access', 'entity_type' => 'surveyor_assignments'],
    'suspendSite' => ['action' => 'site_access_suspended', 'message' => 'Suspended surveyor site access', 'entity_type' => 'surveyor_assignments'],
]);

/* =========================
   CORE SWITCH
   ========================= */

switch ($_REQUEST['FUNCTION'] ?? '') {
    default:
        break;

    /* -------- INSERT -------- */
    case "insert":
        $_REQUEST['statuslive'] = ($_REQUEST['statuslive'] == "on") ? "1" : "0";
        $_REQUEST['delAuth']    = ($_REQUEST['delAuth'] == "on") ? "1" : "0";
        $access = !empty($_SESSION['contractorNumber']) ? '2' : '';

        // Capacity guard only if creating live
        $newIsLive = $_REQUEST['statuslive'] === "1";
        if ($newIsLive && isset($admin_con)) {
            [$client_id, $base, $effective] = boost_effective_limit($con, $admin_con);
            $live = enrep_surveyor_active_slot_count($GLOBALS['con'], $admin_con);
            $isLinkedOwner = enrep_surveyor_email_is_linked_owner($admin_con, $_REQUEST['email'] ?? '', $client_id);
            if (!$isLinkedOwner && $live >= $effective) { echo "limit_reached"; exit(); }
        }

        // Next esname
        $r = mysqli_query($GLOBALS['con'], "SELECT `esname` FROM `surveyor` ORDER BY ABS(esname) DESC LIMIT 1,1");
        $rd = mysqli_fetch_array($r);
        $num = ($rd['esname'] + 1);

        $hasDayStartTime = surveyorColumnExists($GLOBALS['con'], 'day_start_time');
        $dayStartTime = normaliseSurveyorDayStartTime($_REQUEST['day_start_time'] ?? '');
        $columns = "`esname`, `surname`, `forename`, `address1`, `address2`, `address3`, `postcode`, `phone1`, `phone2`, `fax`, `mobile`, `password`, `email`, `statuslive`, `access`, `qual`, `delAuth`, `contractor`, `live_since`";
        $values = "?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,NULL";
        $types = 'issssssssssssssii';
        $params = [
            $num,
            $_REQUEST['surname'],
            $_REQUEST['forename'],
            $_REQUEST['address1'],
            $_REQUEST['address2'],
            $_REQUEST['address3'],
            $_REQUEST['postcode'],
            $_REQUEST['phone1'],
            $_REQUEST['phone2'],
            $_REQUEST['fax'],
            $_REQUEST['mobile'],
            $apw,
            $_REQUEST['email'],
            $_REQUEST['statuslive'],
            $_REQUEST['qual'],
            $_REQUEST['delAuth'],
            $_REQUEST['contractor']
        ];
        if ($hasDayStartTime) {
            $columns .= ", `day_start_time`";
            $values .= ",?";
            $types .= "s";
            $params[] = $dayStartTime;
        }

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor` ($columns) VALUES($values)") or die(mysqli_error($GLOBALS['con']));
        // NOTE: $apw is assumed to be defined upstream in your environment
        surveyorBindParams($stmt, $types, $params);
        $ok = $stmt->execute();
        $e  = $stmt->error;
        $newId = (int)mysqli_insert_id($GLOBALS['con']);
        echo $newId . $e;
        $stmt->close();

        // Tag if created live during an active boost
        if ($ok && $newIsLive && isset($admin_con) && !enrep_surveyor_email_is_linked_owner($admin_con, $_REQUEST['email'] ?? '', $client_id ?? 0)) {
            boost_maybe_tag($con, $admin_con, $newId, false);
        }
        exit();

    /* -------- UPDATE -------- */
   case "update":
    $surveyorId = (int)($_REQUEST['id'] ?? 0);
    if ($surveyorId <= 0) { echo "error"; exit(); }
    $isProfileUpdate = (($_REQUEST['profile'] ?? '') === '1');
    if ($isProfileUpdate && (($_SESSION['usertype'] ?? '') === 'surveyor') && $surveyorId !== (int)($_SESSION['userid'] ?? 0)) {
        echo "forbidden";
        exit();
    }

    $hasDayStartTime = surveyorColumnExists($GLOBALS['con'], 'day_start_time');

    // Previous state
    $prevLive = 0; $hadLiveBefore = false; $liveSinceVal = null; $prevDelAuth = 0; $prevDayStartTime = null;
    $profileSelect = "SELECT statuslive, live_since, delAuth" . ($hasDayStartTime ? ", day_start_time" : "") . " FROM surveyor WHERE id=?";
    if ($stmt = $GLOBALS['con']->prepare($profileSelect)) {
        $stmt->bind_param('i', $surveyorId);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && ($row = $res->fetch_assoc())) {
            $prevLive      = (int)$row['statuslive'];
            $hadLiveBefore = !empty($row['live_since']);
            $liveSinceVal  = $row['live_since'] ?? null;
            $prevDelAuth   = (int)($row['delAuth'] ?? 0);
            $prevDayStartTime = $hasDayStartTime ? ($row['day_start_time'] ?? null) : null;
        }
        $stmt->close();
    }

    // Inputs
    $newStatusLive = $isProfileUpdate ? $prevLive : ((isset($_POST['statuslive']) && ($_POST['statuslive'] === "1" || $_POST['statuslive'] === "on")) ? 1 : 0);
    $_REQUEST['statuslive'] = $newStatusLive ? "1" : "0";
    if ($isProfileUpdate) {
        $_REQUEST['delAuth'] = (string)$prevDelAuth;
    } else {
        if ($_REQUEST['delAuth'] == "on")  $_REQUEST['delAuth'] = "1";
        if ($_REQUEST['delAuth'] == "off" || $_REQUEST['delAuth'] == "") $_REQUEST['delAuth'] = "0";
    }

    $isFlipToLive    = ($prevLive === 0 && $newStatusLive === 1);
    $isFlipToArchive = ($prevLive === 1 && $newStatusLive === 0);

    // Block archive if today's lock is active
    if ($isFlipToArchive && isTodayLockActive($liveSinceVal)) { echo "lock"; exit(); }

    // Capacity guard when flipping 0 -> 1
    if ($isFlipToLive && isset($admin_con)) {
        [$client_id, $base, $effective] = boost_effective_limit($GLOBALS['con'], $admin_con);
        $live = enrep_surveyor_active_slot_count($GLOBALS['con'], $admin_con);
        $isLinkedOwner = enrep_surveyor_email_is_linked_owner($admin_con, $_REQUEST['email'] ?? '', $client_id);
        if (!$isLinkedOwner && $live >= $effective) { echo "capacity"; exit(); }
    }

    // live_since: set ONLY on 0->1. Never null here. Never touch if not flipping.
    $liveSinceClause = $isFlipToLive ? "live_since=NOW()," : "";

    $dayStartTime = normaliseSurveyorDayStartTime($_REQUEST['day_start_time'] ?? '');
    if ($isProfileUpdate && !array_key_exists('day_start_time', $_REQUEST)) {
        $dayStartTime = $prevDayStartTime;
    }
    $dayStartTimeClause = $hasDayStartTime ? "`day_start_time`=?," : "";

    // UPDATE
    $sql = "
        UPDATE `surveyor` SET
            `surname`=?, `forename`=?, `address1`=?, `address2`=?, `address3`=?, `postcode`=?,
            `phone1`=?, `phone2`=?, `fax`=?, `mobile`=?,
            `password`=AES_ENCRYPT('" . $_REQUEST['password'] . "','" . $_REQUEST['email'] . "'),
            `email`=?, `statuslive`=?, `qual`=?, `delAuth`=?,
            {$dayStartTimeClause}
            {$liveSinceClause}
            id=id
        WHERE `id`=?
    ";
    $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
    $types = str_repeat('s', 13) . 'i';
    $params = [
        $_REQUEST['surname'],
        $_REQUEST['forename'],
        $_REQUEST['address1'],
        $_REQUEST['address2'],
        $_REQUEST['address3'],
        $_REQUEST['postcode'],
        $_REQUEST['phone1'],
        $_REQUEST['phone2'],
        $_REQUEST['fax'],
        $_REQUEST['mobile'],
        $_REQUEST['email'],
        $_REQUEST['statuslive'],
        $_REQUEST['qual'],
        $_REQUEST['delAuth']
    ];
    if ($hasDayStartTime) {
        $types .= 's';
        $params[] = $dayStartTime;
    }
    $types .= 'i';
    $params[] = $surveyorId;
    surveyorBindParams($stmt, $types, $params);
    $ok = $stmt->execute();
    $stmt->close();

    // Tag if 0->1 (boost tagging unchanged)
    if ($ok && $isFlipToLive && isset($admin_con) && !enrep_surveyor_email_is_linked_owner($admin_con, $_REQUEST['email'] ?? '', $client_id ?? 0)) {
        $action = $hadLiveBefore ? 'reinstated' : 'created';
        boost_tag_action($GLOBALS['con'], $admin_con, $surveyorId, $action);
    }

    echo $ok ? "success" : "error";
    exit();


    /* -------- getList -------- */
    case "getList":
        if ($_REQUEST['mode'] == "site") {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['comp'] . "'") or die($error = mysqli_error($GLOBALS['con']));
            $arr = array(); $ret = '';
            $stmt->execute();
            $res = $stmt->get_result();
            $er = mysqli_stmt_error($stmt);
            $stmt->close();
            while ($d = mysqli_fetch_array($res)) {
                $ret .= '<li class="list-group-item btn btn-block btn-secondary mb-1 A' . $d['locnumber'] . '" id="I' . $d['locnumber'] . '" data-item-id="I' . $d['locnumber'] . '" >
                <div class="row">
                <div class="col-md-11">' . $d['locname'] . '</div>
                <div class="col-md-1"><button type="button" class="close add_area" aria-label="Close"><span aria-hidden="true">&plus;</span></button></div>
                </div>
                </li>';
                $arr[] = $d['locnumber'];
            }
            echo json_encode($arr) . "|" . $ret . $er;
        }
        
        if ($_REQUEST['mode'] == "asset") {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['comp'] . "'") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $res = $stmt->get_result();
            $er = mysqli_stmt_error($stmt);
            $stmt->close();
            while ($d = mysqli_fetch_array($res)) { $ite[] = $d; }
            $arr = array(); $ret = '';
            foreach ($ite as $a) {
                $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`serialnumber`,`desc` FROM `itemdetails` WHERE `locnumber`='" . $a['locnumber'] . "' AND `statuslive`='1'") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
                $res2 = $stmt->get_result();
                $er = mysqli_stmt_error($stmt);
                $stmt->close();
                while ($itm = mysqli_fetch_array($res2)) {
                    $ret .= '<li class="list-group-item btn btn-block btn-secondary mb-1 A' . $itm['itemnumber'] . '" id="I' . $itm['itemnumber'] . '" data-item-id="I' . $itm['itemnumber'] . '" >
                <div class="row">
                <div class="col-md-11">' . $itm['itemnumber'] . " : " . $itm['desc'] . ' : ' . $itm['serialnumber'] . '</div><div class="col-md-1"><button type="button" class="close add_area" aria-label="Close"><span aria-hidden="true">&plus;</span></button></div>
                </div>
                </li>';
                    $arr[] = $a['locnumber'];
                }
            }
            echo json_encode($arr) . "|" . $ret . $er;
        }
        
        if ($_REQUEST['mode'] == "list") {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname`,`postcode`,`locaddress1`,`locaddress2`,`locaddress3`,`locaddress4` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['comp'] . "' AND `statuslive`='1'") or die($error = mysqli_error($GLOBALS['con']));
            $ret = '<select id="locationSelector" class="form-control form-control-sm" data-placeholder="Select Location" onChange="getLocationList()"><option value=""></option><option value="ALL">ALL</option>';
            $stmt->execute();
            $res = $stmt->get_result();
            $er = mysqli_stmt_error($stmt);
            $stmt->close();
            while ($d = mysqli_fetch_array($res)) {
                $ret .= '<option value="' . $d['locnumber'] . '">' . $d['locaddress1'] . ',' . $d['locaddress2'] . ',' . $d['locaddress3'] . ',' . $d['locaddress4'] . ', ' . $d['postcode'] . '</option>';
            }
            echo $ret;
        }
        break;

        /* -------- getSurv -------- */
        case "getSurv":
        if ($_REQUEST['mode'] == "site") {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['comp'] . "'") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $res = $stmt->get_result();
            $er = mysqli_stmt_error($stmt);
            $stmt->close();
            $arr = array(); $ret = '';
            while ($d = mysqli_fetch_array($res)) {
                $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc` FROM `itemdetails` WHERE `locnumber`='" . $d['locnumber'] . "' AND `surveyor`='" . $_REQUEST['surv'] . "'") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
                $res2 = $stmt->get_result();
                $stmt->close();
                $cnt = mysqli_num_rows($res2);
                if ($cnt > 0) {
                    $ret .= '<li class="list-group-item btn btn-block btn-secondary mb-1 C' . $d['locnumber'] . '" id="I' . $d['locnumber'] . '" data-item-id="I' . $d['locnumber'] . '" >
                    <div class="row">
                    <div class="col-md-11">' . $d['locname'] . '</div><div class="col-md-1"><button type="button" class="close click_area" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>
                    </div>
                    </li>';
                    $arr[] = $d['locnumber'];
                }
            }
            echo json_encode($arr) . "|" . $ret . $er;
        }
        
        
        if ($_REQUEST['mode'] == "asset") {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['comp'] . "'") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $res = $stmt->get_result();
            $er = mysqli_stmt_error($stmt);
            $stmt->close();
            while ($d = mysqli_fetch_array($res)) { $ite[] = $d; }
            $arr = array(); $ret = '';
            foreach ($ite as $a) {
                $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc` FROM `itemdetails` WHERE `locnumber`='" . $a['locnumber'] . "' AND `surveyor`='" . $_REQUEST['surv'] . "'") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
                $res2 = $stmt->get_result();
                $stmt->close();
                while ($itm = mysqli_fetch_array($res2)) {
                    $ret .= '<li class="list-group-item btn btn-block btn-secondary mb-1 C' . $itm['itemnumber'] . '" id="I' . $itm['itemnumber'] . '" data-item-id="I' . $itm['itemnumber'] . '" >
                    <div class="row">
                    <div class="col-md-11">' . $itm['itemnumber'] . ": " . $itm['desc'] . '</div><div class="col-md-1"><button type="button" class="close click_area" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>
                    </div>
                    </li>';
                    $arr[] = $itm['itemnumber'];
                }
            }
            echo json_encode($arr) . "|" . $ret . $er;
        }
        break;

    /* -------- removals / toggles -------- */
    case "remSur":
        $asset = explode("I", $_REQUEST['asset']);
        if ($_REQUEST['mode'] == "site") {
            $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `surveyor`='' WHERE `locnumber`='" . $asset[1] . "' ") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
        } else {
            $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `surveyor`='' WHERE `itemnumber`='" . $asset[1] . "' ") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
        }
        echo $asset[1];
        break;

    case "serial":
        $i = 0; $ret = '';
        $orderlist = explode(',', $_REQUEST['ar']);
        foreach ($orderlist as $value) { $r .= $value; $i++; }

        if ($_REQUEST['mode'] == "asset") {
            $assets = explode("I", $r);
            foreach ($assets as $asset) {
                $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `surveyor`='" . $_REQUEST['surv'] . "' WHERE `itemnumber`='" . $asset . "' ") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
                echo $asset . "<br>";
            }
        }

        if ($_REQUEST['mode'] == "site") {
            $assets = explode("I", $r);
            $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `surveyor`='" . $_REQUEST['surv'] . "' WHERE `locnumber`='" . $assets[1] . "' ") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            echo $_REQUEST['comp'] . "|" . $_REQUEST['surv'] . "|" . $_REQUEST['mode'];
        }
        break;

    case "archiveSupplier":
    $sid = (int)($_REQUEST['id'] ?? 0);
    if ($sid <= 0) { echo "error"; break; }

    // Fetch live_since to enforce today's lock
    $stmt = $con->prepare("SELECT statuslive, live_since FROM surveyor WHERE id=?");
    $stmt->bind_param('i', $sid);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$row) { echo "error"; break; }

    if ((int)$row['statuslive'] === 1 && isTodayLockActive($row['live_since'] ?? null)) {
        // Return remaining seconds to midnight
        $until = strtotime('tomorrow') - 1;
        $remaining = max(0, $until - time());
        echo "lock|".$remaining;
        break;
    }

    $stmt = $con->prepare("UPDATE surveyor SET statuslive='0' WHERE id=?");
    $stmt->bind_param('i', $sid);
    $stmt->execute();
    echo "s";
    break;


    /* -------- REINSTATE -------- */
   case "reinstateSupplier":
    $surveyorId = (int)($_REQUEST['id'] ?? 0);
    if ($surveyorId <= 0) { echo "error"; break; }

    // Previous
    $prevLive = 0; $hadLiveBefore = false; $surveyorEmail = '';
    if ($stmt = $con->prepare("SELECT statuslive, live_since, email FROM surveyor WHERE id=?")) {
        $stmt->bind_param('i', $surveyorId);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && ($row = $res->fetch_assoc())) {
            $prevLive      = (int)$row['statuslive'];
            $hadLiveBefore = !empty($row['live_since']);
            $surveyorEmail = (string)($row['email'] ?? '');
        }
        $stmt->close();
    }

    // Capacity guard (reinstate is 0->1)
    if (isset($admin_con)) {
        [$client_id, $base, $effective] = boost_effective_limit($con, $admin_con);
        $live = enrep_surveyor_active_slot_count($con, $admin_con);
        $isLinkedOwner = enrep_surveyor_email_is_linked_owner($admin_con, $surveyorEmail, $client_id);
        if (!$isLinkedOwner && $live >= $effective) { echo "capacity"; break; }
    }

    // Activate and set live_since NOW (lock applies until midnight)
    $stmt = $con->prepare("UPDATE surveyor SET statuslive='1', live_since=NOW() WHERE id=?") or die(mysqli_error($con));
    $stmt->bind_param('i', $surveyorId);
    $ok = $stmt->execute(); 
    $stmt->close();

    if ($ok && $prevLive === 0 && isset($admin_con) && !enrep_surveyor_email_is_linked_owner($admin_con, $surveyorEmail, $client_id ?? 0)) {
        $action = $hadLiveBefore ? 'reinstated' : 'created';
        boost_tag_action($con, $admin_con, $surveyorId, $action);
    }
    echo $ok ? "s" : "error";
    break;





    /* -------- assignments -------- */
    case "surverorAssigned":
        function getAssetName($l) {
            $stmt = $GLOBALS['con']->prepare("SELECT `desc` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $l);
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            $pd = mysqli_fetch_array($cc);
            return $pd['desc'];
        }
        function getAssetMarkings($l) {
            $stmt = $GLOBALS['con']->prepare("SELECT `plantnumber`,`serialnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $l);
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            $pd = mysqli_fetch_array($cc);
            return "<small class='text-danger'>[" . $pd['plantnumber'] . " - " . $pd['serialnumber'] . "]</small>";
        }

        $_REQUEST['name'] = trim(preg_replace('/\s*\([^)]*\)/', '', $_REQUEST['name']));

        $ret = '<div class="col-12 lead"><strong>' . $_REQUEST['name'] . '</strong> assigned clients/sites</div>
    <table class="table table-sm table-striped table-bordered table-hover">
    <thead class="table-dark">
        <tr>
            <td width="33%">Client</td>
            <td width="33%">Assigned  Location</td>
            <td width="33%">Assigned Assets</td>
        </tr>
    </thead>
    <tbody>
    ';
        $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', $_REQUEST['surveyor']);
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();

        while ($id = mysqli_fetch_array($ic)) { $itemData[] = $id; }
        foreach ($itemData as $data) {
            $locs = ''; $assets = '';
            $stmt = $GLOBALS['con']->prepare("SELECT * FROM `surveyor_assignments` WHERE `surveyor`=? AND `client_id`=? ") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ii', $_REQUEST['surveyor'], $data['client_id']);
            $stmt->execute();
            $ic = $stmt->get_result();
            $stmt->close();
            while ($id = mysqli_fetch_array($ic)) {
                if ($id['status'] == 1) {
                    $statusMode = 'suspendSite'; $statusIcon = 'pause'; $statusColour = 'success'; $statusText = 'Suspend site access';
                }
                if ($id['status'] == 0) {
                    $statusMode = 'activateSite'; $statusIcon = 'play'; $statusColour = 'warning'; $statusText = 'Grant site access';
                }

                $locs .= '<div class="col-12 border-bottom"><p><small>' . getLocation($id['site_id']) . '</small>';
                if (empty($id['asset_id'])) {
                    $locs .= '<span class="float-end">
            <button data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="' . $statusText . '" class="btn btn-sm btn-' . $statusColour . ' m-0 px-3 py-2" type="button" onclick="' . $statusMode . '(\'' . $id['id'] . '\',\'' . getLocation($id['site_id']) . '\')"><i class="fad fa-' . $statusIcon . '"></i></button>
            <button data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Remove site access" class="btn btn-sm btn-danger m-0 px-3 py-2" type="button" onclick="revokeSite(\'' . $id['id'] . '\')"><i class="fad fa-close"></i></button></span>
            </p></div>';
                } else {
                    $locs .= '</div>';
                }

                if (!empty($id['asset_id'])) {
                    $assets .= '<div class="col-12 border-bottom"><p><small>' . getAssetName($id['asset_id']) . ' ' . getAssetMarkings($id['asset_id']) . '</small> 
            <span class="float-end">
            <button data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="' . $statusText . '" class="btn btn-sm btn-' . $statusColour . ' m-0 px-3 py-2" type="button" onclick="' . $statusMode . '(\'' . $id['id'] . '\',\'' . getLocation($id['site_id']) . '\')"><i class="fad fa-' . $statusIcon . '"></i></button>
            <button data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Remove site access" class="btn btn-sm btn-danger m-0 px-3 py-2" type="button" onclick="revokeSite(\'' . $id['id'] . '\')"><i class="fad fa-close"></i></button></span>
            </p></div>';
                }
            }
            $ret .= '
    <tr><td width="33%">
        <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Remove client access" class="btn btn-danger m-0 px-3 py-2 btn-sm me-3" type="button"  onclick="revoke(\'' . $data['client_id'] . '\')"><i class="fad fa-close"></i></a>
        <a id="B' . $data['client_id'] . '" href="index.php?t=includes/master&p=client.php&clientnumber=' . $data['client_id'] . '&view=asset" class="item me-0" style="width:80%">' . getClientName($data['client_id'], 'name') . '</a>
        </td>
        <td width="33%">' . $locs . '</td>
        <td width="33%">' . $assets . '</td>
    </tr>
    ';
        }
        $ret .= '</tbody></table>';
        echo $ret;
        break;

    /* -------- site/asset assign -------- */
    case "setSiteSurveyor":
        $date = strtotime('now');
        if ($_REQUEST['locnumber'] == "ALL") {
            $r = mysqli_query($GLOBALS['con'], "SELECT `locnumber` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'");
            while ($d = mysqli_fetch_array($r)) {
                $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `surveyor_assignments` WHERE `surveyor`='" . $_REQUEST['surveyor'] . "' AND `client_id`='" . $_REQUEST['clientnumber'] . "' AND `site_id`='" . $d['locnumber'] . "'");
                if (mysqli_num_rows($check) == 0) {
                    $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor_assignments` VALUES(NULL,'" . $_REQUEST['surveyor'] . "','" . $_REQUEST['clientnumber'] . "','" . $d['locnumber'] . "',NULL,'" . $date . "','0','1') ") or die($error = mysqli_error($GLOBALS['con']));
                    $stmt->execute();
                }
            }
            mysqli_close($GLOBALS['con']);
        } else {
            $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `surveyor_assignments` WHERE `client_id`='" . $_REQUEST['clientnumber'] . "' AND `site_id`='" . $_REQUEST['locnumber'] . "'");
            if (mysqli_num_rows($check) == 0) {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor_assignments` VALUES(NULL,'" . $_REQUEST['surveyor'] . "','" . $_REQUEST['clientnumber'] . "','" . $_REQUEST['locnumber'] . "',NULL,'" . $date . "','0','1') ") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
            }
        }
        echo "done" . $_REQUEST['locnumber'] . $error;
        break;

    case "setAssetSurveyor":
        $date = strtotime('now');
        if ($_REQUEST['locnumber'] == "ALL") {
            $r = mysqli_query($GLOBALS['con'], "SELECT `locnumber` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'");
            while ($d = mysqli_fetch_array($r)) {
                $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `surveyor_assignments` WHERE `surveyor`='" . $_REQUEST['surveyor'] . "' AND `client_id`='" . $_REQUEST['clientnumber'] . "' AND `asset_id`='" . $_REQUEST['itemnumber'] . "'");
                if (mysqli_num_rows($check) == 0) {
                    $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor_assignments` VALUES(NULL,'" . $_REQUEST['surveyor'] . "','" . $_REQUEST['clientnumber'] . "','" . $d['locnumber'] . "','" . $_REQUEST['itemnumber'] . "','" . $date . "','0','1') ") or die($error = mysqli_error($GLOBALS['con']));
                    $stmt->execute();
                }
            }
            mysqli_close($GLOBALS['con']);
        } else {
            $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `surveyor_assignments` WHERE `client_id`='" . $_REQUEST['clientnumber'] . "' AND `site_id`='" . $_REQUEST['locnumber'] . "' AND `asset_id`='" . $_REQUEST['itemnumber'] . "'");
            if (mysqli_num_rows($check) == 0) {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor_assignments` VALUES(NULL,'" . $_REQUEST['surveyor'] . "','" . $_REQUEST['clientnumber'] . "','" . $_REQUEST['locnumber'] . "','" . $_REQUEST['itemnumber'] . "','" . $date . "','0','1') ") or die($error = mysqli_error($GLOBALS['con']));
                $stmt->execute();
            }
        }
        echo "dones" . $_REQUEST['itemnumber'] . $error;
        break;

    case "revokeSurveyor":
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `surveyor_assignments` WHERE `client_id`='" . $_REQUEST['clientnumber'] . "' ") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->execute();
        break;

    case "revokeSurveyorSite":
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `surveyor_assignments` WHERE `id`='" . $_REQUEST['assignment'] . "'") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->execute();
        break;

    case "activateSite":
        $stmt = $GLOBALS['con']->prepare("UPDATE `surveyor_assignments` SET `status`='1' WHERE `id`='" . $_REQUEST['assignment'] . "'") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->execute();
        break;

    case "suspendSite":
        $stmt = $GLOBALS['con']->prepare("UPDATE `surveyor_assignments` SET `status`='0' WHERE `id`='" . $_REQUEST['assignment'] . "'") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->execute();
        break;

    case "clientAssigned":
        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'  ORDER BY `clientname` ASC") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $cc = $stmt->get_result();
        $stmt->close();

        while ($pd = mysqli_fetch_array($cc)) { $ca[] = $pd; }

        $ret = '<select class="form-control form-control-sm" id="clientSelector" name="comp" onchange="getList()" data-placeholder="Select Company"><option value=""></option>';
        foreach ($ca as $px) {
            $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `site_id` FROM `surveyor_assignments` WHERE `client_id`=? AND `surveyor`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ii', $px['clientnumber'], $_REQUEST['surveyor']);
            $stmt->execute();
            $ic = $stmt->get_result();
            $stmt->close();
            $count = mysqli_num_rows($ic);
            $ret .= '<option value="' . $px['clientnumber'] . '" >' . $px['clientname'] . ' (' . $count . ')</option>';
        }
        $ret .= '</select>';
        echo ($ret);
        break;
}
