<?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();
    }
}
/* =========================
   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');
  }
}

/* =========================
   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);
            $liveRow = $GLOBALS['con']->query("SELECT COUNT(*) AS c FROM surveyor WHERE statuslive=1")->fetch_assoc();
            $live = (int)$liveRow['c'];
            if ($live >= $effective) {
                // force not live at insert if over capacity
                $_REQUEST['statuslive'] = "0";
                $newIsLive = false;
            }
        }

        // 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);

        // INSERT (kept as-is)
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `surveyor` VALUES(NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,NULL)") or die(mysqli_error($GLOBALS['con']));
        // NOTE: $apw is assumed to be defined upstream in your environment
        $stmt->bind_param(
            'issssssssssssssii',
            $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']
        );
        $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)) {
            boost_maybe_tag($con, $admin_con, $newId, false);
        }
        exit();

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

    // Previous state
    $prevLive = 0; $hadLiveBefore = false; $liveSinceVal = null;
    if ($stmt = $GLOBALS['con']->prepare("SELECT statuslive, live_since 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']);
            $liveSinceVal  = $row['live_since'] ?? null;
        }
        $stmt->close();
    }

    // Inputs
    $newStatusLive = (isset($_POST['statuslive']) && ($_POST['statuslive'] === "1" || $_POST['statuslive'] === "on")) ? 1 : 0;
    $_REQUEST['statuslive'] = $newStatusLive ? "1" : "0";
    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 = (int)$GLOBALS['con']->query("SELECT COUNT(*) c FROM surveyor WHERE statuslive=1")->fetch_assoc()['c'];
        if ($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()," : "";

    // 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`=?,
            {$liveSinceClause}
            id=id
        WHERE `id`=?
    ";
    $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param(
        'sssssssssssssii',
        $_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'],
        $surveyorId
    );
    $ok = $stmt->execute();
    $stmt->close();

    // Tag if 0->1 (boost tagging unchanged)
    if ($ok && $isFlipToLive && isset($admin_con)) {
        $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;
    if ($stmt = $con->prepare("SELECT statuslive, live_since 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']);
        }
        $stmt->close();
    }

    // Capacity guard (reinstate is 0->1)
    if (isset($admin_con)) {
        [$client_id, $base, $effective] = boost_effective_limit($con, $admin_con);
        $live = (int)$con->query("SELECT COUNT(*) c FROM surveyor WHERE statuslive=1")->fetch_assoc()['c'];
        if ($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)) {
        $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'] . "','','" . $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'] . "','','" . $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;
}
