<?php if (!empty($_SESSION['contractorNumber'])) {
    $filter = "AND `contractor`='" . $_SESSION['contractorNumber'] . "'";
}
$SurveyorFilterArray = array();
$clientAccess = array();

?>
<div id="loadingObject">
    <h1 class="text-center"><i class="fad fa-flux-capacitor fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Loading Data <br><small>Please
            wait</small>
    </h1>
</div>

<div class="row">
    <?php
    function getRenew($renewal)
    {
        $now = new DateTime();
        if (is_numeric($renewal)) {
            $renewal_date = date('d-m-Y', $renewal);

            $current_date = $now->format('d-m-Y');
            $onemonth = $now->sub(new DateInterval('P1M'));
            //$twomonth = $now->sub(new DateInterval('P2M'));
            $om = $onemonth->format('d-m-Y');
            //$tm=$twomonth->format('d-m-Y');

            $datetime1 = new DateTime($current_date);
            $datetime2 = new DateTime($renewal_date);
            $difference = $datetime1->diff($datetime2);

            $days = $difference->format("%r%a");
            if (strpos($days, '-') !== false) {
                $day = $difference->format("%a") . ' days ago';
            } else {
                $day = 'in ' . $days . ' days';
            }

            if ($days < 60 && $days > 0 && date('m-Y', $renewal) != date("m-Y")) {
                $stat = "status_colour success-color-dark";
                $statTitle = "not due";
            } elseif ($days == 0 && (date('m', $renewal) == date("m"))) {
                $stat = "status_colour success-color-dark";
                $statTitle = "not due";
            } elseif (($days < 30 && $days > 0) && (date('m', $renewal) == date("m"))) {
                $stat = "status_colour warning-color-dark";
                $statTitle = "pending";
            } elseif (date('m-Y', $renewal) == date("m-Y")) {
                $stat = "status_colour danger-color-dark";
                $statTitle = "overdue";
            } elseif (date('m-Y', $renewal) == date("m-Y", strtotime($om))) {
                $stat = "status_colour success-color-dark";
                $statTitle = "not due";
            }

            //elseif(date('m-Y',$renewal)==date("m-Y",strtotime($twomonth))){$ret= '<div class="alert alert-dark text-center m-0" style="padding:3px">Renewal due '.$day.' ('.$renewal_date.')</div>';}

            else {
                $stat = "status_colour success-color-dark";
                $statTitle = "not due";
            }
        } else {
            $stat = "status_colour bg-dark";
            $statTitle = "Notset";
            $renewal_date = "Not set";
        }
        return '<td class="' . $stat . '" width="20px" data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover" title="Due - ' . $renewal_date . '">
        <div class="' . $stat . '" style="font-size:0px">' . $statTitle . '</div></td>';
    }

    if ($_SESSION['usertype'] == "surveyor" && $_SESSION['access'] == 3 && $_REQUEST['view'] == "list") {

        $status = "1";

        // Get assignments
        $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `client_id` FROM `surveyor_assignments` WHERE `surveyor` = ?  AND `status` = '1'");
        $stmt->bind_param("i", $_SESSION['userid']);
        $stmt->execute();
        $ac = $stmt->get_result();
        $stmt->close();

        while ($ds = mysqli_fetch_array($ac)) {
            $SurveyorFilterArray[] = $ds['client_id'];
        }
    }


    $accessQuery = "SELECT clientnumbers FROM admin_access WHERE admin_id = ?";
    $stmt = $con->prepare($accessQuery);
    $stmt->bind_param('i', $_SESSION['userid']);
    $stmt->execute();
    $accessResult = $stmt->get_result()->fetch_assoc();
    $clientAccessArray = json_decode($accessResult['clientnumbers']);

    foreach ($clientAccessArray as $client) {
        $clientAccess[] = $client;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`locname`,`postcode` FROM `locations` WHERE `statuslive`='1' AND `locname`!='' $filter ORDER BY `locname` ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $cc = $stmt->get_result();
    $stmt->close(); ?>
    <div class=" col-12 col-md-3 me-auto mb-3">
        <div class="input-group input-group-sm">
            <span class="input-group-text bg-info text-light" id="loadClientBySite">Locate Site</span>
            <select data-mdb-size="sm" data-mdb-select-init data-mdb-filter="true" id="loadClientBySite"
                data-placeholder="search" onchange="loadClientBySite()">
                <option value=""></option>
                <?php while ($pd = mysqli_fetch_array($cc)) {
                    if (!in_array($pd['clientnumber'], $SurveyorFilterArray) && $_SESSION['access'] == 3) {
                    } elseif (!in_array($pd['clientnumber'], $clientAccess) && $_SESSION['access'] == 1) {
                    } else {
                ?>
                <option value="<?= $pd['clientnumber'] ?>" data-mdb-secondary-text="<?= $pd['postcode'] ?>">
                    <?= $pd['locname'] ?></option>
                <?php }
                } ?>
            </select>

        </div>
    </div>

    <div class="col-6 text-center text-md-end"><a href="index.php?t=includes/master&p=client.php&view=new"
            class="btn btn-secondary btn-sm"><i class="fad fa-plus" aria-hidden="true"></i> New Client</a>
        <?php if ($_REQUEST['filter'] == "" || $_REQUEST['filter'] == "current") { ?>
        <script>
        document.getElementById('navBox').innerHTML =
            '<li class="breadcrumb-item">Client List <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Active Clients</li>';
        </script>
        <a href="index.php?t=includes/master&p=client.php&view=list&filter=archive" class="btn btn-secondary btn-sm"><i
                class="fad fa-archive" aria-hidden="true"></i> View Archived Clients</a>
        <div id="exportTitle" style="display: none">Active Client List - <?= date('d-m-Y') ?></div>
        <?php }
        if ($_REQUEST['filter'] == "archive") { ?>
        <script>
        document.getElementById('navBox').innerHTML =
            '<li class="breadcrumb-item">Client List <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Archived Clients</li>';
        </script>
        <a href="index.php?t=includes/master&p=client.php&view=list&filter=current" class="btn btn-secondary btn-sm"><i
                class="fad fa-wave-pulse"></i> View Active Clients</a>
        <div id="exportTitle" style="display: none">Archived Client List - <?= date('d-m-Y') ?></div>

        <?php } ?>

    </div>
</div>
<?php $status = 1;
if ($_REQUEST['filter'] == "archive") {
    $status = 0;
}

$stmt = $GLOBALS['con']->prepare("SELECT 
    a.clientnumber,
    a.clientname,
    a.phone1,
    a.email,
    a.postcode,
    a.pri_contact_name,
    a.agent_number,
    a.broker_number,
    a.renewal_date,
    a.statuslive,
    a.contractor,
    a.systemMode,
    b.agent_number AS anum,
    b.agent_name AS aname,
    c.broker_number AS bnum,
    c.broker_name AS bname
    FROM clientdetails a LEFT JOIN agents b ON a.agent_number=b.agent_number LEFT JOIN brokers c ON a.broker_number=c.broker_number WHERE a.statuslive='" . $status . "' $filter ORDER BY `clientname` ASC") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();
$cn = mysqli_num_rows($cc);
//echo $cn;
?>
<div class="row">
    <div class="col-md-6 mb-3 text-center text-md-start">

        <button type="button" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
            title="Filter Overdue renewals" class="btn color danger-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Overdue',0)">&nbsp;Overdue&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
            title="Filter Pending renewals" class="btn color warning-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Pending',0)">&nbsp;Pending&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
            title="Filter renewals not due" class="btn color success-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Not Due',0)">&nbsp;Not
            Due&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
            title="Filter unset renewals" class="btn color bg-dark text-light filterButtons btn-sm"
            onClick="addSearch('Notset',0)">&nbsp;Not Set&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
            title="Reset filters" class="btn color bg-white filterButtons btn-sm" onClick="clearSearch()">&nbsp;<i
                class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters&nbsp;</button>

    </div>
</div>
<table id="assetTable" class="table table-striped table-bordered table-hover responsive table-sm" width="100%"
    style="display:none">
    <thead>
        <tr>
            <th class="no-sort noExport text-center p-0 text-hidden" width="10px"></th>
            <th>Client</th>
            <th>Client Name</th>
            <th>Contact Name</th>
            <th>Agent/Broker</th>
            <th>Phone</th>
            <th>Email</th>
            <th width="100px">Post Code</th>
            <th class="no-sort noExport "></th>
        </tr>
    </thead>
    <tbody>
        <?php $smIcon = '';
        while ($cd = mysqli_fetch_array($cc)) {
            if ($cd['systemMode'] === 1) {
                $smIcon = '<i class="fad fa-bolt-lightning"></i>';
            } elseif ($cd['systemMode'] === 0) {
                $smIcon = '<i class="fad fa-hurricane"></i>';
            }
            if (!in_array($cd['clientnumber'], $SurveyorFilterArray) && $_SESSION['access'] == 3) {
            } elseif (!in_array($cd['clientnumber'], $clientAccess) && $_SESSION['access'] == 1) {
            } else {
                $cd['pri_contact_name'] = urldecode($cd['pri_contact_name']);
                $cd['clientname'] = urldecode($cd['clientname']);
                $cd['account_handler'] = urldecode($cd['account_handler']);

                if ($cd['anum'] != 0) {
                    $accountName = urldecode($cd['aname']);
                    $accountLink = '<span class="badge badge-pill badge-dark">A</span> <a href="index.php?t=includes/master&p=agent.php&agent_number=' . $cd['anum'] . '&view=edit">' . $accountName . '</a>';
                }
                if ($cd['bnum'] != 0) {
                    $accountName = urldecode($cd['bname']);
                    $accountLink = '<span class="badge badge-pill badge-dark">B</span> <a href="index.php?t=includes/master&p=broker.php&broker_number=' . $cd['bnum'] . '&view=edit">' . $accountName . '</a>';
                }
                if ($cd['anum'] == 0 && $cd['bnum'] == 0) {
                    $accountName = 'blank';
                    $accountLink = '';
                }

                $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));
        ?>
        <tr>
            <?= getRenew($cd['renewal_date']) ?>
            <td class="align-middle text-center"><?= $cd['clientnumber'] ?></td>
            <td class="align-middle"><?= $smIcon ?> <?= $cd['clientname'] ?></td>
            <td class="align-middle"><?= $cd['pri_contact_name'] ?></td>
            <td class="align-middle"><?= $accountLink ?></td>
            <td class="align-middle"><?= $cd['phone1'] ?></td>
            <td class="align-middle"><?= $cd['email'] ?></td>
            <td class="align-middle"><?= $cd['postcode'] ?></td>
            <td class="align-middle  text-md-end">
                <div class="btn-group" role="group"><a
                        href="index.php?t=includes/master&p=client.php&clientnumber=<?= $cd['clientnumber'] ?>&view=asset"
                        class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="top"
                        data-mdb-trigger="hover" title="View Schedule"><i class="fad fa-th-list"></i></a>
                    <?php
                            if ($cd['phone1'] != "") { ?>
                    <a id="phone" href="tel:<?= $cd['phone1'] ?>" class="btn btn-secondary noprint me-2"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Call Client"><i
                            class="fad fa-phone"></i></a>
                    <?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="top" data-mdb-trigger="hover" title="Email Client"><i
                            class="fad fa-envelope"></i></a>
                    <?php } ?>

                    <a href="index.php?t=includes/client&p=client_addressbook.php&clientnumber=<?= $cd['clientnumber'] ?>"
                        class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="top"
                        data-mdb-trigger="hover" title="Address Book"><i class="fad fa-address-book"></i></a>
                    <?php if ($_SESSION['access'] == 1 || $_SESSION['access'] == 2 || $_SESSION['access'] == 999) { ?>
                    <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $cd['clientnumber'] ?>&view=edit"
                        class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top"
                        data-mdb-trigger="hover" title="View Client Details"><i class="fad fa-info-circle"></i></a>
                    <?php } else { ?>
                    <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $cd['clientnumber'] ?>&view=edit"
                        class="btn btn-secondary noprint" data-mdb-tooltip-init data-mdb-placement="top"
                        data-mdb-trigger="hover" title="View Client Details"><i class="fad fa-info-circle"></i></a>
                    <?php } ?>
                </div>
            </td>
        </tr>
        <?php }
        } ?>
    </tbody>
</table>
<?php //echo  $_SESSION['usertype']." | ".$_SESSION['access']
?>
<?php
$table = "assetTable";

?>
<?php require_once(ROOT_URL . "/includes/tables/client_table.php"); ?>

<script>
document.addEventListener('DOMContentLoaded', function() {

    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 + "?string=" + string + "&mode=popup&tenant=" + TENANT_URL);
            loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mailer");

        }
    });

    // Hide elements with class 'remove'
    const removeElements = document.querySelectorAll('.remove');
    removeElements.forEach(element => {
        element.style.display = 'none';
    });

});
</script>