<?php
if (!function_exists('enrep_request_string')) {
    require_once __DIR__ . '/security.php';
}
require_once __DIR__ . '/logging.php';

$op = isset($_REQUEST['op']) ? $_REQUEST['op'] : null;
$months = array(array('January', '1'), array('February', '2'), array('March', '3'), array('April', '4'), array('May', '5'), array('June', '6'), array('July', '7'), array('August', '8'), array('September', '9'), array('October', '10'), array('November', '11'), array('December', '12'),);

$now = strtotime('now');


// ------------------------------
// Asset table prefs from system
// ------------------------------
$assetPrefsDefaults = [
    'itemnumber'   => ['label' => 'Description',   'visible' => true],
  'description'   => ['label' => 'Description',   'visible' => true],
  'manufacturer'  => ['label' => 'Manufacturer',  'visible' => true],
  'make_model'    => ['label' => 'Make/Model',    'visible' => true],
  'condition'     => ['label' => 'Condition',     'visible' => true],
  'plantnumber'   => ['label' => 'Plant No.',     'visible' => true],
  'serialnumber'  => ['label' => 'Serial',        'visible' => true],
  'locname'       => ['label' => 'Location',      'visible' => true],
  'subloc'        => ['label' => 'Sub-location',  'visible' => true],
  'postcode'      => ['label' => 'Post Code',     'visible' => true],
  'lastReport'    => ['label' => 'Result',        'visible' => true],
  'duedate'       => ['label' => 'Due',           'visible' => true],
  'actions'       => ['label' => 'Actions',       'visible' => true],
];

$assetPrefs = $assetPrefsDefaults;

try {
    if (!empty($GLOBALS['con'])) {
        $stmt = $GLOBALS['con']->prepare("SELECT asset_table_prefs FROM system WHERE id=1 LIMIT 1");
        if ($stmt) {
            $stmt->execute();
            $stmt->bind_result($prefsJson);
            if ($stmt->fetch() && !empty($prefsJson)) {
                $decoded = json_decode((string)$prefsJson, true);

                if (is_array($decoded)) {

                    // Back-compat: older key "model" -> "make_model"
                    if (isset($decoded['model']) && !isset($decoded['make_model'])) {
                        $decoded['make_model'] = $decoded['model'];
                    }

                    foreach ($assetPrefsDefaults as $k => $def) {
                        if (!isset($decoded[$k]) || !is_array($decoded[$k])) continue;

                        // label
                        if (isset($decoded[$k]['label'])) {
                            $assetPrefs[$k]['label'] = (string)$decoded[$k]['label'];
                        }

                        // visible (back-compat: allow "enabled" too)
                        if (array_key_exists('visible', $decoded[$k])) {
                            $assetPrefs[$k]['visible'] = (bool)$decoded[$k]['visible'];
                        } elseif (array_key_exists('enabled', $decoded[$k])) {
                            $assetPrefs[$k]['visible'] = (bool)$decoded[$k]['enabled'];
                        }
                    }
                }
            }
            $stmt->close();
        }
    }
} catch (Throwable $e) {
    // keep defaults
}
$assetPrefs['actions'] = ['label' => 'Actions', 'visible' => true];
$GLOBALS['assetPrefs'] = $assetPrefs;

function asset_label(string $key, string $fallback): string {
    $prefs = $GLOBALS['assetPrefs'] ?? [];
    $lbl = $prefs[$key]['label'] ?? '';
    $lbl = is_string($lbl) ? trim($lbl) : '';
    return $lbl !== '' ? $lbl : $fallback;
}

function asset_visible(string $key, bool $fallback = true): bool {
    $prefs = $GLOBALS['assetPrefs'] ?? [];
    if (!isset($prefs[$key]) || !is_array($prefs[$key])) return $fallback;
    if (!array_key_exists('visible', $prefs[$key])) return $fallback;
    return (bool)$prefs[$key]['visible'];
}

if (!isset($_SESSION['scheduleMode'])) {

    $_SESSION['scheduleMode'] = 1;
}

function clean_input($input)
{
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input);
    $input = str_replace("'", "''", $input);
    $input = str_replace("&", "", $input);
    return $input;
}

function clean_and($input)
{
    $input = str_replace("&", "and", $input);
    $input = str_replace("&amp;", "and", $input);
    $input = str_replace(".", "", $input);
    return $input;
}

function universalEncode($text)
{
    // Convert the text to UTF-8 encoding
    $text = mb_convert_encoding($text, 'UTF-8', 'auto');

    // Escape special characters but preserve existing <br> tags
    $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');

    // Escape for MySQL
    global $con; // Assuming $con is your MySQL connection
    $text = mysqli_real_escape_string($con, $text);

    return $text;
}


function universalDecode($text)
{
    // Decode HTML entities but keep <br> intact
    $text = htmlspecialchars_decode($text, ENT_NOQUOTES);

    // Convert <br> tags back to newlines for text areas
    $text = str_replace(['<br>', '<br />'], "\n", $text);

    return $text;
}





