<?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');

if (empty($_SESSION['scheduleMode'])) {
    $stmt = $GLOBALS['con']->prepare("SELECT `smode` FROM `system` WHERE `id`='1' ") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $r = $stmt->get_result();
    $stmt->close();
    $i = mysqli_fetch_array($r);
    $_SESSION['scheduleMode'] = $i['smode'];
}

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'];
    }
}

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 . ', 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['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") {
        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'];
            }

            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;
}


if ($op == "login") {
    $_SESSION['user'] = "";
    $_SESSION['userid'] = "";
    $_SESSION['adminunique'] = "";
    $_SESSION['access'] = "";
    $_SESSION['usertype'] = "";

    $check = mysqli_query($GLOBALS['con'], "SELECT * FROM `" . $_REQUEST['t'] . "` WHERE `email`='" . $_REQUEST['u'] . "' AND `password`=AES_ENCRYPT('" . $_REQUEST['p'] . "', '" . $_REQUEST['u'] . "')") or die(mysqli_error($GLOBALS['con']));
    $num = mysqli_num_rows($check);

    if ($num < 1) {
        echo "0"; // Invalid credentials
    } else {
        $sql = mysqli_query($GLOBALS['con'], "SELECT * FROM `" . $_REQUEST['t'] . "` WHERE `email`='" . $_REQUEST['u'] . "' AND `password`=AES_ENCRYPT('" . $_REQUEST['p'] . "', '" . $_REQUEST['u'] . "')") or die(mysqli_error($GLOBALS['con']));
        $udata = mysqli_fetch_array($sql);

        if ($udata['access'] == 0 || $udata['statuslive']=='0') {
            echo "3"; // Account disabled
        } else {
            // 2FA gate for admins (new devices)
            if ($_REQUEST['t'] === '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 ($_REQUEST['t']) {
                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)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $s = $stmt->get_result();
    $stmt->close();
    $xd = mysqli_fetch_array($s);
    if ($type = "delivery_email") {
        return '<option value="' . $xd['pri_contact_email'] . '" SELECTED >[' . strtoupper($xd['clientname']) . '] ' . strtoupper($xd['pri_contact_name']) . '</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'];
    }
}

function writeLog($type, $string)
{
    $stmt = $GLOBALS['con']->prepare("INSERT `log` VALUES(NULL,'" . $_SESSION['usertype'] . "|" . $_SESSION['userid'] . "|" . $type . "',NULL,'" . $_SESSION['user'] . " " . $string . "','" . strtotime('now') . "') ") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $a = $stmt->get_result();
    $stmt->close();
}

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