<?php require_once(ROOT_URL . '/includes/asset/asset_functions.php');

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`=? ") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['clientnumber']);
$stmt->execute();
$cr = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($cr);
$email_values = [
    0 => $cd['clientnumber'], //client
    1 => $cd['clientname'], //type
    2 => $cd['email'], //recipient
    3 => '', //subject
    4 => '', //message
    5 => '', //attachment
    6 => '' //source
];
$email64_values = base64_encode(json_encode($email_values));
?>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset"><?= addslashes($cd['clientname']) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active">Edit Client</li>'
</script>
<div class="d-flex w-100 flex-wrap justify-content-end">

    <?php if ($cd['clientMode'] == 1) { ?>
    <div class="note note-warning mb-3 me-auto">
        <strong>Notice:</strong> This client's reports are set to use <a href="#contractDetailsContainer"
           data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
           title="Jump to alternative branding">alternative
            branding</a>.
    </div>
    <?php } ?>

    <div class="d-flex flex-wrap mt-0 mb-4 justify-content-end">


        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset"
           class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="bottom"
           data-mdb-trigger="hover" totitle="hover" title="View Schedule"><i class="fad fa-th-list"></i></a>


        <a id="newSite"
           href="index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= getClientName($_REQUEST['clientnumber']) ?>"
           class="btn btn-secondary me-2" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
           title="View Locations"><i class="fad fa-building" aria-hidden="true"></i></a>

        <a id="phone" href="tel:<?= $cd['phone1'] ?>" class="btn btn-secondary noprint me-2" data-mdb-tooltip-init
           data-mdb-placement="bottom" data-mdb-trigger="hover" title="Phone Client"><i class="fad fa-phone"></i></a>

        <?php if ($_SESSION['access'] == 1 || $_SESSION['access'] == 999) { ?>
        <a href="index.php?t=includes/finance&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>"
           class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="bottom"
           data-mdb-trigger="hover" totitle="hover" title="Client Finances"><i class="fad fa-file-chart-line"></i></a>
        <?php } ?>

        <?php if (!filter_var($cd['email'], FILTER_VALIDATE_EMAIL) === false) { ?>
        <a href="javascript:void(0)" class="btn btn-secondary noprint emailButton me-2"
           data-values="<?= $email64_values ?>" data-href="<?= ROOT_URL ?>/includes/master/mailer.php"
           data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover"
           title="Email Client"><i class="fad fa-envelope"></i></a>
        <?php } ?>

        <a href="index.php?t=includes/client&p=client_addressbook.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>"
           class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="bottom"
           data-mdb-trigger="hover" totitle="hover" title="Address Book"><i class="fad fa-address-book"></i></a>

        <?php if ($cd['statuslive'] == 1) { ?>
        <a href="javascript:void(0)" class="btn btn-secondary noprint archiveButton me-2" data-mdb-tooltip-init
           data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Archive Client" data-
           onClick="archiveClient('<?= $_REQUEST['clientnumber'] ?>')"><i class="fad fa-archive"></i></a>
        <?php } ?>

        <?php if ($cd['statuslive'] == 0) { ?>
        <a href="javascript:void(0)" class="btn btn-secondary noprint archiveButton me-2" data-mdb-tooltip-init
           data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Activate Client"
           onClick="activateClient('<?= $_REQUEST['clientnumber'] ?>')"><i class="fad fa-upload"></i></a>
        <?php } ?>

        <a href="javascript:void(0)" class="btn btn-secondary noprint " data-mdb-tooltip-init
           data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Print"
           onclick="printDetails()"><i class="fad fa-print"></i></a>

    </div>
</div>

<form id="clientForm" class="form-horizontal">

    <div class="row row-cols-1 row-cols-md-2 g-4">
        <div class="col-md-9 mb-4">
            <?php require_once(ROOT_URL . '/forms/elements/client_details.frm'); ?>
        </div>
        <div class="col-md-3 mb-4">
            <?php
            $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname` FROM `locations` WHERE `clientnumber`=? AND `statuslive`='1'") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['clientnumber']);
            $stmt->execute();
            $lc = $stmt->get_result();
            $stmt->close();
            $ln = mysqli_num_rows($lc);
            $items = 0;
            while ($ld = mysqli_fetch_array($lc)) {
                $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc` FROM `itemdetails` WHERE `locnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('i', $ld['locnumber']);
                $stmt->execute();
                $ic = $stmt->get_result();
                $stmt->close();
                $in = mysqli_num_rows($ic);
                $items = $items + $in;
            }
            $stmt = $GLOBALS['con']->prepare("SELECT locnumber, COUNT(locnumber) AS occurrence FROM itemdetails GROUP BY locnumber") or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            while ($cdx = mysqli_fetch_array($cc)) {
                //echo $cd['locnumber']." | ".$cd['occurrence']."<br>";	
            }
            ?>

            <div class="card card-cascade mb-4">
                <div class="card-header">Client Type</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="systemMode" id="typeSelectEng"
                                       value="0" <?php if ($cd['systemMode'] == '0') {
                                                    echo "CHECKED";
                                                } ?> />
                                <label class="form-check-label" for="typeSelectEng">Engineering</label>
                            </div>

                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="systemMode" id="typeSelectEle"
                                       value="1" <?php if ($cd['systemMode'] == '1') {
                                                    echo "CHECKED";
                                                } ?> />
                                <label class="form-check-label" for="typeSelectEle">Electrical</label>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4">
                        <div class="col">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="clientMode" id="clientSelectDirect"
                                       value="0" <?php if ($cd['clientMode'] == '0') {
                                                    echo "CHECKED";
                                                } ?> />
                                <label class="form-check-label" for="clientSelectDirect">Direct</label>
                            </div>

                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="clientMode" id="clientSelectContract"
                                       value="1" <?php if ($cd['clientMode'] == '1') {
                                                    echo "CHECKED";
                                                } ?> />
                                <label class="form-check-label" for="clientSelectContract">Contract</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card card-cascade mb-4">
                <div class="card-header">Overview</div>
                <div class="card-body">
                    <a class="list-group-item list-group-item-action lead"
                       href="index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $cd['clientname'] ?>"><small>Locations:
                            <?= $ln ?></small></a>
                    <a class="list-group-item list-group-item-action lead"
                       href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset"><small>Items:
                            <?= $items ?></small></a>
                    <a class="list-group-item list-group-item-action lead"
                       href="javascript:void(0)"><small><?= checkItemDate($cd['renewal_date']) ?></small></a>

                </div>
            </div>

            <?php
            require_once(ROOT_URL . '/forms/elements/client_ws.php');
            require_once(ROOT_URL . '/forms/elements/client_loler_ws.php');
            ?>
        </div>

        <?php
        require_once(ROOT_URL . '/forms/elements/client_contacts.frm');
        if ($_SESSION['access'] == 1 || $_SESSION['access'] == 999) {
            require_once(ROOT_URL . '/forms/elements/client_billing.frm');
            require_once(ROOT_URL . '/forms/elements/client_other.frm');
            require_once(ROOT_URL . '/forms/elements/client_renewals.frm');
        }
        ?>





        <input type="hidden" name="clientnumber" value="<?= $_REQUEST['clientnumber'] ?>">
        <input type="hidden" name="FUNCTION" id="function" value="update">

        <input id="btn_update" type="submit" name="submit" value="Update" style="display:none">