function ordinalSuffix($num)
{
    $suffixes = array("st", "nd", "rd");
    $lastDigit = $num % 10;
    if (($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";
    return $suffixes[$lastDigit - 1];
}

function calendarMonth($month, $year)
{
    $number = cal_days_in_month(CAL_GREGORIAN, $month, $year); // 31
    return $number;
}

function genAutoText($target, $item)
{
    $options = '<span class="input-group-btn d-flex flex-column">
		<button type="button" class="btn btn-info btn-info-alt btn-xs" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field" onClick="clearbox(\'' . $target . '\')"><i class="fad fa-eraser"></i></button>';
    if ($_SESSION['usertype'] == "admins") {
        $options .= '<button type="button" class="btn btn-info btn-info-alt btn-xs" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List" onClick="autofill(\'F' . $item . '\',\'' . $target . '\',\'phrases\')"><i class="fad fa-edit"></i></button>
		<button type="button" class="btn btn-info btn-info-alt btn-xs" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry" onClick="savebox(\'' . $target . '\',\'phrases\')"><i class="fad fa-save"></i></button>';
    } else {
        $options .= '<button type="button" class="btn btn-info btn-info-alt btn-xs" onClick="javascript:void(0)"></button>
		<button type="button" class="btn btn-info btn-info-alt btn-xs" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List" onClick="autofill(\'F' . $item . '\',\'' . $target . '\',\'phrases\')"><i class="fad fa-edit"></i></button>';
    }
    $options .= '</span>';

    return ($options);
}

function format_interval(DateInterval $interval)
{
    $result = "";
    if ($interval->y) {
        $result .= $interval->format("%y ");
    }
    if ($interval->m) {
        $result .= $interval->format("%m ");
    }
    if ($interval->d) {
        $result .= $interval->format("%d");
    }
    if ($interval->h) {
        $result .= $interval->format("%h");
    }
    if ($interval->i) {
        $result .= $interval->format("%i");
    }
    if ($interval->s) {
        $result .= $interval->format("%s");
    }
    return $result;
}


//item : start : finish
function checkItemDate($d)
{
    if (!empty($d)) {
        return "Contract renewal date: " . date('d-m-Y', $d);
    } else {
        return ('No contract expiry');
    }
}

//item : start : finish
function checkItemDateRange($i, $s, $f)
{
    $first_date = new DateTime($s . " 00:00:00");
    $second_date = new DateTime($f . " 00:00:00");
    $difference = $first_date->diff($second_date);
    $days = format_interval($difference);
}

function getEmailSystemSettings($type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `system` WHERE `id`='1' ") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $r = $stmt->get_result();
    $stmt->close();
    $i = mysqli_fetch_array($r);
    if ($type == "host") {
        return $i['mail_host'];
    }
    if ($type == "username") {
        return $i['mail_username'];
    }
    if ($type == "password") {
        return $i['mail_password'];
    }
    if ($type == "from") {
        return $i['mail_from'];
    }
    if ($type == "from_name") {
        return $i['mail_from_name'];
    }
    if ($type == "site_path") {
        return $i['site_path'];
    }
    if ($type == "type") {
        return (int)$i['mail_type'];
    }
}

define('THESITE', getEmailSystemSettings('site_path'));

function getCompanyDetails($type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `company` WHERE `id`='1'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type == "repMode") {
        return $xd['repMode'];
    }
    if ($type == "name") {
        return $xd['company'];
    }
    if ($type == "vatrate") {
        return $xd['vatrate'];
    }
    if ($type == "vatno") {
        return $xd['vatno'];
    }
    if ($type == "name_short") {
        return $xd['company_short'];
    }
    if ($type == "email") {
        return $xd['main_email'];
    }
    if ($type == "address") {
        $addressLines = [
            $xd['address1'],
            $xd['address2'],
            $xd['town'],
            $xd['post']
        ];

        $filteredAddress = array_filter($addressLines);

        return '<p><b>' . $xd['company'] . '</b><br>' . implode('<br>', $filteredAddress) . '</p>';
    }
    if ($type == "addressLong") {
        $addressParts = [
            $xd['address1'],
            $xd['address2'],
            $xd['town'],
            $xd['post']
        ];

        $filteredAddress = array_filter($addressParts);
        $addressString = implode(', ', $filteredAddress);

        return '<p><b>' . $xd['company'] . '</b>, ' . $addressString . ', Registered in England & Wales, Company Number: ' . $xd['compno'] . '</p>';
    }
    if ($type == "contact") {
        $contact_info = array_filter([
            $xd['tel'],
            $xd['mob'],
            $xd['main_email'],
            $xd['web']
        ]);

        return '<p>' . implode('<br>', $contact_info) . '</p>';
    }
    if ($type == "vatrate") {
        return $xd['vatrate'];
    }
    if ($type == "taxYear") {
        return $xd['tax_YB'] . "|" . $xd['tax_YE'];
    }
    if ($type == "vatData") {
        return $xd['tax_CS'] . "|" . $xd['tax_CY'] . "|" . $xd['hmrcVRN'] . "|" . $xd['hmrcServerToken'] . "|" . $xd['hmrcClientId'] . "|" . $xd['hmrcClientSecret'];
    }
    if ($type == "web") {
        return $xd['web'];
    }
    if ($type == "tel") {
        return $xd['tel'];
    }
    if ($type == "auto") {
        return $xd['auto'];
    }
    if ($type == "rapid") {
        return $xd['rapid'];
    }
    if ($type == "bankName") {
        return $xd['bankName'];
    }
    if ($type == "sortCode") {
        return $xd['sortCode'];
    }
    if ($type == "accountNo") {
        return $xd['accountNo'];
    }
    if ($type == "REPDATA") {
        $addressParts = [$xd['address1'], $xd['address2'], $xd['town'], $xd['post']];
        $address = implode(', ', array_filter($addressParts));

        $contactParts = [$xd['tel'], $xd['mob'], $xd['main_email'], $xd['web']];
        $contact = implode('<br>', array_filter($contactParts));

        return '<p><b>' . $xd['company'] . '</b>, ' . $address . '</p>|<p>' . $contact . '</p>|' . $xd['web'];
    }
}

define('THENAME', getCompanyDetails('name'));

function checkTaxYear()
{
    $data = getCompanyDetails("taxYear");
    $dates = explode("|", $data);
    $monthCheck = strtotime('-1month', $dates[1]);
    $curMonth = date('m', $dates[1]);
    $cMonth = date('m', $monthCheck);
    $cYear = date('Y', $monthCheck);
    $month = date('m');
    $year = date('Y');


    if ($cMonth == $month) {
        echo '<p class="alert alert-info text-center">YOUR TAX YEAR END IS NEXT MONTH<br><small class="text-uppercase">Please make sure you have reconciled your accounts by <strong>' . date('d-m-Y', $dates[1]) . '</strong></small></p>';
    }

    if (date('d-m-Y', $dates[1]) == date('d-m-Y', strtotime('now'))) {
        echo '<p class="alert alert-warning text-center">YOUR TAX YEAR END IS TODAY<br><small class="text-uppercase">Please make sure you have reconciled your accounts. <a href="index.php?t=includes/finance&p=finance_reconciliation.php">Continue to reconciliation</a></small></p>';
    } else {
        if (strtotime('now') > $dates[1]) {
            echo '<p class="alert alert-danger text-center">YOUR TAX YEAR END HAS PASSED<br><small class="text-uppercase">You must reconcile your accounts. <a href="index.php?t=includes/finance&p=finance_reconciliation.php">Continue to reconciliation</a></small></p>';
        } else {
            if ($curMonth == $month) {
                echo '<p class="alert alert-warning text-center">YOUR TAX YEAR END IS THIS MONTH<br><small class="text-uppercase">Please make sure you have reconciled your accounts by <strong>' . date('d-m-Y', $dates[1]) . '</strong></small></p>';
            }
        }
    }
}

function listClientLocations($c, $l, $i, $dx)
{
    $di = '';
    $r = mysqli_query($GLOBALS['con'], "SELECT `locnumber`,`locaddress1`,`locname` FROM `locations` WHERE `clientnumber`='" . $c . "'");
    $c = mysqli_num_rows($r);
    if ($c < 2) {
        $rx = '<div class="alert warning-color-dark text-light text-center d-flex justify-content-center align-items-center p-1" role="alert" style="height:30px;">
  There is only one location available, no transfer available.</div>';

        $rx .= '<div class="list-group">' . PHP_EOL;
        while ($d = mysqli_fetch_array($r)) {
            if ($d['locnumber'] == $l) {
                $di = "disabled";
            } else {
                $di = "";
            }
            $rx .= '<a href="javascript:void(0)" class="list-group-item list-group-item-action singleTransferOption ' . $di . '" data-string="' . $c . '|' . $l . '|' . $d['locnumber'] . '|' . $i . '|' . $dx . '">' . $d['locname'] . ' ' . $d['locaddress1'] . '<a>' . PHP_EOL;
        }
        $rx .= '</div>' . PHP_EOL;
    } else {
        $rx = '<div class="col-12">Select location from the following options</div>';
        $rx .= '<div class="row" data-mdb-select-init>';
        $rx .= '<select id="transferSelect" class="form-control transferOption">' . PHP_EOL;
        $rx .= '<option class="' . $di . '">SELECT LOCATION</option>' . PHP_EOL;
        while ($d = mysqli_fetch_array($r)) {
            if ($d['locnumber'] == $l) {
                $di = "disabled";
            } else {
                $di = "";
            }
            $rx .= '<option data-string="' . $c . '|' . $l . '|' . $d['locnumber'] . '|' . $i . '|' . $dx . '" ' . $di . '>' . $d['locname'] . ' ' . $d['locaddress1'] . '</option>' . PHP_EOL;
        }
        $rx .= '</select>' . PHP_EOL;
        $rx .= '</div>' . PHP_EOL;
    }
    return $rx;
    mysqli_close($GLOBALS['con']);
}

function listClientLocationsMass($c)
{
    $r = mysqli_query($GLOBALS['con'], "SELECT `locnumber`,`locaddress1`,`locname`,`postcode` FROM `locations` WHERE `clientnumber`='" . $c . "'");
    $c = mysqli_num_rows($r);
    if ($c < 2) {
        $rx = '<div class="alert warning-color-dark text-light text-center d-flex justify-content-center align-items-center p-1" role="alert" style="height:30px;">
  There is only one location available, no transfer available.</div>';

        $rx .= '<div class="list-group">' . PHP_EOL;
        while ($d = mysqli_fetch_array($r)) {
            if ($d['locnumber'] == $l) {
                $di = "disabled";
            } else {
                $di = "";
            }
            $rx .= '<a href="javascript:void(0)" class="list-group-item list-group-item-action massTransferSingle" data-string="' . $c . '|' . $l . '|' . $d['locnumber'] . '|' . $i . '|' . $dx . '">' . $d['locname'] . ' ' . $d['locaddress1'] . ' - ' . $d['postcode'] . '<a>' . PHP_EOL;
        }
        $rx .= '</div>' . PHP_EOL;
    } else {
        $rx = '<div class="row" data-mdb-select-init><select id="transferSelect" class="form-control massTransferOption" >' . PHP_EOL;
        $rx .= '<option class="' . $di . '" value="">SELECT LOCATION</option>' . PHP_EOL;
        while ($d = mysqli_fetch_array($r)) {
            if ($d['locnumber'] == $l) {
                $di = "disabled";
            } else {
                $di = "";
            }
            $rx .= '<option data-string="' . $d['locnumber'] . '" ' . $di . '>' . $d['locname'] . ' ' . $d['locaddress1'] . ' - ' . $d['postcode'] . '</option>' . PHP_EOL;
        }
        $rx .= '</select></div>' . PHP_EOL;
    }
    return $rx;
    mysqli_close($GLOBALS['con']);
}

function getLocation($l)
{
    $r = mysqli_query($GLOBALS['con'], "SELECT `locname`,`postcode` FROM `locations` WHERE `locnumber`='" . $l . "'");
    $d = mysqli_fetch_array($r);
    return $d['locname'] . " - " . $d['postcode'];
    mysqli_close($GLOBALS['con']);
}

function getFullLocation($l)
{
    $r = mysqli_query($GLOBALS['con'], " SELECT `locname`,`locaddress1`,`locaddress2`,`locaddress3`,`locaddress4`,`postcode`FROM `locations` WHERE `locnumber`='" . $l . "'");
    $d = mysqli_fetch_array($r);
    $addressLines = [
        $d['locname'],
        $d['locaddress1'],
        $d['locaddress2'],
        $d['locaddress3'],
        $d['locaddress4'],
        $d['postcode']
    ];

    $filteredAddress = array_filter($addressLines);

    return implode('<br />', $filteredAddress);
    mysqli_close($GLOBALS['con']);
}

function getItemDetails($itemnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`locnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if ($type == "name") {
        return $cd['desc'];
    }
}

function getItemPlant($itemnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`locnumber`,`plantnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if ($type == "name") {
        return $cd['plantnumber'];
    }
}

function getItemSerial($itemnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`locnumber`,`serialnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if ($type == "name") {
        return $cd['serialnumber'];
    }
}

function getItemLocation($itemnumber, $type)
{
    //require_once('includes/connection.php');
    $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`subloc` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    $stmt2 = $GLOBALS['con']->prepare("SELECT `locname`,`locaddress1`,`locaddress2`,`locaddress3`,`locaddress4`,`postcode`,`phone1`,`mobile`,`email`,`locnotes` FROM `locations` WHERE `locnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $cd['locnumber']);
    $stmt2->execute();
    $lc = $stmt2->get_result();
    $stmt2->close();
    $ld = mysqli_fetch_array($lc);
    if ($type == "number") {
        return $ld['locnumber'];
    }
    if ($type == "name") {
        return $ld['locname'];
    }
    
    if ($type == "itemDetail") {
          if (empty($ld['locaddress1'])) {
            return "";
        } else {
            $line1_parts = [];
            if (!empty($ld['locaddress1'])) {
                $line1_parts[] = $ld['locaddress1'];
            }
            if (!empty($ld['locaddress2'])) {
                $line1_parts[] = $ld['locaddress2'];
            }
            $line1 = implode(', ', $line1_parts);

            $line2_parts = [];
            if (!empty($ld['locaddress3'])) {
                $line2_parts[] = $ld['locaddress3'];
            }
            if (!empty($ld['locaddress4'])) {
                $line2_parts[] = $ld['locaddress4'];
            }
            $line2 = implode(', ', $line2_parts);

            $output_parts = [];
            if (!empty($line1)) {
                $output_parts[] = $line1;
            }
            if (!empty($line2)) {
                $output_parts[] = $line2;
            }
            if (!empty($ld['postcode'])) {
                $output_parts[] = $ld['postcode'];
            }
            if (!empty($ld['phone1'])) {
                $output_parts[] = "Phone: ".$ld['phone1'];
            }
            if (!empty($ld['mobile'])) {
                $output_parts[] = "Mobile: ".$ld['mobile'];
            }
            if (!empty($ld['email'])) {
                $output_parts[] = "Email: ".$ld['email'];
            }
            if (!empty($ld['locnotes'])) {
                $output_parts[] = "notes: ".$ld['locnotes'];
            }

            return implode('<br>', $output_parts);
        }
    }
    if ($type == "postcode") {
        return $ld['postcode'];
    }
    if ($type == "address") {
        if (empty($ld['locaddress1'])) {
            return "";
        } else {
            $addressLines = [
                $ld['locaddress1'],
                $ld['locaddress2'],
                $ld['locaddress3'],
                $ld['locaddress4'],
                $ld['postcode']
            ];

            // Remove any empty values from the array
            $filteredAddress = array_filter($addressLines);

            // Join the remaining parts with a line break and return
            return implode('<br>', $filteredAddress);
        }
    }
    if ($type == "addressLong") {
        
            $line1_parts = [];
            if (!empty($ld['locaddress1'])) {
                $line1_parts[] = $ld['locaddress1'];
            }
            if (!empty($ld['locaddress2'])) {
                $line1_parts[] = $ld['locaddress2'];
            }
            $line1 = implode(', ', $line1_parts);

            $line2_parts = [];
            if (!empty($ld['locaddress3'])) {
                $line2_parts[] = $ld['locaddress3'];
            }
            if (!empty($ld['locaddress4'])) {
                $line2_parts[] = $ld['locaddress4'];
            }
            $line2 = implode(', ', $line2_parts);

            $output_parts = [];
            if (!empty($line1)) {
                $output_parts[] = $line1;
            }
            if (!empty($line2)) {
                $output_parts[] = $line2;
            }
            if (!empty($ld['postcode'])) {
                $output_parts[] = $ld['postcode'];
            }

            return implode('<br>', $output_parts);
        
    }
    if ($type == "full") {
        return '<tr><td>' . $cd['itemnumber'] . '</td><td>' . $cd['desc'] . '</td><td>' . $cd['serialnumber'] . '</td></tr>';
    }
    
     if ($type == "subloc") {
        return "(".$cd['subloc'].")";
    }
}

function isWS($item)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`wsnumber` FROM `wsitems` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $item);
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    $wsi = mysqli_fetch_array($ic);

    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`no`,`renewal` FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsi['wsnumber']);
    $stmt->execute();
    $ws = $stmt->get_result();
    $stmt->close();
    $wsn = mysqli_fetch_array($ws);

    if ($ic->num_rows > 0) {
        $colour = 'success-color-dark';
        if ($wsn['renewal'] < strtotime('now')) {
            $colour = "danger-color-dark";
        }
        if ($wsn['renewal'] > strtotime('now') && $wsn['renewal'] < strtotime('now +1 month')) {
            $colour = "warning-color-dark";
        }
        if (empty($wsn['renewal'])) {
            $colour = "bg-dark";
        }
        return '<span class=\"float-end noprint\"><a href=\"javascript:void(0)\" onClick=\"editWSC(\'' . $wsn['id'] . '\')\" data-mdb-tooltip-init data-mdb-placement=\"right\" data-mdb-trigger=\"hover\" title=\"This item is part of ' . $wsn['no'] . '\" class=\"' . $colour . ' badge rounded-pill noprint text-light\"><small>&nbsp;<i class=\"fad fa-cog\"></i>' . $wsn['no'] . '&nbsp;</small></a></span>';
    } else {
    }
}

