<?php 
require_once __DIR__ . '/../../functions/logging.php';

$originalRequestKeys = array_fill_keys(array_keys($_REQUEST), true);
$tenantRequest = (string)($_REQUEST['tenant'] ?? '');

if ($tenantRequest !== '' && file_exists('../../../' . $tenantRequest . '/config.php')) {
    require_once('../../../' . $tenantRequest . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
$_REQUEST['address1'] = mysqli_real_escape_string($con, $_REQUEST['address1'] ?? '');
$_REQUEST['address2'] = mysqli_real_escape_string($con, $_REQUEST['address2'] ?? '');
$_REQUEST['town'] = mysqli_real_escape_string($con, $_REQUEST['town'] ?? '');
$_REQUEST['county'] = mysqli_real_escape_string($con, $_REQUEST['county'] ?? '');
$_REQUEST['billing1'] = mysqli_real_escape_string($con, $_REQUEST['billing1'] ?? '');
$_REQUEST['billing2'] = mysqli_real_escape_string($con, $_REQUEST['billing2'] ?? '');
$_REQUEST['billing_town'] = mysqli_real_escape_string($con, $_REQUEST['billing_town'] ?? '');
$_REQUEST['billing_county'] = mysqli_real_escape_string($con, $_REQUEST['billing_county'] ?? '');

$_REQUEST['clientname'] = mysqli_real_escape_string($con, $_REQUEST['clientname'] ?? '');
$_REQUEST['pri_contact_name'] = mysqli_real_escape_string($con, $_REQUEST['pri_contact_name'] ?? '');
$_REQUEST['billing_name'] = mysqli_real_escape_string($con, $_REQUEST['billing_name'] ?? '');
$_REQUEST['clientnotes'] = mysqli_real_escape_string($con, $_REQUEST['clientnotes'] ?? '');
$_REQUEST['account_handler'] = mysqli_real_escape_string($con, $_REQUEST['account_handler'] ?? '');

$_REQUEST['account_manager_name'] = mysqli_real_escape_string($con, $_REQUEST['account_manager_name'] ?? '');
$_REQUEST['account_manager_email'] = mysqli_real_escape_string($con, $_REQUEST['account_manager_email'] ?? '');
$_REQUEST['account_manager_phone'] = mysqli_real_escape_string($con, $_REQUEST['account_manager_phone'] ?? '');
$_REQUEST['account_manager_notes'] = mysqli_real_escape_string($con, $_REQUEST['account_manager_notes'] ?? '');
$_REQUEST['iu_base_rate'] = mysqli_real_escape_string($con, $_REQUEST['iu_base_rate'] ?? '');
$_REQUEST['iu_admin_fee'] = mysqli_real_escape_string($con, $_REQUEST['iu_admin_fee'] ?? '');

function clientNullableDecimalSql($value): string
{
    $value = trim((string)$value);
    return $value === '' ? 'NULL' : "'" . $value . "'";
}

function clientInsertAddressBook(int $clientnumber, string $clientname, string $firstName, string $lastName, string $phone1, string $phone2, string $email, int $auto, int $indexer, string $assignmentType): void
{
    $role = '';
    $siteNumbers = '';
    $type = 'client';
    $stmt = $GLOBALS['con']->prepare("
        INSERT INTO `address_book`
        (`type`,`clientnumber`,`cname`,`firstName`,`lastName`,`role`,`phone1`,`phone2`,`email`,`site_numbers`,`auto`,`indexer`,`assignment_type`)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param(
        'sissssssssiis',
        $type,
        $clientnumber,
        $clientname,
        $firstName,
        $lastName,
        $role,
        $phone1,
        $phone2,
        $email,
        $siteNumbers,
        $auto,
        $indexer,
        $assignmentType
    );
    $stmt->execute();
    $stmt->close();
}

function getSitesClient($s, $c)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname`,`postcode`,`locaddress1`,`locaddress2`,`locaddress3`,`locaddress4` FROM `locations` WHERE `clientnumber`=?  AND statuslive=1") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $s);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $ret = '<select class="form-control form-control-sm" data-mdb-select-init data-mdb-size="sm" data-mdb-filter="true" id="locnumber" name="locnumber" data-placeholder="Select Location">';
    $ret .= '<option value="">Select Location</option>';
    $count = mysqli_num_rows($res);
    while ($d = mysqli_fetch_array($res)) {
        if ($c == $d['locnumber']) {
            $s = 'SELECTED';
        } else {
            $s = '';
        }
        $ret .= '<option value="' . $d['locnumber'] . '" ' . $s . '>' . $d['locname'] . '</option>';
    }

    $ret .= '</select>';
    return $ret;
}

$clientFunction = (string)($_REQUEST['FUNCTION'] ?? '');
enrep_log_request_completion('clients', 'FUNCTION', [
    'archive' => ['action' => 'archived', 'message' => 'Archived client', 'entity_type' => 'clientdetails'],
    'activate' => ['action' => 'activated', 'message' => 'Activated client', 'entity_type' => 'clientdetails'],
    'insert' => ['action' => 'created', 'message' => 'Created client', 'entity_type' => 'clientdetails'],
    'update' => ['action' => 'updated', 'message' => 'Updated client', 'entity_type' => 'clientdetails'],
    'cleandata_itemdetails' => ['action' => 'asset_data_cleaned', 'message' => 'Cleaned client asset data', 'entity_type' => 'clientdetails'],
    'setRenew' => ['action' => 'renewal_updated', 'message' => 'Updated client renewal settings', 'entity_type' => 'clientdetails'],
    'saveClientUser' => ['action' => 'portal_user_created', 'message' => 'Created client portal user', 'entity_type' => 'client_access'],
    'updateClientUser' => ['action' => 'portal_user_updated', 'message' => 'Updated client portal user', 'entity_type' => 'client_access'],
    'deleteClientUser' => ['action' => 'portal_user_deleted', 'message' => 'Deleted client portal user', 'entity_type' => 'client_access'],
]);

switch ($clientFunction) {
    default:
        break;

    case "archive":
        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `statuslive`='0' WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'");
        $stmt->execute();

        echo "success";
        break;

    case "activate":
        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `statuslive`='1' WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'");
        $stmt->execute();
        //
        //genSchedule($_REQUEST['clientnumber']);
        echo "success";
        break;

    case "insert":
        $renewOptions = array();
        $renewOptions['notice'] = $_REQUEST['A1'];
        $renewOptions['inotice'] = $_REQUEST['A1i'];
        $renewOptions['renewalSet'] = $_REQUEST['A1d'];
        if ($_REQUEST['A2'] == "on") {
            $renewOptions['schedule'] = 1;
        } else {
            $renewOptions['schedule'] = 0;
        }
        if ($_REQUEST['A3'] == "on") {
            $renewOptions['plant'] = 1;
        } else {
            $renewOptions['plant'] = 0;
        }
        if ($_REQUEST['A4'] == "on") {
            $renewOptions['inspection'] = 1;
        } else {
            $renewOptions['inspection'] = 0;
        }
        if ($_REQUEST['A5'] == "on") {
            $renewOptions['nag'] = 1;
            $renewOptions['R1'] = $_REQUEST['A6'];
            $renewOptions['R2'] = $_REQUEST['A7'];
        } else {
            $renewOptions['nag'] = 0;
            $renewOptions['R1'] = '';
            $renewOptions['R2'] = '';
        }
        if ($_REQUEST['A8'] == "on") {
            $renewOptions['lapse'] = 1;
            $renewOptions['lapseDays'] = $_REQUEST['A9'];
        } else {
            $renewOptions['lapse'] = 0;
            $renewOptions['lapseDays'] = '';
        }

        $renews = json_encode($renewOptions);

        if (!empty($_SESSION['contractorNumber'])) {
            $contractorNumber = $_SESSION['contractorNumber'];
        } else {
            $contractorNumber = '0';
        }
        if ($_REQUEST['statuslive'] == "on") {
            $_REQUEST['statuslive'] = "1";
        }
        if ($_REQUEST['statuslive'] == "off" || $_REQUEST['statuslive'] == "") {
            $_REQUEST['statuslive'] = "0";
        }
        if ($_REQUEST['autoRenew'] == "on") {
            $_REQUEST['autoRenew'] = "1";
        }
        if ($_REQUEST['autoRenew'] == "off" || $_REQUEST['autoRenew'] == "") {
            $_REQUEST['autoRenew'] = "0";
        }
        if ($_REQUEST['contractMode'] == "on") {
            $_REQUEST['contractMode'] = "1";
        }
        if ($_REQUEST['contractMode'] == "off" || $_REQUEST['contractMode'] == "") {
            $_REQUEST['contractMode'] = "0";
        }
        if ($_REQUEST['agent_number'] == "") {
            $_REQUEST['agent_number'] = 0;
        }
        if ($_REQUEST['broker_number'] == "") {
            $_REQUEST['broker_number'] = 0;
        }
        $iuBaseRateSql = clientNullableDecimalSql($_REQUEST['iu_base_rate']);
        $iuAdminFeeSql = clientNullableDecimalSql($_REQUEST['iu_admin_fee']);

        $stmt = mysqli_query($GLOBALS['con'], "INSERT INTO `clientdetails` (
`clientname`,`address1`,`address2`,`town`,`county`,`postcode`,`phone1`,`phone2`,`mobile`,`fax`,`email`,
`pri_contact_name`,`pri_contact_position`,`pri_contact_tel`,`pri_contact_mob`,`pri_contact_email`,
`sec_contact_name`,`sec_contact_position`,`sec_contact_tel`,`sec_contact_mob`,`sec_contact_email`,
`rate_per_hour`,`iu_base_rate`,`iu_admin_fee`,`vat_rate`,`commission`,`comType`,`clientnotes`,`statuslive`,
`agent_number`,`broker_number`,`account_handler`,`account_manager_name`,`account_manager_email`,
`account_manager_phone`,`account_manager_notes`,`contract_number`,`incepton_date`,`term_years`,
`billing_name`,`billing1`,`billing2`,`billing_town`,`billing_county`,`billing_postcode`,`billing_email`,
`billing_phone`,`renewal_date`,`renewal_status`,`delivery_pref`,`delivery_type`,`autoRenew`,`renewOptions`,
`contractMode`,`contractor`,`systemMode`,`clientMode`,`ancillary`
) VALUES (
'" . $_REQUEST['clientname'] . "',
'" . $_REQUEST['address1'] . "',
'" . $_REQUEST['address2'] . "', 
'" . $_REQUEST['town'] . "',
'" . $_REQUEST['county'] . "',
'" . $_REQUEST['postcode'] . "',
'" . $_REQUEST['phone1'] . "',
'" . $_REQUEST['phone2'] . "',
'" . $_REQUEST['mobile'] . "', 
'" . $_REQUEST['fax'] . "',
'" . $_REQUEST['email'] . "',
'" . $_REQUEST['pri_contact_name'] . "',
'" . $_REQUEST['pri_contact_position'] . "', 
'" . $_REQUEST['pri_contact_tel'] . "',
'" . $_REQUEST['pri_contact_mob'] . "',
'" . $_REQUEST['pri_contact_email'] . "',
'" . $_REQUEST['sec_contact_name'] . "',
'" . $_REQUEST['sec_contact_position'] . "', 
'" . $_REQUEST['sec_contact_tel'] . "',
'" . $_REQUEST['sec_contact_mob'] . "',
'" . $_REQUEST['sec_contact_email'] . "', 
'" . $_REQUEST['rate_per_hour'] . "', 
" . $iuBaseRateSql . ",
" . $iuAdminFeeSql . ",
NULL,
'" . $_REQUEST['commission'] . "', 
'" . $_REQUEST['comType'] . "',
'" . $_REQUEST['clientnotes'] . "',
'" . $_REQUEST['statuslive'] . "',
'" . $_REQUEST['agent_number'] . "',
'" . $_REQUEST['broker_number'] . "',
'" . $_REQUEST['account_handler'] . "',
'" . $_REQUEST['account_manager_name'] . "',
'" . $_REQUEST['account_manager_email'] . "',
'" . $_REQUEST['account_manager_phone'] . "',
'" . $_REQUEST['account_manager_notes'] . "',
'" . $_REQUEST['contract_number'] . "',
'" . strtotime($_REQUEST['incepton_date']) . "', 
'" . $_REQUEST['term_years'] . "',
'" . $_REQUEST['billing_name'] . "', 
'" . $_REQUEST['billing1'] . "',
'" . $_REQUEST['billing2'] . "',
'" . $_REQUEST['billing_town'] . "',
'" . $_REQUEST['billing_county'] . "',
'" . $_REQUEST['billing_postcode'] . "', 
'" . $_REQUEST['billing_email'] . "',
'" . $_REQUEST['billing_phone'] . "',
'" . strtotime($_REQUEST['renewal_date']) . "', 
'" . $_REQUEST['renewal_status'] . "',
'" . $_REQUEST['delivery_pref'] . "',
'" . $_REQUEST['delivery_type'] . "',
'" . $_REQUEST['autoRenew'] . "',
'" . $renews . "',
'" . $_REQUEST['contractMode'] . "',
'" . $contractorNumber . "',
'0',
'0',
'" . $_REQUEST['ancillary'] . "'
)") or die(mysqli_error($GLOBALS['con']));

        $id = mysqli_insert_id($GLOBALS['con']);

        if (isset($_REQUEST['iu_base_rate'])) {
            $stmtIuRate = @$GLOBALS['con']->prepare("UPDATE `clientdetails` SET `iu_base_rate`=?, `iu_admin_fee`=? WHERE `clientnumber`=?");
            if ($stmtIuRate) {
                $iuBaseRate = trim((string)$_REQUEST['iu_base_rate']) === '' ? null : (string)$_REQUEST['iu_base_rate'];
                $iuAdminFee = trim((string)($_REQUEST['iu_admin_fee'] ?? '')) === '' ? null : (string)$_REQUEST['iu_admin_fee'];
                $stmtIuRate->bind_param('ssi', $iuBaseRate, $iuAdminFee, $id);
                $stmtIuRate->execute();
                $stmtIuRate->close();
            }
        }

        echo $id;



        if ($_REQUEST['pri_contact_email'] != "") {
            if (checkAddressBook($id, $_REQUEST['pri_contact_email']) == 0) {
                clientInsertAddressBook($id, $_REQUEST['clientname'], $_REQUEST['pri_contact_name'], '', $_REQUEST['pri_contact_tel'], $_REQUEST['pri_contact_mob'], $_REQUEST['pri_contact_email'], 1, 1, 'all');
            }
        }

        if ($_REQUEST['sec_contact_email'] != "") {
            if (checkAddressBook($id, $_REQUEST['sec_contact_email']) == 0) {
                clientInsertAddressBook($id, $_REQUEST['clientname'], $_REQUEST['sec_contact_name'], '', $_REQUEST['sec_contact_tel'], $_REQUEST['sec_contact_mob'], $_REQUEST['sec_contact_email'], 0, 2, 'all');
            }
        }

        exit();
        break;

    case "update":

        // session contractor number
        $contractorNumber = !empty($_SESSION['contractorNumber']) ? $_SESSION['contractorNumber'] : '0';
        $clientnumberForUpdate = (int)($_REQUEST['clientnumber'] ?? 0);

        $stmtExisting = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmtExisting->bind_param('i', $clientnumberForUpdate);
        $stmtExisting->execute();
        $existingClientResult = $stmtExisting->get_result();
        $stmtExisting->close();
        $existingClient = mysqli_fetch_array($existingClientResult);

        if (!$existingClient) {
            die('Client not found');
        }

        $adminClientSections = (($_SESSION['access'] ?? 0) == 1 || ($_SESSION['access'] ?? 0) == 999);
        $preserveMissingClientField = function ($key, $column = null) use ($originalRequestKeys, $existingClient, $con) {
            if (!isset($originalRequestKeys[$key])) {
                $column = $column ?: $key;
                $_REQUEST[$key] = mysqli_real_escape_string($con, (string)($existingClient[$column] ?? ''));
            }
        };

        foreach ([
            'clientname', 'address1', 'address2', 'town', 'county', 'postcode', 'phone1', 'phone2', 'mobile', 'fax', 'email',
            'pri_contact_name', 'pri_contact_position', 'pri_contact_tel', 'pri_contact_mob', 'pri_contact_email',
            'sec_contact_name', 'sec_contact_position', 'sec_contact_tel', 'sec_contact_mob', 'sec_contact_email',
            'rate_per_hour', 'commission', 'comType', 'clientnotes', 'agent_number', 'broker_number', 'account_handler',
            'account_manager_name', 'account_manager_email', 'account_manager_phone', 'account_manager_notes',
            'contract_number', 'term_years', 'billing_name', 'billing1', 'billing2', 'billing_town', 'billing_county',
            'billing_postcode', 'billing_phone', 'billing_email', 'renewal_status', 'delivery_pref', 'delivery_type',
            'systemMode', 'clientMode', 'ancillary', 'iu_base_rate', 'iu_admin_fee'
        ] as $clientField) {
            $preserveMissingClientField($clientField);
        }

        if (!isset($originalRequestKeys['incepton_date'])) {
            $_REQUEST['incepton_date'] = !empty($existingClient['incepton_date']) ? date('d-m-Y', (int)$existingClient['incepton_date']) : '';
        }
        if (!isset($originalRequestKeys['renewal_date'])) {
            $_REQUEST['renewal_date'] = !empty($existingClient['renewal_date']) ? date('d-m-Y', (int)$existingClient['renewal_date']) : '';
        }

        // toggle normalisers
        $onoff = function ($k) use ($originalRequestKeys, $existingClient, $adminClientSections) {
            if (!isset($originalRequestKeys[$k]) && ($k === 'autoRenew' || $k === 'contractMode') && !$adminClientSections) {
                return (string)($existingClient[$k] ?? '0');
            }
            if (!isset($originalRequestKeys[$k]) && $k === 'statuslive') {
                return (string)($existingClient[$k] ?? '0');
            }
            return (($_REQUEST[$k] ?? '') === 'on') ? '1' : '0';
        };
        $_REQUEST['statuslive']   = $onoff('statuslive');
        $_REQUEST['autoRenew']    = $onoff('autoRenew');
        $_REQUEST['contractMode'] = $onoff('contractMode');

        // clientMode is radio 0/1
        $_REQUEST['clientMode'] = (($_REQUEST['clientMode'] ?? (string)($existingClient['clientMode'] ?? '0')) === '1') ? '1' : '0';

        // renewal options pack
        if (!$adminClientSections && !isset($originalRequestKeys['A1']) && !isset($originalRequestKeys['A2'])) {
            $renews = (string)($existingClient['renewOptions'] ?? '');
        } else {
            $renewOptions = [];
            $renewOptions['notice']      = $_REQUEST['A1']  ?? '';
            $renewOptions['inotice']     = $_REQUEST['A1i'] ?? '';
            $renewOptions['renewalSet']  = $_REQUEST['A1d'] ?? '';
            $renewOptions['schedule']    = (($_REQUEST['A2'] ?? '') === 'on') ? 1 : 0;
            $renewOptions['plant']       = (($_REQUEST['A3'] ?? '') === 'on') ? 1 : 0;
            $renewOptions['inspection']  = (($_REQUEST['A4'] ?? '') === 'on') ? 1 : 0;
            $renewOptions['nag']         = (($_REQUEST['A5'] ?? '') === 'on') ? 1 : 0;
            $renewOptions['R1']          = ($renewOptions['nag'] === 1) ? ($_REQUEST['A6'] ?? '') : '';
            $renewOptions['R2']          = ($renewOptions['nag'] === 1) ? ($_REQUEST['A7'] ?? '') : '';
            $renewOptions['lapse']       = (($_REQUEST['A8'] ?? '') === 'on') ? 1 : 0;
            $renewOptions['lapseDays']   = ($renewOptions['lapse'] === 1) ? ($_REQUEST['A9'] ?? '') : '';
            $renews = json_encode($renewOptions);
        }

        // safe timestamps
        $ts_inception = !empty($_REQUEST['incepton_date']) ? strtotime($_REQUEST['incepton_date']) : 0;
        $ts_renewal   = !empty($_REQUEST['renewal_date'])  ? strtotime($_REQUEST['renewal_date'])  : 0;

        // main clientdetails update (kept in legacy style to avoid regressions)
        $stmt = mysqli_query($GLOBALS['con'], "UPDATE `clientdetails` SET 
     `clientname`='" . $_REQUEST['clientname'] . "', 
     `address1`='" . $_REQUEST['address1'] . "',  
     `address2`='" . $_REQUEST['address2'] . "', 
     `town`='" . $_REQUEST['town'] . "',  
     `county`='" . $_REQUEST['county'] . "',  
     `postcode`='" . $_REQUEST['postcode'] . "', 
     `phone1`='" . $_REQUEST['phone1'] . "', 
     `phone2`='" . $_REQUEST['phone2'] . "',  
     `mobile`='" . $_REQUEST['mobile'] . "', 
     `fax`='" . $_REQUEST['fax'] . "', 
     `email`='" . $_REQUEST['email'] . "',  
     `pri_contact_name`='" . $_REQUEST['pri_contact_name'] . "', 
     `pri_contact_position`='" . $_REQUEST['pri_contact_position'] . "', 
     `pri_contact_tel`='" . $_REQUEST['pri_contact_tel'] . "',  
     `pri_contact_mob`='" . $_REQUEST['pri_contact_mob'] . "', 
     `pri_contact_email`='" . $_REQUEST['pri_contact_email'] . "', 
     `sec_contact_name`='" . $_REQUEST['sec_contact_name'] . "', 
     `sec_contact_position`='" . $_REQUEST['sec_contact_position'] . "', 
     `sec_contact_tel`='" . $_REQUEST['sec_contact_tel'] . "',  
     `sec_contact_mob`='" . $_REQUEST['sec_contact_mob'] . "',  
     `sec_contact_email`='" . $_REQUEST['sec_contact_email'] . "',  
     `rate_per_hour`='" . $_REQUEST['rate_per_hour'] . "', 
     `vat_rate`=NULL,  
     `commission`='" . $_REQUEST['commission'] . "', 
     `comType`='" . $_REQUEST['comType'] . "', 
     `clientnotes`='" . $_REQUEST['clientnotes'] . "', 
     `statuslive`='" . $_REQUEST['statuslive'] . "',  
     `agent_number`='" . $_REQUEST['agent_number'] . "', 
     `broker_number`='" . $_REQUEST['broker_number'] . "', 
     `account_handler`='" . $_REQUEST['account_handler'] . "', 
     `account_manager_name`='" . $_REQUEST['account_manager_name'] . "', 
     `account_manager_email`='" . $_REQUEST['account_manager_email'] . "', 
     `account_manager_phone`='" . $_REQUEST['account_manager_phone'] . "', 
     `account_manager_notes`='" . $_REQUEST['account_manager_notes'] . "', 
     `contract_number`='" . $_REQUEST['contract_number'] . "',
     `incepton_date`='" . $ts_inception . "', 
     `term_years`='" . $_REQUEST['term_years'] . "', 
     `billing_name`='" . $_REQUEST['billing_name'] . "', 
     `billing1`='" . $_REQUEST['billing1'] . "',  
     `billing2`='" . $_REQUEST['billing2'] . "',  
     `billing_town`='" . $_REQUEST['billing_town'] . "',  
     `billing_county`='" . $_REQUEST['billing_county'] . "', 
     `billing_postcode`='" . $_REQUEST['billing_postcode'] . "',  
     `billing_phone`='" . $_REQUEST['billing_phone'] . "',  
     `billing_email`='" . $_REQUEST['billing_email'] . "',  
     `renewal_date`='" . $ts_renewal . "',  
     `renewal_status`='" . $_REQUEST['renewal_status'] . "',  
     `delivery_pref`='" . $_REQUEST['delivery_pref'] . "', 
     `delivery_type`='" . $_REQUEST['delivery_type'] . "', 
     `autoRenew`='" . $_REQUEST['autoRenew'] . "', 
     `renewOptions`='" . $renews . "', 
     `contractMode`='" . $_REQUEST['contractMode'] . "', 
     `contractor`='" . $contractorNumber . "',
     `systemMode`='" . $_REQUEST['systemMode'] . "',
     `clientMode`='" . $_REQUEST['clientMode'] . "',
     `ancillary`='" . $_REQUEST['ancillary'] . "'
     WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));

        if (isset($_REQUEST['iu_base_rate'])) {
            $stmtIuRate = @$GLOBALS['con']->prepare("UPDATE `clientdetails` SET `iu_base_rate`=?, `iu_admin_fee`=? WHERE `clientnumber`=?");
            if ($stmtIuRate) {
                $clientnumberForIuRate = (int)$_REQUEST['clientnumber'];
                $iuBaseRate = trim((string)$_REQUEST['iu_base_rate']) === '' ? null : (string)$_REQUEST['iu_base_rate'];
                $iuAdminFee = trim((string)($_REQUEST['iu_admin_fee'] ?? '')) === '' ? null : (string)$_REQUEST['iu_admin_fee'];
                $stmtIuRate->bind_param('ssi', $iuBaseRate, $iuAdminFee, $clientnumberForIuRate);
                $stmtIuRate->execute();
                $stmtIuRate->close();
            }
        }

        // agent/broker propagation
        if ($_REQUEST['agent_number'] == "0") {
            $stmt2 = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `agent`='0', `broker`='" . $_REQUEST['broker_number'] . "' WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
            $stmt2->execute();
        }
        if ($_REQUEST['broker_number'] == "0") {
            $stmt2 = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `agent`='" . $_REQUEST['agent_number'] . "', `broker`='0' WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
            $stmt2->execute();
        }

        // address_book inserts (kept as-is)
        if ($_REQUEST['pri_contact_email'] != "") {
            $check = checkAddressBook($_REQUEST['clientnumber'], $_REQUEST['pri_contact_email']);
            if ($check < 1) {
                clientInsertAddressBook((int)$_REQUEST['clientnumber'], $_REQUEST['clientname'], $_REQUEST['pri_contact_name'], '', $_REQUEST['pri_contact_tel'], $_REQUEST['pri_contact_mob'], $_REQUEST['pri_contact_email'], 1, 1, 'all');
            }
        }

        if ($_REQUEST['sec_contact_email'] != "") {
            $check = checkAddressBook($_REQUEST['clientnumber'], $_REQUEST['sec_contact_email']);
            if ($check < 1) {
                clientInsertAddressBook((int)$_REQUEST['clientnumber'], $_REQUEST['clientname'], $_REQUEST['sec_contact_name'], '', $_REQUEST['billing_phone'], 'N/A', $_REQUEST['sec_contact_email'], 0, 2, 'all');
            }
        }

        if ($_REQUEST['billing_email'] != "") {
            $check = checkAddressBook($_REQUEST['clientnumber'], $_REQUEST['billing_email']);
            if ($check < 1) {
                clientInsertAddressBook((int)$_REQUEST['clientnumber'], $_REQUEST['clientname'], $_REQUEST['billing_name'], '', $_REQUEST['pri_contact_tel'], $_REQUEST['billing_phone'], $_REQUEST['billing_email'], 1, 1, 'billing');
            }
        }

        // contractor upsert/clear based on clientMode
        $clientId   = (int)($_REQUEST['clientnumber'] ?? 0);
        $clientMode = (int)($_REQUEST['clientMode'] ?? 0);

        if ($clientId > 0) {
            if ($clientMode === 1) {
                // gather fields
                $g = function ($k) {
                    return trim($_REQUEST[$k] ?? '');
                };
                $c = [
                    'cont_company'       => $g('cont_company'),
                    'cont_company_short' => $g('cont_company_short'),
                    'cont_address1'      => $g('cont_address1'),
                    'cont_address2'      => $g('cont_address2'),
                    'cont_town'          => $g('cont_town'),
                    'cont_county'        => $g('cont_county'),
                    'cont_post'          => $g('cont_post'),
                    'cont_tel'           => $g('cont_tel'),
                    'cont_fax'           => $g('cont_fax'),
                    'cont_main_email'    => $g('cont_main_email'),
                    'cont_finance_email' => $g('cont_finance_email'),
                    'cont_web'           => $g('cont_web'),
                    'cont_vatno'         => $g('cont_vatno'),
                    'cont_compno'        => $g('cont_compno')
                ];

                // require at least a company name to store
                if ($c['cont_company'] !== '') {
                    // exists?
                    $exists = 0;
                    $chk = $GLOBALS['con']->prepare("SELECT COUNT(*) FROM contract_companies WHERE client_id=?");
                    $chk->bind_param('i', $clientId);
                    $chk->execute();
                    $chk->bind_result($exists);
                    $chk->fetch();
                    $chk->close();

                    if ($exists > 0) {
                        $sql = "UPDATE contract_companies SET
                        cont_company=?, cont_company_short=?, cont_address1=?, cont_address2=?, cont_town=?, cont_county=?, cont_post=?,
                        cont_tel=?, cont_fax=?, cont_main_email=?, cont_finance_email=?, cont_web=?, cont_vatno=?, cont_compno=?,
                        updated_at=NOW()
                        WHERE client_id=?";
                        $s = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
                        // 14 strings + 1 int
                        $s->bind_param(
                            'ssssssssssssssi',
                            $c['cont_company'],
                            $c['cont_company_short'],
                            $c['cont_address1'],
                            $c['cont_address2'],
                            $c['cont_town'],
                            $c['cont_county'],
                            $c['cont_post'],
                            $c['cont_tel'],
                            $c['cont_fax'],
                            $c['cont_main_email'],
                            $c['cont_finance_email'],
                            $c['cont_web'],
                            $c['cont_vatno'],
                            $c['cont_compno'],
                            $clientId
                        );
                        if (!$s->execute()) {
                            echo 'contract_update_fail: ' . mysqli_error($GLOBALS['con']);
                            exit;
                        }
                        $s->close();
                    } else {
                        $sql = "INSERT INTO contract_companies
                      (client_id, cont_company, cont_company_short, cont_address1, cont_address2, cont_town, cont_county, cont_post,
                       cont_tel, cont_fax, cont_main_email, cont_finance_email, cont_web, cont_vatno, cont_compno, created_at, updated_at)
                      VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())";
                        $s = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
                        // 1 int + 14 strings
                        $s->bind_param(
                            'issssssssssssss',
                            $clientId,
                            $c['cont_company'],
                            $c['cont_company_short'],
                            $c['cont_address1'],
                            $c['cont_address2'],
                            $c['cont_town'],
                            $c['cont_county'],
                            $c['cont_post'],
                            $c['cont_tel'],
                            $c['cont_fax'],
                            $c['cont_main_email'],
                            $c['cont_finance_email'],
                            $c['cont_web'],
                            $c['cont_vatno'],
                            $c['cont_compno']
                        );
                        if (!$s->execute()) {
                            echo 'contract_insert_fail: ' . mysqli_error($GLOBALS['con']);
                            exit;
                        }
                        $s->close();
                    }
                }
            } else {
                // clear contractor record when switching off
                $del = $GLOBALS['con']->prepare("DELETE FROM contract_companies WHERE client_id=?") or die(mysqli_error($GLOBALS['con']));
                $del->bind_param('i', $clientId);
                if (!$del->execute()) {
                    echo 'contract_delete_fail: ' . mysqli_error($GLOBALS['con']);
                    exit;
                }
                $del->close();
            }
        }

        echo "success";
        exit();
        break;



    case "cleandata_itemdetails":

        $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`duedate` FROM `itemdetails`") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        while ($dd = mysqli_fetch_array($s)) {
            $d = $dd['duedate'];
            if ($d == "00:00:00.000000") {
                $d2 = str_replace('00:00:00.000000', 'Not Known', $d);
            } else {
                $d3 = str_replace(' 00:00:00', '', $d);
                $e = "";
                $e = explode("-", $d3);
                $d4 = strtotime($e[2] . "-" . $e[1] . "-" . $e[0]);
                $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `duedate`=? WHERE `itemnumber`='" . $dd['itemnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('i', $d4);
                $stmt->execute();
                $stmt->close();
            }
        }

        $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`currdate` FROM `itemdetails`") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        while ($dd = mysqli_fetch_array($s)) {
            if ($dd['currdate'] == "Not Known") {
            } else {
                $e = "";
                $e = explode("/", $dd['currdate']);
                $f2 = strtotime($e[0] . "-" . $e[1] . "-" . $e[2]);
                $x = mysqli_query($GLOBALS['con'], "UPDATE `itemdetails` SET `currdate`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('ii', $f2, $dd['itemnumber']);
                $stmt->execute();
                $stmt->close();
            }
        }
        break;

    case "setRenew":
        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `renewal_status`='ACTIVE', `renewal_date`='" . $now . "' WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $stmt->close();
        echo "1";
        break;


    case "getEmailData":
        $stmt = $GLOBALS['con']->prepare("SELECT `clientname`,`pri_contact_name`,`pri_contact_email`,`contract_number` FROM `clientdetails` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        $emailData = mysqli_fetch_array($s);
        echo json_encode($emailData);
        break;

    case "saveClientUser":
        $data = json_decode($_REQUEST['data'], true);

        $clientnumber = (int)($data['clientnumber'] ?? 0);
        $name = trim($data['name'] ?? '');
        $username = trim($data['username'] ?? '');
        $password = trim($data['password'] ?? '');
        $accessAll = (int)($data['access_all'] ?? 0);
        $siteAccess = $data['site_access'] ?? [];

        if ($clientnumber < 1 || $name === '' || $username === '' || $password === '') {
            echo "error";
            exit;
        }

        if (!is_array($siteAccess)) {
            $siteAccess = [];
        }

        $cleanSites = [];
        foreach ($siteAccess as $siteId) {
            $siteId = (int)$siteId;
            if ($siteId > 0 && !in_array($siteId, $cleanSites, true)) {
                $cleanSites[] = $siteId;
            }
        }

        if ($accessAll === 1) {
            $access = 0;
            $accessMulti = null;
            $summary = 'Full schedule access';
        } else {
            if (count($cleanSites) < 1) {
                echo "error";
                exit;
            }

            $access = (int)$cleanSites[0];
            $accessMulti = json_encode($cleanSites, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            if (count($cleanSites) === 1) {
                $summary = trim(strip_tags(getSitesClient($clientnumber, $cleanSites[0])));
            } else {
                $summary = count($cleanSites) . ' sites selected';
            }
        }

        $stmt = $GLOBALS['con']->prepare("
                INSERT INTO `client_users`
                (`clientnumber`, `name`, `username`, `password`, `access`, `access_multi`, `statuslive`)
                VALUES (?, ?, ?, AES_ENCRYPT(?, ?), ?, ?, 1)
            ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param(
            'issssis',
            $clientnumber,
            $name,
            $username,
            $password,
            $username,
            $access,
            $accessMulti
        );
        $stmt->execute();
        $stmt->close();

        $insert = mysqli_insert_id($GLOBALS['con']);

        $clientAccessCompanyName = (string)getCompanyDetails('name');
        $clientAccessCompanyWeb = (string)getCompanyDetails('web');
        $emailMessage =
            '<p>Your access details for ' . htmlspecialchars($clientAccessCompanyName, ENT_QUOTES) . ' client portal are as follows:</p>' .
            '<p><strong>URL:</strong> <a href="' . htmlspecialchars($clientAccessCompanyWeb, ENT_QUOTES) . '">' . htmlspecialchars($clientAccessCompanyWeb, ENT_QUOTES) . '</a></p>' .
            '<p><strong>Username:</strong> ' . htmlspecialchars($username, ENT_QUOTES) . '<br>' .
            '<strong>Password:</strong> ' . htmlspecialchars($password, ENT_QUOTES) . '</p>';

        $email_values = [
            'clientNumber' => (string)$clientnumber,
            'clientName' => $name,
            'primaryEmail' => $username,
            'secondaryEmail' => '',
            'subject' => $clientAccessCompanyName . ' Client portal access',
            'message' => $emailMessage,
            'filePath' => '',
            'fileName' => '',
        ];

        $email64_values = base64_encode(json_encode($email_values, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

        $ret = '<tr id="R' . $insert . '">';
        $ret .= '<td><input name="name" class="form-control form-control-sm" value="' . htmlspecialchars($name, ENT_QUOTES) . '"></td>';

        $ret .= '<td>
                <div class="d-flex justify-content-between align-items-center gap-2">
                    <span id="accessSummary_' . $insert . '" class="small">' . htmlspecialchars($summary, ENT_QUOTES) . '</span>
                    <button type="button"
                            class="btn btn-warning btn-sm px-2 access-manage-button"
                            onclick="openAccessManager(\'' . $insert . '\')"
                            data-mdb-tooltip-init
                            data-mdb-placement="top"
                            data-mdb-trigger="hover"
                            title="Manage site access">
                        <i class="fad fa-map-marker-alt"></i>
                    </button>
                </div>
                <input type="hidden" name="access_all_hidden" value="' . ($accessAll === 1 ? '1' : '0') . '">
                <input type="hidden" name="site_access_hidden" value="' . htmlspecialchars(json_encode($cleanSites, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES) . '">
            </td>';

        $ret .= '<td><input name="username" class="form-control form-control-sm" value="' . htmlspecialchars($username, ENT_QUOTES) . '"></td>';
        $ret .= '<td><input class="form-control form-control-sm" type="text" name="password" value="' . htmlspecialchars($password, ENT_QUOTES) . '" autocomplete="new-password" required></td>';

        $ret .= '<td class="text-end">
                <button type="button"
                        class="btn btn-success btn-sm m-0"
                        onclick="saveChange(\'' . $insert . '\')"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Save changes">
                    <i class="fad fa-save"></i>
                </button>
    
                <button type="button"
                        class="btn btn-danger btn-sm m-0"
                        onclick="deleteUser(\'' . $insert . '\')"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Delete user">
                    <i class="fad fa-trash"></i>
                </button>
    
                <button type="button"
                        class="btn btn-info btn-sm m-0 accessButton"
                        data-values="' . htmlspecialchars($email64_values, ENT_QUOTES) . '"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Email user login details">
                    <i class="fad fa-envelope"></i>
                </button>
            </td>';

        $ret .= '</tr>';

        echo $ret;
        exit;

    case "updateClientUser":
        $data = json_decode($_REQUEST['data'], true);

        $user = (int)($data['user'] ?? 0);
        $name = trim($data['name'] ?? '');
        $username = trim($data['username'] ?? '');
        $password = trim($data['password'] ?? '');
        $accessAll = (int)($data['access_all'] ?? 0);
        $siteAccess = $data['site_access'] ?? [];

        if ($user < 1 || $name === '' || $username === '' || $password === '') {
            echo "error";
            exit;
        }

        if (!is_array($siteAccess)) {
            $siteAccess = [];
        }

        $cleanSites = [];
        foreach ($siteAccess as $siteId) {
            $siteId = (int)$siteId;
            if ($siteId > 0 && !in_array($siteId, $cleanSites, true)) {
                $cleanSites[] = $siteId;
            }
        }

        if ($accessAll === 1) {
            $access = 0;
            $accessMulti = null;
        } else {
            if (count($cleanSites) < 1) {
                echo "error";
                exit;
            }

            $access = (int)$cleanSites[0];
            $accessMulti = json_encode($cleanSites, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }

        $stmt = $GLOBALS['con']->prepare("
                UPDATE `client_users` SET
                    `name`=?,
                    `username`=?,
                    `password`=AES_ENCRYPT(?, ?),
                    `access`=?,
                    `access_multi`=?
                WHERE `id`=?
            ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param(
            'ssssisi',
            $name,
            $username,
            $password,
            $username,
            $access,
            $accessMulti,
            $user
        );
        $stmt->execute();
        $stmt->close();

        echo "success";
        exit;

    case "deleteClientUser":
        $user = (int)($_REQUEST['user'] ?? 0);

        if ($user < 1) {
            echo "error";
            exit;
        }

        $stmt = $GLOBALS['con']->prepare("DELETE FROM `client_users` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $user);
        $stmt->execute();
        $stmt->close();

        echo "success";
        exit;
}
