<?php
$currentFilter = $_REQUEST['filter'] ?? 'current';
$contractorNumber = !empty($_SESSION['contractorNumber']) ? (int)$_SESSION['contractorNumber'] : 0;
$SurveyorFilterArray = [];
$clientAccess = [];
$allowedClientNumbers = [];
$accessLimited = false;

if (!function_exists('client_list_e')) {
    function client_list_e($value)
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
    }
}
?>
<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
    if (!function_exists('getRenew')) {
    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" && (int)($_SESSION['access'] ?? 0) === 3 && ($_REQUEST['view'] ?? '') === "list") {
        // 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[] = (int)$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();
    $stmt->close();
    $clientAccessArray = json_decode($accessResult['clientnumbers'] ?? '[]', true);
    if (!is_array($clientAccessArray)) {
        $clientAccessArray = [];
    }

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

    if ((int)($_SESSION['access'] ?? 0) === 3) {
        $accessLimited = true;
        $allowedClientNumbers = $SurveyorFilterArray;
    } elseif ((int)($_SESSION['access'] ?? 0) === 1) {
        $accessLimited = true;
        $allowedClientNumbers = $clientAccess;
    }

    $allowedClientNumbers = array_values(array_unique(array_filter(array_map('intval', $allowedClientNumbers))));
    $allowedClientSql = '';
    if ($accessLimited) {
        $allowedClientSql = empty($allowedClientNumbers)
            ? ' AND 1=0'
            : ' AND `clientnumber` IN (' . implode(',', $allowedClientNumbers) . ')';
    }

    $contractorLocationSql = $contractorNumber > 0 ? " AND `contractor`=" . $contractorNumber : '';

  $stmt = $GLOBALS['con']->prepare("
    SELECT `clientnumber`,`locname`,`postcode`
    FROM `locations`
    WHERE `statuslive`='1'
      AND `locname`!=''
      $contractorLocationSql
      $allowedClientSql
    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"
              data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
              title="Locate Site">
            Locate Site
        </span>

        <select data-mdb-size="sm"
                data-mdb-select-init
                data-mdb-filter="true"
                id="siteFinderSelect"
                data-placeholder="Search"
                onchange="loadClientBySite()">
            <option value=""></option>

            <?php while ($pd = mysqli_fetch_array($cc)) {
                $locname = client_list_e($pd['locname'] ?? '');
                $postcode = client_list_e($pd['postcode'] ?? '');
            ?>
                <option value="<?= (int)$pd['clientnumber'] ?>" data-mdb-secondary-text="<?= $postcode ?>">
                    <?= $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 ($currentFilter === "" || $currentFilter === "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 ($currentFilter === "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 ($currentFilter === "archive") {
    $status = 0;
}

$clientWhere = ['a.statuslive=' . (int)$status];
if ($contractorNumber > 0) {
    $clientWhere[] = 'a.contractor=' . $contractorNumber;
}
if ($accessLimited) {
    $clientWhere[] = empty($allowedClientNumbers)
        ? '1=0'
        : 'a.clientnumber IN (' . implode(',', $allowedClientNumbers) . ')';
}
$clientWhereSql = implode(' AND ', $clientWhere);

$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 $clientWhereSql 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
        while ($cd = mysqli_fetch_array($cc)) {
            $clientNumber = (int)($cd['clientnumber'] ?? 0);
            $clientName = urldecode((string)($cd['clientname'] ?? ''));
            $contactName = urldecode((string)($cd['pri_contact_name'] ?? ''));
            $phone = (string)($cd['phone1'] ?? '');
            $email = (string)($cd['email'] ?? '');
            $postcode = (string)($cd['postcode'] ?? '');
            $accountLink = '';
            $smIcon = '';
            $systemMode = ($cd['systemMode'] ?? '') !== '' ? (int)$cd['systemMode'] : null;

            if ($systemMode === 1) {
                $smIcon = '<i class="fad fa-bolt-lightning"></i>';
            } elseif ($systemMode === 0) {
                $smIcon = '<i class="fad fa-hurricane"></i>';
            }

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

                $email_values = [
                    'clientNumber' => (string)$clientNumber,
                    'clientName' => $clientName,
                    'primaryEmail' => $email,
                    'secondaryEmail' => '',
                    'subject' => '',
                    'message' => '',
                    'filePath' => '',
                    'fileName' => '',
                ];
                $email64_values = base64_encode(json_encode($email_values, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        ?>
        <tr>
            <?= getRenew($cd['renewal_date']) ?>
            <td class="align-middle text-center"><?= $clientNumber ?></td>
            <td class="align-middle"><?= $smIcon ?> <?= client_list_e($clientName) ?></td>
            <td class="align-middle"><?= client_list_e($contactName) ?></td>
            <td class="align-middle"><?= $accountLink ?></td>
            <td class="align-middle"><?= client_list_e($phone) ?></td>
            <td class="align-middle"><?= client_list_e($email) ?></td>
            <td class="align-middle"><?= client_list_e($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=<?= $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 ($phone !== "") { ?>
                    <a id="phone" href="tel:<?= client_list_e(preg_replace('/[^0-9+]/', '', $phone)) ?>" 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($email, FILTER_VALIDATE_EMAIL) !== false) { ?>
                    <a href="javascript:void(0)" class="btn btn-secondary noprint emailButton me-2"
                        data-values="<?= htmlspecialchars($email64_values, ENT_QUOTES) ?>" 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=<?= $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>
                    <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $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>
                </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
        const emailButton = event.target.closest('.emailButton');
        if (emailButton) {
            const target = emailButton.dataset.href;
            const string = emailButton.dataset.values;
            const dest = target + "?data=" + encodeURIComponent(encodeURIComponent(string)) + "&mode=popup&tenant=" + encodeURIComponent(TENANT_URL);
            loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Direct Mailer");

        }
    });

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

});
</script>