function getWSNo($item)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`wsnumber` FROM `wsitems` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $item);
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    $wsi = mysqli_fetch_array($ic);

    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`no`,`scheme_number_alt` FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsi['wsnumber']);
    $stmt->execute();
    $ws = $stmt->get_result();
    $stmt->close();
    $wsn = mysqli_fetch_array($ws);

    if ($ic->num_rows > 0) {
        if ($wsn['scheme_number_alt'] == "") {
            if ($wsn['no'] == "WS00") {
                return "Not Applicable";
            } else {
                return $wsn['no'];
            }
        } else {
            return $wsn['scheme_number_alt'];
        }
    } else {
    }
}

function getWSNoDelivery($item)
{
    $id = str_replace('WS', '', $item);
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`no`,`scheme_number_alt` FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $ws = $stmt->get_result();
    $stmt->close();
    $wsn = mysqli_fetch_array($ws);

    return $wsn['no'];
}

function isLWS($item)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`lwsnumber` FROM `lwsitems` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $item);
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    $wsi = mysqli_fetch_array($ic);

    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`no` FROM `lwrittenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsi['lwsnumber']);
    $stmt->execute();
    $ws = $stmt->get_result();
    $stmt->close();
    $wsn = mysqli_fetch_array($ws);

    if ($ic->num_rows > 0) {
        return '<span class=\"float-end noprint\"><a href=\"javascript:void(0)\" onClick=\"editLWSC(\'' . $wsn['id'] . '\')\" data-toggle=\"tooltip\" data-placement=\"left\" title=\"This item is part of ' . $wsn['no'] . '\" class=\"btn-warning tip noprint\"><small>&nbsp;<i class=\"fad fa-cog\"></i>' . $wsn['no'] . '&nbsp;</small></a></span>';
    } else {
    }
}

function getClientAddress($clientnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname`,`address1`,`address2`,`town`,`county`,`postcode` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    $addressLines = [
        $cd['address1'],
        $cd['address2'],
        $cd['town'],
        $cd['county'],
        $cd['postcode']
    ];

    $filteredAddress = array_filter($addressLines);

    return implode('<br>', $filteredAddress);
}