</form>
<?php
require_once(ROOT_URL . '/forms/elements/client_additional.frm');
require_once(ROOT_URL . '/forms/elements/client_access.frm');
require_once(ROOT_URL . '/forms/elements/client_image.frm');

?>

</div>
<?php
$clientId = (int)($_REQUEST['clientnumber'] ?? 0);

$contract = [
    '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' => ''
];

if ($clientId > 0) {
    $sql = "SELECT 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
          FROM contract_companies WHERE client_id = ? LIMIT 1";
    $s = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
    $s->bind_param('i', $clientId);
    $s->execute();
    $r = $s->get_result();
    if ($row = $r->fetch_assoc()) {
        $contract = array_merge($contract, $row);
    }
    $s->close();
}

$e = static function ($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
};
?>

<div id="contractDetailsContainer" class="<?= $cd['clientMode'] == '1' ? '' : 'd-none' ?> mt-4 bg-dark rounded p-4">
    <div class="note note-light mb-3">
        <strong>Contract Company Details:</strong> Complete these details to allow full branding for your contractor
        when producing reports for them. <br><span class="text-warning"><i
               class="fad fa-solid fa-triangle-exclamation"></i> All
            PDF reports generated when contractor is enabled will
            not contain any of your company information.</span>
    </div>
    <div class="card mb-4">
        <div class="card-header">Company Details</div>
        <div class="card-body">
            <div class="row">
                <div class="col-12 col-md-6">

                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="company">Company Name</label>
                        <div class="col-12 col-md-9"><input id="cont_company" name="cont_company" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_company'] ?>" required>
                        </div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="company_short">Short Name</label>
                        <div class="col-12 col-md-9"><input id="cont_company_short" name="cont_company_short"
                                   type="text" placeholder="" class="form-control "
                                   value="<?= $contract['cont_company_short'] ?>" required></div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="address1">Address 1</label>
                        <div class="col-12 col-md-6"><input id="cont_address1" name="cont_address1" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_address1'] ?>" required>
                        </div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="address2">Address 2</label>
                        <div class="col-12 col-md-6"><input id="cont_address2" name="cont_address2" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_address2'] ?>"></div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="town">Town</label>
                        <div class="col-12 col-md-6"><input id="cont_town" name="cont_town" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_town'] ?>"></div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="county">County</label>
                        <div class="col-12 col-md-6"><input id="cont_county" name="cont_county" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_county'] ?>"></div>
                    </div>
                    <div class="form-group row mb-3">
                        <label class="col-12 col-md-2 control-label" for="post">Post Code</label>
                        <div class="col-12 col-md-6"><input id="cont_post" name="cont_post" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_post'] ?>"></div>
                    </div>

                </div>


                <div class="col-12 col-md-6">

                    <div class="form-group row mb-3">
                        <label class="col-md-2 control-label" for="co_tel">Tel</label>
                        <div class="col-md-4"><input id="cont_tel" name="cont_tel" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_tel'] ?>" required></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-2 control-label" for="fax">Fax</label>
                        <div class="col-md-4"><input id="cont_fax" name="cont_fax" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_fax'] ?>"></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-2 control-label" for="main_email">Email</label>
                        <div class="col-md-9"><input id="cont_main_email" name="cont_main_email" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_main_email'] ?>"
                                   required></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-2 control-label" for="finance_email">Finance Email<br><small>(If
                                different)</small></label>
                        <div class="col-md-9"><input id="cont_finance_email" name="cont_finance_email" type="text"
                                   placeholder="" class="form-control " value="<?= $contract['cont_finance_email'] ?>">
                        </div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-2 control-label" for="web">Web</label>
                        <div class="col-md-9"><input id="cont_web" name="cont_web" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_web'] ?>"></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-4 control-label" for="vatno">VAT No</label>
                        <div class="col-md-4"><input id="cont_vatno" name="cont_vatno" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_vatno'] ?>"></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label class="col-md-4 control-label" for="compno">Company No</label>
                        <div class="col-md-4"><input id="cont_compno" name="cont_compno" type="text" placeholder=""
                                   class="form-control " value="<?= $contract['cont_compno'] ?>"></div>
                    </div>

                </div>
            </div>
        </div>
    </div>





    <div class="col-md-6">
        <?php require_once(ROOT_URL . '/forms/elements/contract_logo.frm') ?>
    </div>



