<?php
if (!function_exists('dashboardIntListSql')) {
    function dashboardIntListSql($values)
    {
        $values = array_values(array_unique(array_filter(array_map('intval', (array)$values))));
        return implode(',', $values);
    }
}

if (!function_exists('dashboardReviewTableAvailable')) {
    function dashboardReviewTableAvailable(): bool
    {
        if (empty($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
            return false;
        }

        $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `report_review_actions` LIMIT 1");
        if (!$stmt) {
            return false;
        }
        $ok = $stmt->execute();
        $stmt->close();
        return $ok;
    }
}

$sessionAccess = (int)($_SESSION['access'] ?? 0);
$sessionUserId = (int)($_SESSION['userid'] ?? 0);
$contractorNumber = trim((string)($_SESSION['contractorNumber'] ?? ''));
$clientAccess = [];
$hasClientAccessRow = false;
$surveyorFilterArray = [];

// Prepare and execute the query to count incomplete reports without returning every row.
$stmt = $GLOBALS['con']->prepare("SELECT COUNT(*) AS incomplete_count FROM `reportitems_temp`");
$stmt->execute();
$ac = $stmt->get_result()->fetch_assoc();
$icNum = (int)($ac['incomplete_count'] ?? 0);
$stmt->close();

if ($sessionUserId > 0) {
    $accessQuery = "SELECT clientnumbers FROM admin_access WHERE admin_id = ?";
    $stmt = $GLOBALS['con']->prepare($accessQuery);
    $stmt->bind_param('i', $sessionUserId);
    $stmt->execute();
    $accessResult = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($accessResult) {
        $hasClientAccessRow = true;
        $clientAccessArray = json_decode($accessResult['clientnumbers'] ?? '[]', true);
        if (is_array($clientAccessArray)) {
            $clientAccess = array_values(array_unique(array_filter(array_map('intval', $clientAccessArray))));
        }
    }
}

if (($_SESSION['usertype'] ?? '') == "surveyor" && $sessionAccess == 3 && $sessionUserId > 0) {
    $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `client_id` FROM `surveyor_assignments` WHERE `surveyor`=?");
    $stmt->bind_param("i", $sessionUserId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $surveyorFilterArray[] = (int)$row['client_id'];
    }
    $stmt->close();
}
?>
<style>
.dashboard-client-search {
    width: 100% !important;
    min-width: 100% !important;
    max-width: 100% !important;
}
.dashboard-client-results {
    background: #fff;
    border: 1px solid #dfe5eb;
    border-radius: 6px;
    display: none;
    left: 0;
    max-height: 240px;
    overflow: auto;
    position: absolute;
    right: 0;
    top: calc(100% + 4px);
    z-index: 1040;
}
.dashboard-client-result {
    border-bottom: 1px solid #eef1f4;
    cursor: pointer;
    padding: .45rem .65rem;
}
.dashboard-client-result:hover,
.dashboard-client-result:focus {
    background: #f4f7fa;
}
.dashboard-client-result:last-child {
    border-bottom: 0;
}
.dashboard-client-result small {
    color: #6b7580;
    display: block;
}
.dashboard-report-progress {
    min-width: 340px;
}
.dashboard-report-progress th,
.dashboard-report-progress td {
    vertical-align: middle;
}
.dashboard-report-progress .progress {
    height: 6px;
}
.dashboard-report-client {
    min-width: 160px;
}
.dashboard-report-metric {
    min-width: 110px;
    white-space: nowrap;
}
.dashboard-review-badges {
    align-items: flex-start;
    display: flex;
    flex-direction: column;
    gap: .2rem
}
</style>
<script>
document.body.classList.add('dashboard');
<?php if (empty($_SESSION['contractorNumber']) && $icNum > 0): ?>
document.getElementById('navBox').innerHTML = `
    <li class="breadcrumb-item">
        <a href="index.php?t=includes/master&p=incomplete.php">
            <i class="fad fa-hourglass-half fa-spin"></i> <?= $icNum ?> Incomplete Reports
        </a>
    </li>`;
<?php endif; ?>
</script>
<div id="loadingObject">
    <div class="col-12 text-center text-light">
        <h1>
            <i class="fad fa-spinner fa-spin fa-3x fa-fw"
                style="--fa-primary-color: #0055A6; --fa-secondary-color: white;"></i><br>Syncing Data<br><small>Please
                wait</small>
        </h1>
    </div>
</div>

<div id="dash" class="mt-n5 mt-md-0" style="display: none">
    <div class="row mb-3">
        <div class="col-12 col-lg-9">

            <h2 class="text-light">Dashboard</h2>
        </div>
        <div class="col-12 col-lg-3">
            <div class="card">
                <div class="card-header">Load Client</div>
                <div class="card-body position-relative">
                    <input type="search" id="loadClientSearch" class="form-control dashboard-client-search"
                        autocomplete="off" placeholder="Search clients">
                    <div id="loadClientResults" class="dashboard-client-results"></div>
                </div>
            </div>
        </div>
    </div>

    <?php
    if ($_SESSION['usertype'] == "admins") {
        require_once(ROOT_URL . '/includes/admin/admin_assignment.php');
    }
    if ($_SESSION['usertype'] == "surveyor" && $_SESSION['access'] == 3) {

        //require_once(ROOT_URL.'/includes/surveyor/jobsheet.php');
        require_once(ROOT_URL . '/includes/surveyor/admin_assignments.php');
    } else {
        $dest = ROOT_URL . '/includes/master/reportsNotSent.php?tenant=' . TENANT_URL;
    ?>

    <?php
        if (($_SESSION['usertype'] ?? '') == "surveyor" && in_array($sessionAccess, [1, 2], true)) {
            require_once(ROOT_URL . '/includes/surveyor/surveyor_review_notes.php');
        }
    ?>
    <div id="dynamic1" class="row px-3"></div>
    <div id="dynamic2" class="row px-3">
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-header">Reports Not Sent <a class="float-end text-light" href="javascript:void(0)"
                        onclick="loadModalContent('<?= $dest ?>', 'popupBox', 'modal-xl', 1060, 'true','Reports not sent','close');">View
                        all</a>
                </div>
                <div class="card-body" style="max-height:200px; overflow: auto">
                    <table id="datatable" class="table table-sm table-striped dashboard-report-progress">
                        <thead>
                            <tr>
                                <th>Client</th>
                                <th class="dashboard-report-metric">Done / Expected</th>
                                <th class="dashboard-report-metric">Left</th>
                                <th class="dashboard-report-metric">Review</th>
                                <th class="text-end"></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                            $todayEnd = strtotime('tomorrow midnight') - 1;
                            $reviewTableReady = dashboardReviewTableAvailable();
                            $reportWhere = ["b.`statuslive` = '1'"];
                            $types = 'i';
                            $params = [$todayEnd];
                            if (!empty($contractorNumber)) {
                                $reportWhere[] = "b.contractor = ?";
                                $types .= 's';
                                $params[] = $contractorNumber;
                            }
                            if ($sessionAccess == 1 && $hasClientAccessRow) {
                                $clientAccessSqlList = dashboardIntListSql($clientAccess);
                                $reportWhere[] = $clientAccessSqlList !== '' ? "b.clientnumber IN ($clientAccessSqlList)" : "1 = 0";
                            }

                            $reviewSelect = $reviewTableReady
                                ? "COALESCE(rra.active_review_count, 0) AS active_review_count,
                                   COALESCE(rra.response_count, 0) AS response_count,
                                   COALESCE(rra.ready_count, 0) AS ready_count"
                                : "0 AS active_review_count,
                                   0 AS response_count,
                                   0 AS ready_count";
                            $reviewJoin = $reviewTableReady
                                ? "LEFT JOIN (
                                    SELECT
                                        rra.`clientnumber`,
                                        SUM(CASE WHEN rra.`status` IN ('pending', 'responded') THEN 1 ELSE 0 END) AS active_review_count,
                                        SUM(CASE WHEN rra.`status` = 'responded' AND TRIM(COALESCE(rra.`surveyor_response`, '')) <> '' THEN 1 ELSE 0 END) AS response_count,
                                        SUM(CASE WHEN rra.`status` = 'ready' THEN 1 ELSE 0 END) AS ready_count
                                    FROM `report_review_actions` rra
                                    INNER JOIN `reportitems` rri
                                        ON rri.`repitem` = rra.`repitem`
                                        AND rri.`clientnumber` = rra.`clientnumber`
                                        AND rri.`delivery` = '0'
                                    GROUP BY rra.`clientnumber`
                                ) rra ON b.`clientnumber` = rra.`clientnumber`"
                                : "";

                            $reportSql = "
                        SELECT
                            b.`clientnumber`,
                            b.`clientname`,
                            b.`contractor`,
                            COALESCE(ri.not_sent_count, 0) AS count,
                            COALESCE(due.expected_count, 0) AS expected_count,
                            $reviewSelect
                        FROM `clientdetails` b
                        LEFT JOIN (
                            SELECT `clientnumber`, COUNT(`repitem`) AS not_sent_count
                            FROM `reportitems`
                            WHERE `delivery` = '0'
                            GROUP BY `clientnumber`
                        ) ri ON b.`clientnumber` = ri.`clientnumber`
                        LEFT JOIN (
                            SELECT `clientnumber`, COUNT(`itemnumber`) AS expected_count
                            FROM `itemdetails`
                            WHERE `statuslive` = '1' AND `duedate` > 0 AND `duedate` <= ?
                            GROUP BY `clientnumber`
                        ) due ON b.`clientnumber` = due.`clientnumber`
                        $reviewJoin
                        WHERE " . implode(' AND ', $reportWhere) . "
                          AND COALESCE(ri.not_sent_count, 0) > 0
                        ORDER BY b.clientname ASC
                    ";
                            $stmt = $GLOBALS['con']->prepare($reportSql);
                            if ($types !== '') {
                                $stmt->bind_param($types, ...$params);
                            }
                            $stmt->execute();
                            $items = $stmt->get_result();
                            $stmt->close();
                            while ($idata = $items->fetch_assoc()) {
                                $clientName = htmlspecialchars(preg_replace("/[^a-zA-Z0-9 &.'-]/", " ", $idata['clientname']));
                                $clientNumber = htmlspecialchars($idata['clientnumber']);
                                $done = (int)$idata['count'];
                                $left = (int)$idata['expected_count'];
                                $expected = $done + $left;
                                $progressBase = max($expected, $done, 1);
                                $progressPercent = min(100, round(($done / $progressBase) * 100));
                                $activeReview = (int)$idata['active_review_count'];
                                $responseReview = (int)$idata['response_count'];
                                $readyReview = (int)$idata['ready_count'];
                                $reviewBadges = [];
                                if ($activeReview > 0) {
                                    $reviewBadges[] = "<span class='badge bg-warning text-white'>Review underway $activeReview</span>";
                                } elseif ($readyReview > 0) {
                                    $reviewBadges[] = "<span class='badge bg-success'>$readyReview ready</span>";
                                }
                                if ($responseReview > 0) {
                                    $reviewBadges[] = "<span class='badge bg-danger text-white'>Surveyor response $responseReview</span>";
                                }
                                if (!empty($reviewBadges)) {
                                    $reviewHtml = "<span class='dashboard-review-badges'>" . implode('', $reviewBadges) . "</span>";
                                } else {
                                    $reviewHtml = "<span class='text-muted small'>No review</span>";
                                }
                                echo "<tr id='R$clientNumber'>";
                                echo "<th class='dashboard-report-client'>$clientName</th>";
                                echo "<td><strong>$done</strong> / $expected<div class='progress mt-1'><div class='progress-bar bg-info' style='width: {$progressPercent}%'></div></div></td>";
                                echo "<td><strong>$left</strong><br><small class='text-muted'>remaining</small></td>";
                                echo "<td>$reviewHtml</td>";
                                echo "<td><a href='index.php?t=includes/master/&p=reports_outstanding.php&clientnumber=$clientNumber' class='btn btn-secondary m-0 px-3 py-2 waves-effect float-end' data-mdb-tooltip-init data-mdb-placement='bottom' title='View Reports'><i class='fad fa-eye'></i></a></td>";
                                echo "</tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer border-0"></div>
            </div>
        </div>
    </div>
    <?php } ?>
</div>


<script>
// Use fetch API for AJAX requests
async function fetchData(url, data) {
    try {
        // Create form data
        const formData = new FormData();
        for (const key in data) {
            formData.append(key, data[key]);
        }

        // Fetch with form data
        const response = await fetch(url, {
            method: 'POST',
            body: formData
        });

        return await response.text();
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

function inspections_due() {
    fetchData(ROOT_URL + '/framework/dashboard_functions/inspections_due.php', {
        contractorNumber: <?= json_encode($contractorNumber) ?>,
        tenant: TENANT_URL
    }).then(data => document.getElementById('dynamic1').innerHTML += data);
}

function inspections_overdue() {
    fetchData(ROOT_URL + '/framework/dashboard_functions/inspections_overdue.php?mode=', {
        contractorNumber: <?= json_encode($contractorNumber) ?>,
        tenant: TENANT_URL
    }).then(data => document.getElementById('dynamic1').innerHTML += data);
}

<?php if ($_SESSION['usertype'] != "surveyor"){?>
function renewals_due() {
    fetchData(ROOT_URL + '/framework/dashboard_functions/renewals_due.php', {
        contractorNumber: <?= json_encode($contractorNumber) ?>,
        tenant: TENANT_URL
    }).then(data => document.getElementById('dynamic2').innerHTML += data);
}
renewals_due();
<?php }?>
<?php if (empty($_SESSION['contractorNumber'])): ?>

function reports() {
    fetchData(ROOT_URL + '/framework/dashboard_functions/reports.php', {
        contractorNumber: <?= json_encode($contractorNumber) ?>,
        tenant: TENANT_URL
    }).then(data => document.getElementById('dynamic2').innerHTML += data);
}

<?php endif; ?>
inspections_due();
inspections_overdue();

function setRenew(c, n) {
    const content =
        `<p class="text-center lead">Do you wish to set the contract for <strong>${n}</strong> as renewed and send out the invoice?</p>`;
    const footer = `
        <div class="row">
            <div class="col-md-4">
                <a href="javascript:void(0)" class="btn btn-success m-0 px-3 py-2 waves-effect" onclick="renewContract('${c}', '${n}')">Confirm</a>
            </div>
            <div class="col-md-4"></div>
            <div class="col-md-4 text-right">
                <a href="javascript:void(0)" class="btn btn-danger m-0 px-3 py-2 waves-effect" onclick="closePop()">Cancel</a>
            </div>
        </div>`;
    showPop('Confirm Contract renewal', content, footer, 'd');
}

async function renewContract(c, n) {
    const result = await fetchData('includes/client/client_functions.php', {
        FUNCTION: 'setRenew',
        src: 'ext2',
        clientnumber: c,
        tenant: TENANT_URL
    });

    if (result.trim() == "1") {
        const clientData = await fetchData(ROOT_URL + '/includes/client/client_functions.php', {
            FUNCTION: 'getEmailData',
            src: 'ext2',
            clientnumber: c,
            tenant: TENANT_URL
        });

        const clientObj = JSON.parse(clientData);

        const invoiceData = await fetchData(ROOT_URL + '/includes/client/client_functions.php', {
            FUNCTION: 'getInvoiceData',
            src: 'ext2',
            clientnumber: c,
            tenant: TENANT_URL
        });

        const inv = invoiceData.trim();
        closePop();

        const emailResult = await fetchData(ROOT_URL + '/functions/sendmail.php', {
            src: 'ext',
            subject: 'Your Contract Renewal',
            recipient_1: clientObj[2],
            source_1: 'invoices',
            file_1: `${inv}_invoice.pdf`,
            message: `Your contract number <b>${clientObj[3]}</b> has been successfully renewed.<br>Thank you.`
        });

        if (emailResult.trim() == "success") {
            document.getElementById('datatable').querySelector(`#R${c}`).style.display = 'none';
            showResponse('success', `${n} Contract renewed successfully`);
        }
    }
}

function initialiseLoadClientSearch() {
    const search = document.getElementById('loadClientSearch');
    const results = document.getElementById('loadClientResults');
    if (!search || !results || search.dataset.dashboardReady === '1') {
        return;
    }

    search.dataset.dashboardReady = '1';
    const pageSize = 30;
    let searchTimer = null;
    let activeController = null;
    let currentQuery = '';
    let nextOffset = 0;
    let hasMoreClients = false;
    let isLoadingClients = false;
    let clientRequestId = 0;

    const removeMoreMarker = () => {
        const marker = results.querySelector('[data-client-more]');
        if (marker) marker.remove();
    };

    const renderResults = (clients, message = '', append = false, hasMore = false) => {
        removeMoreMarker();
        if (!append) {
            results.innerHTML = '';
        }
        if (!clients.length && !append) {
            results.innerHTML = message ? `<div class="dashboard-client-result text-muted">${message}</div>` : '';
            results.style.display = message ? 'block' : 'none';
            return;
        }
        results.insertAdjacentHTML('beforeend', clients.map(client => `
            <div class="dashboard-client-result" tabindex="0" role="button" data-client="${client.clientnumber}">
                ${escapeDashboardHtml(client.clientname || '')}
            </div>
        `).join(''));
        if (hasMore) {
            results.insertAdjacentHTML('beforeend', '<div class="dashboard-client-result text-muted" data-client-more>Scroll for more clients...</div>');
        }
        results.style.display = 'block';
    };

    const runSearch = (query = '', append = false) => {
        if (append && isLoadingClients) {
            return;
        }
        if (!append) {
            currentQuery = query;
            nextOffset = 0;
            hasMoreClients = false;
        }
        isLoadingClients = true;
        const requestId = ++clientRequestId;
        if (activeController) activeController.abort();
        activeController = new AbortController();
        const params = new URLSearchParams({
            tenant: TENANT_URL,
            q: query,
            limit: pageSize,
            offset: append ? nextOffset : 0
        });
        fetch(ROOT_URL + '/framework/dashboard_functions/client_search.php?' + params.toString(), {
            signal: activeController.signal
        })
            .then(response => response.json())
            .then(data => {
                if (requestId !== clientRequestId) {
                    return;
                }
                const clients = data.clients || [];
                hasMoreClients = !!data.hasMore;
                nextOffset = Number(data.nextOffset || ((append ? nextOffset : 0) + clients.length));
                renderResults(clients, query ? 'No clients found' : 'No clients available', append, hasMoreClients);
            })
            .catch(error => {
                if (requestId === clientRequestId && error.name !== 'AbortError') renderResults([], 'Client search failed', append);
            })
            .finally(() => {
                if (requestId === clientRequestId) {
                    isLoadingClients = false;
                }
            });
    };

    search.addEventListener('input', function() {
        window.clearTimeout(searchTimer);
        const query = this.value.trim();
        if (query !== '' && query.length < 2) {
            currentQuery = query;
            nextOffset = 0;
            hasMoreClients = false;
            clientRequestId++;
            if (activeController) activeController.abort();
            isLoadingClients = false;
            renderResults([], '');
            return;
        }
        searchTimer = window.setTimeout(() => runSearch(query), 250);
    });
    search.addEventListener('focus', function() {
        if (!results.innerHTML || currentQuery !== this.value.trim()) runSearch(this.value.trim());
        else results.style.display = 'block';
    });
    results.addEventListener('scroll', function() {
        if (hasMoreClients && !isLoadingClients && results.scrollTop + results.clientHeight >= results.scrollHeight - 40) {
            runSearch(currentQuery, true);
        }
    });
    results.addEventListener('click', function(event) {
        const item = event.target.closest('[data-client]');
        if (item) loadClient(item.dataset.client);
    });
    results.addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            const item = event.target.closest('[data-client]');
            if (item) loadClient(item.dataset.client);
        }
    });
    document.addEventListener('click', function(event) {
        if (!results.contains(event.target) && event.target !== search) {
            results.style.display = 'none';
        }
    });
}

setTimeout(() => {
    document.getElementById('loadingObject').style.display = 'none';
    document.getElementById('dash').style.display = 'block';
    initialiseLoadClientSearch();
}, 2000);

function loadClient(clientNumber) {
    const client = encodeURIComponent(clientNumber || '');
    if (!client) {
        return;
    }
    window.location.href = `index.php?t=includes/master&p=client.php&clientnumber=${client}&view=asset`;
}

function escapeDashboardHtml(value) {
    return String(value).replace(/[&<>"']/g, function(char) {
        return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[char];
    });
}
</script>