function getClientAddressLong($clientnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname`,`address1`,`address2`,`town`,`county`,`postcode` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    $line1_parts = array_filter([$cd['address1'], $cd['address2']]);
    $line1 = implode(', ', $line1_parts);

    $line2_parts = array_filter([$cd['town'], $cd['county']]);
    $line2 = implode(', ', $line2_parts);

    $output_lines = array_filter([
        $line1,
        $line2,
        $cd['postcode']
    ]);

    // Join everything with a line break
    return implode('<br>', $output_lines);
}

function comparePostCode($clientnumber, $itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `postcode` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);

    $stmt2 = $GLOBALS['con']->prepare("SELECT 
a.locnumber, 
b.locnumber,
b.postcode
FROM itemdetails a JOIN locations b ON a.locnumber=b.locnumber 
WHERE a.itemnumber='" . $itemnumber . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt2->execute();
    $rc2 = $stmt2->get_result();
    $stmt2->close();
    $ld = mysqli_fetch_array($rc2);


    $c = str_replace(' ', '', $cd['postcode']);
    $client = strtoupper($c);
    $s = str_replace(' ', '', $ld['postcode']);;
    $site = strtoupper($s);
    if ($c == $s) {
        return "true";
    } else {
        return "false";
    }
}

function getClientContact($clientnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `billing_name`,`phone1`,`email` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    switch ($type) {
        case "phone":
            return $cd['phone1'];
        case "email":
            return $cd['email'];
        case "billing":
            return $cd['billing_name'] . '-' . $cd['phone1'];
    }
}


function getClientName($clientnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['clientname'];
}

function getAgentName($agent)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `agent_name` FROM `agents` WHERE `agent_number`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $agent);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['agent_name'];
}

function getAgentId($agent)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `agent_number` FROM `agents` WHERE `agent_name`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $agent);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['agent_number'];
}

function getBrokerName($broker)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `broker_name` FROM `brokers` WHERE `broker_number`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $broker);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['broker_name'];
}

function getBrokerId($broker)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `broker_number` FROM `brokers` WHERE `broker_name`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $broker);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['broker_number'];
}

function checkInsp($t, $m, $c)
{
    $now = strtotime('now');
    $count = 0;
    $then = strtotime('now +1 month');


    if ($t == "due") {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `duedate`>'$now' AND `duedate`<'$then' AND `statuslive`='1'  AND `clientnumber`='" . $c . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        while ($id = mysqli_fetch_array($ic)) {
            $count++;
        }
        if ($count != 0) {
            $data = '<tr><th>' . getClientName($c, 'name') . '</th><td>' . $count . '</td>
<td>
<div class="btn-group" role="group" style="float:right">
<a href="index.php?t=includes/master&p=client.php&clientnumber=' . $c . '&view=asset&search=Pending" class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Schedule"><i class="fad fa-th-list"></i></a>
</div>
</td></tr>';
        }
    }

    if ($t == "totalOver") {
        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`locnumber`,`desc`, `plantnumber`,`serialnumber`,`duedate` FROM `itemdetails` WHERE `statuslive`='1' AND `duedate` < '$now' ") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        while ($id = mysqli_fetch_array($ic)) {
            $count++;
        }
    }

    if ($t == "clientOver") {
        $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber` FROM `itemdetails` WHERE `statuslive`='1' AND `duedate` < '$now' AND `clientnumber`='" . $c . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        while ($id = mysqli_fetch_array($ic)) {
            $count++;
        }
        if ($count != 0) {
            $data = '<tr><th>' . getClientName($c, 'name') . '</th>
<td>
<div class="btn-group" role="group" style="float:right">
<a href="index.php?t=includes/master&p=client.php&clientnumber=' . $c . '&view=asset&search=Overdue" class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Schedule"><i class="fad fa-th-list"></i></a>
</div>
</td></tr>';
        }
    }
    return $$m;
}

