<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
$_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']);


switch ($_REQUEST['FUNCTION']) {
    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;
        }
        $stmt = mysqli_query($GLOBALS['con'], "INSERT INTO `clientdetails` VALUES(
NULL,
'" . $_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'] . "', 
'" . $_REQUEST['vat_rate'] . "',
'" . $_REQUEST['commission'] . "', 
'" . $_REQUEST['comType'] . "',
'" . $_REQUEST['clientnotes'] . "',
'" . $_REQUEST['statuslive'] . "',
'" . $_REQUEST['agent_number'] . "',
'" . $_REQUEST['broker_number'] . "',
'" . $_REQUEST['account_handler'] . "',
'" . $_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'
)") or die(mysqli_error($GLOBALS['con']));

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



        if ($_REQUEST['pri_contact_email'] != "") {
            if (checkAddressBook($id, $_REQUEST['pri_contact_email']) == 0) {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES(
NULL,
'client',
'" . $id . "',
'" . $_REQUEST['clientname'] . "',
'" . $_REQUEST['pri_contact_name'] . "',
'',
'" . $_REQUEST['pri_contact_tel'] . "',
'" . $_REQUEST['pri_contact_mob'] . "',
'" . $_REQUEST['pri_contact_email'] . "',
'1',
'1'
)");
                $stmt->execute();
            }
        }

        if ($_REQUEST['sec_contact_email'] != "") {
            if (checkAddressBook($id, $_REQUEST['sec_contact_email']) == 0) {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES(
NULL,
'client',
'" . $id . "',
'" . $_REQUEST['clientname'] . "',
'" . $_REQUEST['sec_contact_name'] . "',
'',
'" . $_REQUEST['sec_contact_tel'] . "',
'" . $_REQUEST['sec_contact_mob'] . "',
'" . $_REQUEST['sec_contact_email'] . "',
'0',
'2',
'" . $_REQUEST['sec_contact_email'] . "'
)");
                $stmt->execute();
            }
        }

        exit();
        break;

    case "update":

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

        // toggle normalisers
        $onoff = function ($k) {
            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'] ?? '0') === '1') ? '1' : '0';

        // renewal options pack
        $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`='" . $_REQUEST['vat_rate'] . "',  
     `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'] . "', 
     `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'] . "'
     WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));

        // 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) {
                $stmt3 = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES(
            NULL,
            'client',
            '" . $_REQUEST['clientnumber'] . "',
            '" . $_REQUEST['clientname'] . "',
            '" . $_REQUEST['pri_contact_name'] . "',
            '',
            '" . $_REQUEST['pri_contact_tel'] . "',
            '" . $_REQUEST['pri_contact_mob'] . "',
            '" . $_REQUEST['pri_contact_email'] . "',
            '1',
            '1',
            'all'
            )") or die($e = mysqli_error($GLOBALS['con']));
                $stmt3->execute();
            }
        }

        if ($_REQUEST['sec_contact_email'] != "") {
            $check = checkAddressBook($_REQUEST['clientnumber'], $_REQUEST['sec_contact_email']);
            if ($check < 1) {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES(
            NULL,
            'client',
            '" . $_REQUEST['clientnumber'] . "',
            '" . $_REQUEST['clientname'] . "',
            '" . $_REQUEST['sec_contact_name'] . "',
            '',
            '" . $_REQUEST['billing_phone'] . "',
            'N/A',
            '" . $_REQUEST['sec_contact_email'] . "',
            '0',
            '2',
            'all'
            )") or die($e = mysqli_error($GLOBALS['con']));
                $stmt->execute();
            }
        }

        if ($_REQUEST['billing_email'] != "") {
            $check = checkAddressBook($_REQUEST['clientnumber'], $_REQUEST['billing_email']);
            if ($check < 1) {
                $stmt3 = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES(
            NULL,
            'client',
            '" . $_REQUEST['clientnumber'] . "',
            '" . $_REQUEST['clientname'] . "',
            '" . $_REQUEST['billing_name'] . "',
            '',
            '" . $_REQUEST['pri_contact_tel'] . "',
            '" . $_REQUEST['billing_phone'] . "',
            '" . $_REQUEST['billing_email'] . "',
            '1',
            '1',
            'billing'
            )") or die($e = mysqli_error($GLOBALS['con']));
                $stmt3->execute();
            }
        }

        // 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";
        function getSites($s, $c)
        {
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname`,`postcode` FROM `locations` WHERE `clientnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $s);
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();
            $rets = '<select class="form-control form-control-sm" name="locnumber" data-placeholder="Select Location">';
            $rets .= '<option value="">Select Location</option>';
            $count = mysqli_num_rows($res);
            while ($d = mysqli_fetch_array($res)) {
                if ($c == $d['locnumber']) {
                    $x = 'SELECTED';
                } else {
                    $x = '';
                }
                $rets .= '<option value="' . $d['locnumber'] . '" ' . $x . '>' . $d['postcode'] . ' - ' . $d['locname'] . '</option>';
            }

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

        $data = json_decode($_REQUEST['data'], true);


        if ($data['locnumber'] == "") {
            $access = 0;
        } else {
            $access = $data['locnumber'];
        }
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `client_users` VALUES(NULL,'" . $data['clientnumber'] . "','" . $data['name'] . "','" . $data['username'] . "',AES_ENCRYPT('" . $data['password'] . "','" . $data['username'] . "'),'" . $access . "','1')") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        $insert = mysqli_insert_id($GLOBALS['con']);
        $sites = getSites($_REQUEST['clientnumber'], $data['locnumber']);
        $ret = '<tr id="R' . $insert . '">';
        $ret .= '<td><input name="name" class="form-control  form-control-sm" value="' . $data['name'] . '"></td>';
        $ret .= '<td>' . $sites . '</td>';
        $ret .= '<td><input name="username" class="form-control form-control-sm" value="' . $data['username'] . '"></td>';
        $ret .= '<td><input class="form-control form-control-sm" type="text" name="password" value="' . $data['password'] . '" autocomplete="new-password" required  /></td>';
        $ret .= '<td class="text-end"><a class="btn btn-success btn-sm m-0 px-3 py-2 me-2" onclick="saveChange(\'' . $insert . '\')"><i class="fad fa-save"></i></a><a class="btn btn-danger btn-sm m-0 px-3 py-2"><i class="fad fa-trash" onclick="deleteUser(\'' . $insert . '\')"></i></a></td>';
        $ret .= '</tr>';
        echo $ret;

        break;

    case "updateClientUser":
        $data = json_decode($_REQUEST['data'], true);
        if ($data['locnumber'] == "") {
            $access = 0;
        } else {
            $access = $data['locnumber'];
        }

        $stmt = $GLOBALS['con']->prepare("UPDATE `client_users` SET
`name`='" . $data['name'] . "',
`username`='" . $data['username'] . "',
`password`=AES_ENCRYPT('" . $data['password'] . "','" . $data['username'] . "'),
`access`='" . $access . "'
WHERE `id`='" . $data['user'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        break;


    case "deleteClientUser":
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `client_users` WHERE `id`='" . $_REQUEST['user'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();

        break;
}