</div>
</div>
<div class="spacer"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const contractContainer = document.getElementById('contractDetailsContainer');
    const radios = document.getElementsByName('clientMode');
    for (let i = 0; i < radios.length; i++) {
        radios[i].addEventListener('change', function() {
            if (this.value === "1") {
                contractContainer.classList.remove('d-none');
            } else {
                contractContainer.classList.add('d-none');
            }
        });
    }
});


function setBilling() {
    document.getElementById('billing_name').value = document.getElementById('clientname').value;
    document.getElementById('billing1').value = document.getElementById('address1').value;
    document.getElementById('billing2').value = document.getElementById('address2').value;
    document.getElementById('billing_town').value = document.getElementById('town').value;
    document.getElementById('billing_county').value = document.getElementById('county').value;
    document.getElementById('billing_postcode').value = document.getElementById('postcode').value;
    document.getElementById('billing_phone').value = document.getElementById('phone1').value;
    document.getElementById('billing_email').value = document.getElementById('email').value;
    document.getElementById('pri_contact_tel').value = document.getElementById('phone1').value;
    document.getElementById('pri_contact_mob').value = document.getElementById('mobile').value;
    document.getElementById('pri_contact_email').value = document.getElementById('email').value;
}

// Function to add and refresh WS and LWS data
function addWS() {

    fetch('<?= ROOT_URL ?>/includes/client/client_ws.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=' +
            TENANT_URL)
        .then(response => response.text())
        .then(data => {
            loadModalContent(data, "wsBox", "modal-xl", 1060, "true", "New Written Scheme");
        });
}

function relWs() {
    fetch('<?= ROOT_URL ?>/includes/master/ws_data.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=' +
            TENANT_URL)
        .then(response => response.text())
        .then(data => {
            document.getElementById('wsData').innerHTML = data;
        });
}

function addLWS() {
    fetch('<?= ROOT_URL ?>/includes/client/client_lws.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=' +
            TENANT_URL)
        .then(response => response.text())
        .then(data => {
            loadModalContent(data, "wsBox", "modal-xl", 1060, "true", "New LOLER Written Scheme");
        });
}

function relLWs() {
    fetch('<?= ROOT_URL ?>/includes/master/lws_data.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=' +
            TENANT_URL)
        .then(response => response.text())
        .then(data => {
            document.getElementById('lwsData').innerHTML = data;
        });
}

// Function to trigger actions (like form submissions)
function triggerAction(buttonId) {
    document.getElementById(buttonId).click();
}


// Function to handle email button clicks
document.body.addEventListener('click', function(event) { // Event delegation on body
    if (event.target.classList.contains('emailButton')) {
        const target = event.target.dataset.href;
        const string = event.target.dataset.values;
        var dest = encodeURI(target + "?data=" + string + "&tenant=" + TENANT_URL);
        loadModalContent(dest, "popupBox", "modal-xl", 1060, "true");

    }
});

// Document ready equivalent in pure JavaScript
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('footerControls').innerHTML =
        '<button class="btn btn-secondary" onclick="triggerAction(\'btn_update\')">UPDATE</button>';
    relWs();
    relLWs();
});

function printContent(target, header) {
    printContainer(target, {
        orientation: 'portrait',
        header: '<p></p>',
        footer: '<p>Generated by EnRep Reporting System: <?= date('d-m-Y') ?></p>',
        logoUrl: 'images/company/logo.jpg',
        styles: [
            ROOT_URL + '/src/css/print.css'
        ],
    });
}
</script>