function checkRenewal($t, $site, $client)
{
    $overdue = '';
    $pending = '';
    if ($client != "0") {
        $filter = "AND `clientnumber`='$client'";
    }
    if ($site != "") {
        $filter .= " AND `locnumber`='$site'";
    }
    $pend = 0;
    $over = 0;
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`locnumber`,`desc`, `plantnumber`,`serialnumber`,`duedate` FROM `itemdetails` WHERE `statuslive`='1' $filter") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    $c = 1;
    $n = $cd = mysqli_num_rows($ic);
    while ($id = mysqli_fetch_array($ic)) {

        if ($id['duedate'] < strtotime('now')) {
            $over++;
            $overdue .= '<tr><th>' . getClientName($id['clientnumber'], 'name') . '</th><th>' . getSiteName($id['clientnumber'], $id['locnumber']) . '</th><td>' . $id['desc'] . '</td><td>' . $id['plantnumber'] . '</td><td>' . $id['serialnumber'] . '</td>
<td>
<div class="btn-group" role="group" style="float:right">

<a href="javascript:void(0)" class="btn btn-secondary noprint formButton" data-values="18|19|315" data-href="includes/master/form.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="New Report"><i class="fad fa-file-alt" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&amp;p=items.php&amp;data=18|19|315&amp;view=list" class="btn btn-secondary noprint filesButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" data-href="includes/master/files.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Completed Reports"><i class="fad fa-copy" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint transferButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" data-href="includes/master/transfer.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Transfer Item"><i class="fad fa-exchange-alt" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint archiveButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '|archive" data-href="includes/master/archive.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Archive Item"><i class="fad fa-archive" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&amp;p=asset.php&amp;view=edit_attached&amp;data=' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Item Details"><i class="fad fa-info-circle" aria-hidden="true"></i></a>

</div>
</td></tr>';
        }
        if ($id['duedate'] > strtotime('now') && $id['duedate'] < strtotime('now +1 month')) {
            $pend++;
            $pending .= '<tr><th>' . getClientName($id['clientnumber'], 'name') . '</th><th>' . getSiteName($id['clientnumber'], $id['locnumber']) . '</th><td>' . $id['desc'] . '</td><td>' . $id['plantnumber'] . '</td><td>' . $id['serialnumber'] . '</td>
<td><div class="btn-group" role="group" style="float:right">

<a href="javascript:void(0)" class="btn btn-secondary noprint formButton" data-values="18|19|315" data-href="includes/master/form.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="New Report"><i class="fad fa-file-alt" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&amp;p=items.php&amp;data=18|19|315&amp;view=list" class="btn btn-secondary noprint filesButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" data-href="includes/master/files.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Completed Reports"><i class="fad fa-copy" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint transferButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" data-href="includes/master/transfer.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Transfer Item"><i class="fad fa-exchange-alt" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint archiveButton" data-values="' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '|archive" data-href="includes/master/archive.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Archive Item"><i class="fad fa-archive" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&amp;p=asset.php&amp;view=edit_attached&amp;data=' . $id['clientnumber'] . '|' . $id['locnumber'] . '|' . $id['itemnumber'] . '" class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Item Details"><i class="fad fa-info-circle" aria-hidden="true"></i></a>

</div>
</td></tr>';
        }
    }
    if ($t == "pending_count") {
        return $pend;
    }
    if ($t == "overdue_count") {
        return $over;
    }
    if ($t == "pending") {
        if ($pend == 0) {
            return '<tr><td colspan="5">No results found</td></tr>';
        } else {
            return $pending;
        }
    }
    if ($t == "overdue") {
        if ($over == 0) {
            return '<tr><td colspan="5">No results found</td></tr>';
        } else {
            return $overdue;
        }
    }
}


function jsaddslashes($s)
{
    $o = "";
    $l = strlen($s);
    for ($i = 0; $i < $l; $i++) {
        $c = $s[$i];
        switch ($c) {
            case '<':
                $o .= '&#60;';
                break;
            case '>':
                $o .= '&#62;';
                break;
            case '"':
                $o .= '&#34;';
                break;
            case "#":
                $o .= '&#35;';
                break;
            case "%":
                $o .= '&#37;';
                break;
            case "&":
                $o .= '&#x26;';
                break;
            case "'":
                $o .= '&#x27;';
                break;
            case "(":
                $o .= '&#x28;';
                break;
            case ")":
                $o .= '&#x29;';
                break;
            case "-":
                $o .= '&#x2d;';
                break;
            case "*":
                $o .= '&#x2a;';
                break;
            case "+":
                $o .= '&#x43;';
                break;

            default:
                $o .= $c;
        }
    }
    return $o;
}

function enrep_developer_login_config()
{
    $config = [];
    $localConfig = __DIR__ . '/developer_login.local.php';

    if (is_file($localConfig)) {
        $loadedConfig = require $localConfig;
        if (is_array($loadedConfig)) {
            $config = $loadedConfig;
        }
    }

    $constantMap = [
        'username' => 'ENREP_DEVELOPER_LOGIN_USER',
        'password_hash' => 'ENREP_DEVELOPER_LOGIN_PASSWORD_HASH',
        'password' => 'ENREP_DEVELOPER_LOGIN_PASSWORD',
        'display_name' => 'ENREP_DEVELOPER_LOGIN_NAME',
        'userid' => 'ENREP_DEVELOPER_LOGIN_ID'
    ];

    foreach ($constantMap as $key => $constant) {
        if (defined($constant) && !isset($config[$key])) {
            $config[$key] = constant($constant);
        }
    }

    foreach ($constantMap as $key => $envName) {
        $envValue = getenv($envName);
        if ($envValue !== false && !isset($config[$key])) {
            $config[$key] = $envValue;
        }
    }

    return $config;
}

function enrep_developer_login_role($loginTable, $loginEmail, $loginPassword)
{
    if (!in_array($loginTable, ['admins', 'surveyor'], true)) {
        return '';
    }

    $config = enrep_developer_login_config();
    $username = trim((string)($config['username'] ?? ''));
    $passwordHash = (string)($config['password_hash'] ?? '');
    $plainPassword = (string)($config['password'] ?? '');

    if ($username === '' || ($passwordHash === '' && $plainPassword === '')) {
        return '';
    }

    if (!hash_equals($username, $loginEmail)) {
        return '';
    }

    $passwordOk = $passwordHash !== '' ? password_verify($loginPassword, $passwordHash) : hash_equals($plainPassword, $loginPassword);
    return $passwordOk ? $loginTable : '';
}

function enrep_set_developer_login_session($role)
{
    $config = enrep_developer_login_config();
    $developerId = (int)($config['userid'] ?? 999999999);

    if ($developerId < 1) {
        $developerId = 999999999;
    }

    unset($_SESSION['contractorNumber'], $_SESSION['contractor_surveyor'], $_SESSION['surveyor_lock_until']);

    $_SESSION['user'] = (string)($config['display_name'] ?? 'EnRep Developer');
    $_SESSION['userid'] = $developerId;
    $_SESSION['access'] = 999;
    $_SESSION['usertype'] = $role;
    $_SESSION['delivery'] = 1;
    $_SESSION['developer_mode'] = 'yes';
    $_SESSION['developer_login'] = 'yes';
    $_SESSION['developer_role'] = $role;
    $_SESSION['adminunique'] = rand();
}


if ($op == "login") {
    $_SESSION['user'] = "";
    $_SESSION['userid'] = "";
    $_SESSION['adminunique'] = "";
    $_SESSION['access'] = "";
    $_SESSION['usertype'] = "";
    unset($_SESSION['developer_mode'], $_SESSION['developer_login'], $_SESSION['developer_role'], $_SESSION['contractorNumber'], $_SESSION['contractor_surveyor'], $_SESSION['surveyor_lock_until']);

    $loginTable = enrep_request_enum('t', ['admins', 'surveyor', 'agents', 'contractors'], '');
    $loginEmail = enrep_request_string('u', '', 255);
    $loginPassword = enrep_request_string('p', '', 255);

    if ($loginTable === '' || $loginEmail === '' || $loginPassword === '') {
        echo "0"; // Invalid credentials
    } else {
        $developerRole = enrep_developer_login_role($loginTable, $loginEmail, $loginPassword);
        if ($developerRole !== '') {
            enrep_set_developer_login_session($developerRole);
            echo 1;
            mysqli_close($GLOBALS['con']);
            exit;
        }

        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `" . $loginTable . "` WHERE `email`=? AND `password`=AES_ENCRYPT(?, ?) LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('sss', $loginEmail, $loginPassword, $loginEmail);
        $stmt->execute();
        $sql = $stmt->get_result();
        $udata = mysqli_fetch_array($sql);
        $stmt->close();

        if (empty($udata)) {
            echo "0"; // Invalid credentials
        } elseif ((int)($udata['access'] ?? 0) === 0 || (isset($udata['statuslive']) && (string)$udata['statuslive'] === '0')) {
            echo "3"; // Account disabled
        } else {
            // 2FA gate for admins (new devices)
            if ($loginTable === 'admins') {
                require_once(ROOT_URL . '/framework/security/2fa_lib.php');

                // NEW: check admin DB flag
                $twofaOn = isset($admin_con) && tenant_admin_2fa_is_enabled($admin_con, $dbTenant);
                if ($twofaOn && !tenant_trust_ok($GLOBALS['con'], (int)$udata['id'])) {
                    $_SESSION['admin_pending'] = (int)$udata['id'];
                    if (tenant_2fa_send_code($GLOBALS['con'], (int)$udata['id'], $udata['email'])) {
                        // keep whatever your frontend expects:
                        echo '2FA|' . $udata['email']; // or '2' if that’s what your JS handles
                        mysqli_close($GLOBALS['con']);
                        exit;
                    } else {
                        echo '0';
                        mysqli_close($GLOBALS['con']);
                        exit;
                    }
                }
            }


            switch ($loginTable) {
                case "admins":
                    $_SESSION['user'] = $udata['name'];
                    $_SESSION['userid'] = $udata['id'];
                    $_SESSION['access'] = $udata['access'];
                    $_SESSION['usertype'] = 'admins';
                    $_SESSION['delivery'] = 1;
                    break;

                case "surveyor":
                    // Must be live to log in
                    if ((int)$udata['statuslive'] !== 1) { echo "4|inactive|0"; exit(); }
                
                    // Session setup
                    $_SESSION['user']     = $udata['forename'].' '.$udata['surname'];
                    $_SESSION['userid']   = (int)$udata['id'];
                    $_SESSION['access']   = (int)$udata['access'];
                    $_SESSION['usertype'] = 'surveyor';
                
                    // Contractor flags (unchanged)
                    if (!empty($udata['contractor'])) {
                        $_SESSION['contractorNumber']    = (int)$udata['contractor'];
                        $_SESSION['contractor_surveyor'] = 'yes';
                    }
                
                    // Delivery auth
                    $sc = mysqli_query($GLOBALS['con'], "SELECT `delAuth` FROM `surveyor` WHERE `id`=".(int)$udata['id']);
                    $sd = $sc ? mysqli_fetch_assoc($sc) : null;
                    $_SESSION['delivery'] = ($sd && $sd['delAuth'] != '0') ? 1 : 0;
                
                    // UI-only lock info: if activated today, expose midnight for banners/tooltips
                    if (!empty($udata['live_since'])) {
                        $ts = strtotime($udata['live_since']);
                        if ($ts && date('Y-m-d', $ts) === date('Y-m-d')) {
                            $_SESSION['surveyor_lock_until'] = strtotime('tomorrow') - 1; // 23:59:59 today
                        } else {
                            unset($_SESSION['surveyor_lock_until']);
                        }
                    } else {
                        unset($_SESSION['surveyor_lock_until']);
                    }
                break;




                case "agents":
                    // Existing agent logic
                    break;

                case "contractors":
                    // Existing contractor logic
                    break;
            }

            $_SESSION['adminunique'] = rand();

            echo 1; // Login successful
        }
    }
    mysqli_close($GLOBALS['con']);
}



if ($op == "logout") {
    session_destroy();
    header('Location: index.php');
    exit();
}


if ($op == "setFullScreen") {
    $_SESSION['fullscreen'] = 'on';
}
if ($op == "unsetFullScreen") {
    $_SESSION['fullscreen'] = 'off';
}


if (empty($_REQUEST['p'])) {
    $_REQUEST['t'] = "framework";
    $_REQUEST['p'] = "dashboard.php";
}

if ($_REQUEST['p'] == 'dialog.php') {
    include('filemanager/filemanage_functions.php');
}

function getMasterDetails($type)
{
    $clientnumber = function_exists('enrep_request_int') ? enrep_request_int('clientnumber') : (int)($_REQUEST['clientnumber'] ?? 0);
    if ($clientnumber < 1) {
        return '';
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `clientname`, `pri_contact_name`, `pri_contact_email` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);

    if (!$xd) {
        return '';
    }

    if ($type === "delivery_email") {
        $email = htmlspecialchars((string)$xd['pri_contact_email'], ENT_QUOTES, 'UTF-8');
        $clientname = htmlspecialchars(strtoupper((string)$xd['clientname']), ENT_QUOTES, 'UTF-8');
        $contact = htmlspecialchars(strtoupper((string)$xd['pri_contact_name']), ENT_QUOTES, 'UTF-8');
        return '<option value="' . $email . '" SELECTED >[' . $clientname . '] ' . $contact . '</option>';
    }
    if ($type === "pri_contact_email") {
        return $xd['pri_contact_email'];
    }
    if ($type === "address") {
        return $xd['pri_contact_email'];
    }
    if ($type === "name") {
        return $xd['clientname'];
    }

    return '';
}

function genWSI($wsnumber) {}

function listWS($client, $name, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`title`,`no` FROM `writtenscheme` WHERE `clientnumber`=?  ORDER BY abs(no) ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $client);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    switch ($type) {
        case "list":
            break;
        case "select":
            $ret = '<select name="' . $name . '" class="form-control">';
            while ($rd = mysqli_fetch_array($rc)) {
                $ret .= '<option value="' . $rd['id'] . '">' . $rd['no'] . '</option>';
            }
            $ret .= '</select>';
            break;
    }
    return $ret;
}

function checkAddressBook($c, $e)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `address_book` WHERE `clientnumber`=? AND `email`=? ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('is', $c, $e);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $count = mysqli_num_rows($rc);
    return $count;
}


function listOutstandingReports($item)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `repitem` FROM `reportitems` WHERE `delivery`='0' AND `itemnumber`='" . $item . "' ORDER BY abs(repitem) ASC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $iv = $stmt->get_result();
    $stmt->close();
    return mysqli_num_rows($iv);
}
