<?php
// finance_paid.php — Paid invoices (status = 3)

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// -----------------------------
// Preserve router params for links
// -----------------------------
$T = $_GET['t'] ?? 'includes/finance';
$P = $_GET['p'] ?? 'finance_paid.php';
$SELF = 'index.php?t=' . rawurlencode($T) . '&p=' . rawurlencode($P);

// -----------------------------
// Read filters (year/month or date range) + new features
// -----------------------------
$selYear  = isset($_GET['y']) ? (int)$_GET['y'] : 0;
$selMonth = isset($_GET['m']) ? (int)$_GET['m'] : 0;
$fromStr  = trim($_GET['from'] ?? '');
$toStr    = trim($_GET['to'] ?? '');

$loadAll  = isset($_GET['all']) && (int)$_GET['all'] === 1;
$searchQ  = trim($_GET['q'] ?? '');
$hasSearch = ($searchQ !== '');

// Helper: parse dd-mm-yyyy or dd/mm/yyyy → timestamp @ 00:00
$parseDMY = function(string $dmy): ?int {
    $dmy = trim($dmy);
    if ($dmy === '') return null;
    $dmy = str_replace('/', '-', $dmy);
    if (!preg_match('/^\s*(\d{1,2})-(\d{1,2})-(\d{4})\s*$/', $dmy, $m)) return null;
    [$all, $d, $mth, $y] = $m;
    return @mktime(0, 0, 0, (int)$mth, (int)$d, (int)$y) ?: null;
};

// Compute time window (inclusive start, exclusive end) — based on invoice `date`
$timeMin = null;
$timeMax = null;

// If "Load all" or Search is active, do NOT apply date window filters
if (!$loadAll && !$hasSearch) {
    if ($fromStr !== '' || $toStr !== '') {
        $fromTs = $fromStr !== '' ? $parseDMY($fromStr) : null;
        $toTs   = $toStr   !== '' ? $parseDMY($toStr)   : null;

        if ($fromTs && $toTs) {
            $timeMin = $fromTs;
            $timeMax = strtotime('+1 day', $toTs); // exclusive
        } elseif ($fromTs && !$toTs) {
            $timeMin = $fromTs;
            $today0  = mktime(0, 0, 0, (int)date('n'), (int)date('j'), (int)date('Y'));
            $timeMax = strtotime('+1 day', $today0);
        } elseif (!$fromTs && $toTs) {
            $timeMax = strtotime('+1 day', $toTs);
        }
    } elseif ($selYear > 0 && $selMonth > 0) {
        $timeMin = mktime(0, 0, 0, $selMonth, 1, $selYear);
        $timeMax = strtotime('+1 month', $timeMin);
    } elseif ($selYear > 0) {
        $timeMin = mktime(0, 0, 0, 1, 1, $selYear);
        $timeMax = strtotime('+1 year', $timeMin);
    } else {
        $timeMin = mktime(0, 0, 0, (int)date('n'), 1, (int)date('Y'));
        $timeMax = strtotime('+1 month', $timeMin);
    }
}

// -----------------------------
// Build Year/Month index counts (all paid invoices)
// -----------------------------
$idxSql = "SELECT `date` FROM `invoices` WHERE `status`=3";
$idxStmt = $GLOBALS['con']->prepare($idxSql) or die(mysqli_error($GLOBALS['con']));
$idxStmt->execute();
$idxRs = $idxStmt->get_result();
$idxStmt->close();

$yrMo = []; // [year => ['total'=>int, 'months'=>[m=>count]]]
while ($r = mysqli_fetch_assoc($idxRs)) {
    $ts = (int)($r['date'] ?? 0);
    if ($ts <= 0) continue;
    $y = (int)date('Y', $ts);
    $m = (int)date('n', $ts);
    if (!isset($yrMo[$y])) $yrMo[$y] = ['total'=>0,'months'=>[]];
    $yrMo[$y]['total']++;
    if (!isset($yrMo[$y]['months'][$m])) $yrMo[$y]['months'][$m] = 0;
    $yrMo[$y]['months'][$m]++;
}
krsort($yrMo);
foreach ($yrMo as &$info) { ksort($info['months']); }
unset($info);

// -----------------------------
// Pull filtered data (status=3) + SEARCH (partial match) + LOAD ALL
// -----------------------------
$sql = "
    SELECT i.*
    FROM `invoices` i
    LEFT JOIN `clientdetails` cd ON cd.clientnumber = i.client
    LEFT JOIN `agents` ag ON ag.agent_number = i.agent
    LEFT JOIN `brokers` br ON br.broker_number = i.broker
    WHERE i.`status` = 3
";

$params = [];
$types  = '';

if ($timeMin !== null) {
    $sql .= " AND i.`date` >= ?";
    $params[] = $timeMin;
    $types    .= 'i';
}
if ($timeMax !== null) {
    $sql .= " AND i.`date` < ?";
    $params[] = $timeMax;
    $types    .= 'i';
}

if ($hasSearch) {
    // make partial + robust
    $q = preg_replace('/\s+/', ' ', $searchQ);
    $like = '%' . $q . '%';

    if (ctype_digit($q)) {
        $sql .= " AND (
            i.invNo = ?
            OR LPAD(i.invNo,6,'0') LIKE ?
            OR cd.clientname LIKE ?
            OR ag.agent_name LIKE ?
            OR br.broker_name LIKE ?
            OR i.address LIKE ?
        )";
        $params[] = (int)$q; $types .= 'i';
        $params[] = $like;   $types .= 's';
        $params[] = $like;   $types .= 's';
        $params[] = $like;   $types .= 's';
        $params[] = $like;   $types .= 's';
        $params[] = $like;   $types .= 's';
    } else {
        $sql .= " AND (
            LPAD(i.invNo,6,'0') LIKE ?
            OR cd.clientname LIKE ?
            OR ag.agent_name LIKE ?
            OR br.broker_name LIKE ?
            OR i.address LIKE ?
        )";
        $params[] = $like; $types .= 's';
        $params[] = $like; $types .= 's';
        $params[] = $like; $types .= 's';
        $params[] = $like; $types .= 's';
        $params[] = $like; $types .= 's';
    }
}

$sql .= " ORDER BY ABS(i.invNo) ASC";

$stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$rs = $stmt->get_result();
$stmt->close();

$data = [];
while ($row = mysqli_fetch_array($rs)) $data[] = $row;
$hasRows = !empty($data);

// -----------------------------
// Small helpers
// -----------------------------
function monthName(int $m): string {
    static $names = [1=>'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return $names[$m] ?? (string)$m;
}
?>

<style>
@media (min-width: 992px) {
    .sidebar-hidden #invoiceSidebar {
        display: none !important;
    }

    .sidebar-hidden #invoiceMain {
        flex: 0 0 100% !important;
        max-width: 100% !important;
    }
}

@media (min-width: 992px) {
    #invoiceSidebar {
        height: 75vh;
        border: 1px solid #ccc;
        border-radius: 5px;
        border-right: 5px solid #999;
        box-shadow: 4px 0 8px rgba(0, 0, 0, .1);
        background-color: var(--mdb-light-bg-subtle);
        position: sticky;
        top: 0;
    }
}
</style>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">Finance - Invoices</a> ' +
    '<i class="fad fa-angle-double-right mx-2 mt-1"></i></li>' +
    '<li class="breadcrumb-item active">Paid</li>';
</script>

<div id="invoiceData" class="container-fluid px-0">

    <?php
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `status`='1' or `status`='2'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $i = $stmt->get_result();
    $stmt->close();
    $unpaidCount = mysqli_num_rows($i);

    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices_temp`") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $i = $stmt->get_result();
    $stmt->close();
    $renewalCount = mysqli_num_rows($i);
?>

    <div class="row">
        <div class="col-12 col-md-9 float-start">
            <div class="btn-group me-2 mb-4 active" role="group" aria-label="New Invoice">
                <a href="index.php?t=includes/finance&p=finance_invoices-new.php" class="btn btn-success">New Invoice</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Blank Invoice">
                <a href="index.php?t=includes/finance&p=finance_invoice_blank.php" class="btn btn-dark">Blank Invoice</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Unpaid Invoices">
                <a href="index.php?t=includes/finance&p=finance_unpaid.php" class="btn btn-outline-secondary">Unpaid Invoices <span class="badge rounded-pill bg-dark ms-2"><?= $unpaidCount ?></span></a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Paid Invoices">
                <a href="index.php?t=includes/finance&p=finance_paid.php" class="btn btn-outline-secondary active">Paid Invoices</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Renewal Invoice">
                <a href="index.php?t=includes/finance&p=finance_renewal_invoice.php" class="btn btn-outline-secondary">Renewal Invoice <span class="badge rounded-pill bg-dark ms-2"><?= $renewalCount ?></span></a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Voided Invoices">
                <a href="index.php?t=includes/finance&p=finance_archive.php" class="btn btn-outline-secondary"><span class="text-danger">Voided Invoices</span></a>
            </div>
        </div>

        <div class="col-12 col-md-3">
            <a href="index.php?t=includes/finance&p=invoicePaid_reports.php"
               class="btn btn-secondary float-end"
               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Reports">
                <i class="fad fa-file-invoice me-1"></i> Create Report
            </a>
        </div>
    </div>

    <div class="mb-2 mb-md-0">
        <div class="note note-light mb-3">
            <strong>You can print or review all paid invoices:</strong>
            <small class="mt-1">Use the sidebar to filter by year, month, date range, load all, or search.</small>
        </div>
    </div>

    <div class="row g-3">
        <!-- Sidebar -->
        <aside id="invoiceSidebar" class="col-12 col-lg-3 px-3">
            <div class="d-flex d-lg-none justify-content-between align-items-center mb-2">
                <h6 class="mb-0">Filter</h6>
                <button class="btn btn-outline-secondary btn-sm" type="button" data-mdb-collapse-init
                        data-mdb-target="#invIndexCollapse" aria-expanded="false" aria-controls="invIndexCollapse">
                    Toggle
                </button>
            </div>

            <div class="collapse d-lg-block" id="invIndexCollapse">
                <label class="mt-2 mb-2 alert-info d-block px-2">Data Explorer</label>
                <div class="mb-3">
                    <a class="btn btn-secondary btn-sm w-100"
                       href="<?= $SELF ?>&y=<?= date('Y') ?>&m=<?= date('n') ?>"
                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                       title="Show paid invoices for this month">
                        This Month (<?= date('M Y') ?>)
                    </a>
                </div>
                <!-- Search (router-safe: always sends t & p) -->
                <div class="mt-3 mb-4">
                    <form class="mb-0" method="get" action="index.php">
                        <input type="hidden" name="t" value="<?= htmlspecialchars($T, ENT_QUOTES) ?>">
                        <input type="hidden" name="p" value="<?= htmlspecialchars($P, ENT_QUOTES) ?>">

                        <div class="input-group">
                            <input
                                   type="text"
                                   class="form-control"
                                   name="q"
                                   id="invSearch"
                                   value="<?= htmlspecialchars($searchQ, ENT_QUOTES) ?>"
                                   placeholder="Search invoice / client / agent / broker"
                                   autocomplete="off">

                            <button class="btn btn-secondary" type="submit"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Search paid invoices">
                                <i class="fad fa-search"></i>
                            </button>

                            <a class="btn btn-danger text-light" href="<?= $SELF ?>"
                               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                               title="Clear search">
                                <i class="fad fa-times"></i>
                            </a>
                        </div>


                    </form>
                </div>

                <div class="mt-3">
                    <a class="btn btn-secondary btn-sm w-100"
                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                       title="Load all paid invoices"
                       href="<?= $SELF ?>&all=1">
                        <i class="fad fa-list me-1"></i> Load all
                    </a>
                </div>

                <?php $openYear = $selYear ?: (int)date('Y'); ?>

                <!-- Year / Month index -->
                <div class="list-group">
                    <?php if (!empty($yrMo)): foreach ($yrMo as $y => $info):
                        $isOpen = ($y === $openYear);
                        $collapseId = "yearMonths-$y";
                    ?>
                    <div class="mb-2 border rounded">
                        <div class="d-flex align-items-center justify-content-between">
                            <button type="button"
                                    class="list-group-item list-group-item-action py-2 flex-grow-1 text-start border-0 bg-transparent"
                                    data-year-toggle="<?= $y ?>"
                                    aria-controls="<?= $collapseId ?>"
                                    aria-expanded="<?= $isOpen ? 'true':'false' ?>">
                                <span class="me-2">
                                    <i class="fad fa-chevron-<?= $isOpen ? 'down' : 'right' ?>"></i>
                                </span>
                                <?= $y ?>
                                <span class="badge bg-dark ms-2"><?= (int)$info['total'] ?></span>
                            </button>

                            <a class="btn btn-info btn-sm me-2"
                               href="<?= $SELF ?>&y=<?= $y ?>"
                               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                               title="View <?= $y ?>">View</a>
                        </div>

                        <div id="<?= $collapseId ?>" class="ps-2 pt-1 collapse <?= $isOpen ? 'show' : '' ?>">
                            <?php foreach ($info['months'] as $m => $cnt): ?>
                            <a class="list-group-item list-group-item-action py-1 <?= ($y === $selYear && $m === $selMonth) ? 'active' : '' ?>"
                               href="<?= $SELF ?>&y=<?= $y ?>&m=<?= $m ?>">
                                <?= monthName($m) ?>
                                <span class="badge bg-light text-dark ms-2 float-end"><?= (int)$cnt ?></span>
                            </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; else: ?>
                    <div class="text-muted small">No invoices found.</div>
                    <?php endif; ?>
                </div>

                <hr class="my-3">

                <!-- Date Range (kept as its own form) -->
                <form id="rangeForm" class="vstack gap-2" onsubmit="return applyRange(event)">
                    <div class="row">
                        <div class="col-12 col-md-6 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="form-label small mb-1">From</label>
                            <input class="form-control form-control-sm"
                                   data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   id="range_from" name="from" placeholder="dd-mm-yyyy" autocomplete="off"
                                   value="<?= htmlspecialchars($fromStr) ?>">
                        </div>
                        <?php $todayDMY = date('d-m-Y'); ?>
                        <div class="col-12 col-md-6 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="form-label small mb-1">To</label>
                            <input class="form-control form-control-sm"
                                   data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   id="range_to" name="to" placeholder="dd-mm-yyyy" autocomplete="off"
                                   value="<?= htmlspecialchars($toStr !== '' ? $toStr : $todayDMY) ?>">
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-secondary btn-sm w-100"
                                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                title="Apply date range">
                            Search
                        </button>
                        <a href="<?= $SELF ?>" class="btn btn-secondary btn-sm w-100"
                           data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                           title="Reset filters">
                            Reset
                        </a>
                    </div>
                </form>



            </div>
        </aside>

        <!-- Main -->
        <section id="invoiceMain" class="col-12 col-lg-9">

            <div class="col-12 col-lg-3 mx-n2 mb-3">
                <button id="toggleSidebar" type="button"
                        class="btn btn-outline-secondary btn-sm ms-2"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Toggle sidebar">
                    <i class="fad fa-columns me-1"></i> <span class="filters-label">Open filters</span>
                </button>
            </div>

            <?php if (!$hasRows): ?>
            <h3 class="text-center text-warning">
                <?= $hasSearch ? 'No paid invoices match your search.' : 'There are no items to display yet for this month.' ?>
            </h3>
            <p class="text-center text-muted">Use the filter panel to view historic data</p>
            <?php else: ?>

            <table id="expenseTable" class="table table-striped table-hover align-middle w-100 table-sm">
                <thead class="table-dark">
                    <tr>
                        <th>Invoice #</th>
                        <th>Client</th>
                        <th>Agent/Broker</th>
                        <th>Contract #</th>
                        <th>Status</th>
                        <th>Amount</th>
                        <th>Date of Invoice</th>
                        <th>Date Paid</th>
                        <th class="text-end noExport">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $mTotal = 0;

                    foreach ($data as $row):
                        $invNoFormatted = sprintf("%06d", (int)$row['invNo']);
                        $address = @unserialize($row['address']); if (!is_array($address)) $address = [];

                        $totals = explode('|', $row['totals']);
                        $sub = (float)str_replace(',', '', $totals[0] ?? '0');
                        $vat = (float)str_replace(',', '', $totals[1] ?? '0');
                        $grandTotal = $sub + $vat;
                        $mTotal += $grandTotal;

                        $invoiceDate = !empty($row['date']) ? date('d-m-Y', (int)$row['date']) : '';
                        $datePaid    = !empty($row['date_paid']) ? date('d-m-Y', (int)$row['date_paid']) : '';

                        $emailBtn = !empty($row['sent'])
                            ? '<span class="badge bg-success text-white">SENT</span>'
                            : '<span class="badge bg-warning text-dark">NOT SENT</span>';

                        // Client link / label
                        $clientLink = '';
                        $cd = null;
                        $ad = null;
                        $bd = null;

                        if (($row['target'] ?? '') === 'blank') {
                            $clientLink = '<span>' . htmlspecialchars($address['billing_name'] ?? '') . '</span>';
                        } else {
                            $stmt = $GLOBALS['con']->prepare("SELECT clientname, clientnumber FROM clientdetails WHERE clientnumber=?");
                            $stmt->bind_param('i', $row['client']);
                            $stmt->execute();
                            $cd = $stmt->get_result()->fetch_assoc();
                            $stmt->close();

                            $clientLink = '<a href="javascript:void(0)" ' .
                                'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Statement" ' .
                                'onclick="showStatement(\'client\',' . (int)$row['client'] . ',\'paid\')">' .
                                htmlspecialchars($cd['clientname'] ?? '') . '</a>';
                        }

                        // Agent/Broker link
                        $nameLink = '';
                        if (($row['target'] ?? '') === 'agent') {
                            $stmt = $GLOBALS['con']->prepare("SELECT agent_name FROM agents WHERE agent_number=?");
                            $stmt->bind_param('i', $row['agent']);
                            $stmt->execute();
                            $ad = $stmt->get_result()->fetch_assoc();
                            $stmt->close();

                            $nameLink = '<a href="javascript:void(0)" ' .
                                'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Statement" ' .
                                'onclick="showStatement(\'agent\',' . (int)$row['agent'] . ',\'paid\')">' .
                                htmlspecialchars($ad['agent_name'] ?? '') . '</a>';
                        } elseif (($row['target'] ?? '') === 'broker') {
                            $stmt = $GLOBALS['con']->prepare("SELECT broker_name FROM brokers WHERE broker_number=?");
                            $stmt->bind_param('i', $row['broker']);
                            $stmt->execute();
                            $bd = $stmt->get_result()->fetch_assoc();
                            $stmt->close();

                            $nameLink = '<a href="javascript:void(0)" ' .
                                'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Statement" ' .
                                'onclick="showStatement(\'broker\',' . (int)$row['broker'] . ',\'paid\')">' .
                                htmlspecialchars($bd['broker_name'] ?? '') . '</a>';
                        }

                        $contractNum = htmlspecialchars($address['contract_number'] ?? '');
                        $grandFmt = number_format($grandTotal, 2);
                    ?>
                    <tr id="R<?= $invNoFormatted ?>">
                        <td><?= $invNoFormatted ?></td>
                        <td><?= $clientLink ?></td>
                        <td><?= $nameLink ?></td>
                        <td><?= $contractNum ?></td>
                        <td><?= $emailBtn ?></td>
                        <td>£<?= $grandFmt ?></td>
                        <td><?= $invoiceDate ?></td>
                        <td><?= $datePaid ?></td>
                        <td class="text-end">
                            <a href="index.php?t=includes/finance&p=finance_preview.php&invNo=<?= (int)$row['invNo'] ?>&type=paid"
                               class="btn btn-secondary btn-sm me-2"
                               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                               title="View Invoice">
                                <i class="fad fa-eye"></i>
                            </a>

                            <button type="button"
                                    class="btn btn-outline-danger btn-sm"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Revoke payment"
                                    onclick="openRevokePaidModal(<?= (int)$row['invNo'] ?>, '<?= $invNoFormatted ?>')">
                                <i class="fad fa-undo-alt"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="d-flex justify-content-end px-3 mt-3">
                <span class="fw-bold">Total Paid: £<?= number_format($mTotal, 2) ?></span>
            </div>

            <?php endif; ?>
        </section>
    </div>
</div>

<div id="exportDiv" style="display:none">
    <div id="exportTitle">Invoices Paid - <small>Generated <?= date('d-m-Y') ?></small></div>
    <table id="exportTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr>
                <th>Invoice Number</th>
                <th>Client</th>
                <th>Agent/Broker</th>
                <th>Contract Number</th>
                <th>Status</th>
                <th>Amount</th>
                <th>Date of Invoice</th>
                <th>Date Paid</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $mTotal = 0;
            foreach ($data as $row):
                $invNoFormatted = sprintf("%06d", (int)$row['invNo']);
                $address = @unserialize($row['address']); if (!is_array($address)) $address = [];
                $totals = explode('|', $row['totals']);
                $sub = (float)str_replace(',', '', $totals[0] ?? '0');
                $vat = (float)str_replace(',', '', $totals[1] ?? '0');
                $grandTotal = $sub + $vat;
                $mTotal += $grandTotal;

                $invoiceDate = !empty($row['date']) ? date('d-m-Y', (int)$row['date']) : '';
                $datePaid    = !empty($row['date_paid']) ? date('d-m-Y', (int)$row['date_paid']) : '';

                $clientName = '';
                if (($row['target'] ?? '') === 'blank') {
                    $clientName = htmlspecialchars($address['billing_name'] ?? '');
                } else {
                    $stmt = $GLOBALS['con']->prepare("SELECT clientname FROM clientdetails WHERE clientnumber=?");
                    $stmt->bind_param('i', $row['client']);
                    $stmt->execute();
                    $cd = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    $clientName = htmlspecialchars($cd['clientname'] ?? '');
                }

                $agentName = '';
                if (($row['target'] ?? '') === 'agent') {
                    $stmt = $GLOBALS['con']->prepare("SELECT agent_name FROM agents WHERE agent_number=?");
                    $stmt->bind_param('i', $row['agent']);
                    $stmt->execute();
                    $ad = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    $agentName = htmlspecialchars($ad['agent_name'] ?? '');
                } elseif (($row['target'] ?? '') === 'broker') {
                    $stmt = $GLOBALS['con']->prepare("SELECT broker_name FROM brokers WHERE broker_number=?");
                    $stmt->bind_param('i', $row['broker']);
                    $stmt->execute();
                    $bd = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    $agentName = htmlspecialchars($bd['broker_name'] ?? '');
                }

                $emailBtn = !empty($row['sent'])
                    ? '<span class="badge bg-success">SENT</span>'
                    : '<span class="badge bg-warning text-dark">NOT SENT</span>';
            ?>
            <tr>
                <td><?= $invNoFormatted ?></td>
                <td><?= $clientName ?></td>
                <td><?= $agentName ?></td>
                <td><?= htmlspecialchars($address['contract_number'] ?? '') ?></td>
                <td><?= $emailBtn ?></td>
                <td>£<?= number_format($grandTotal, 2) ?></td>
                <td><?= $invoiceDate ?></td>
                <td><?= $datePaid ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="d-flex justify-content-end px-3 mt-3">
        <span class="fw-bold">Total Paid: £<?= number_format($mTotal, 2) ?></span>
    </div>
</div>

<!-- Revoke Paid Status Modal -->
<div class="modal fade" id="revokePaidModal" tabindex="-1" aria-hidden="true" data-mdb-backdrop="static">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header bg-info text-light">
                <h5 class="modal-title mb-0">
                    <i class="fad fa-exclamation-triangle me-2"></i>Revoke Invoice Payment
                </h5>
            </div>
            <div class="modal-body">
                <p class="mb-3">
                    This will mark invoice <strong id="revokeInvoiceNumber"></strong> as <strong>unpaid</strong>.
                </p>
                <ul class="mb-3">
                    <li>Any receipts recorded for this invoice will be removed.</li>
                    <li>Any commission expenses recorded will be removed.</li>
                    <li>Paid date and status will be reset, which will update finance and VAT reports.</li>
                </ul>
                <p class="text-danger fw-bold mb-0">
                    This action will affect accounted figures for the periods in which this invoice was recorded as paid.
                    Are you sure you want to continue?
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="btnConfirmRevokePaid">
                    <i class="fad fa-undo-alt me-2"></i>Revoke payment
                </button>
            </div>
        </div>
    </div>
</div>

<?php
// DataTable config
$table = "expenseTable";
$dateTarget = "6";   // Date of Invoice column index (0-based -> 6)
$length = "25";
$sortTarget = "1";
$sortCell = "";
$logo = "yes";
$scroller = "";
$printTarget = 'exportDiv';
$printHeader = 'Paid Invoices';
$popup = "false";
require(ROOT_URL . '/includes/tables/finance_table.php');
?>

<script>
// Tooltips
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-mdb-tooltip-init], [data-mdb-toggle="tooltip"]').forEach(el => {
        try {
            new mdb.Tooltip(el);
        } catch (e) {}
    });
});

// Date range submit → redirect preserving t & p and clearing other modes
function applyRange(ev) {
    ev.preventDefault();
    const from = (document.getElementById('range_from')?.value || '').trim();
    const to = (document.getElementById('range_to')?.value || '').trim();

    const base = "<?= $SELF ?>";
    const qs = new URLSearchParams();
    if (from) qs.set('from', from);
    if (to) qs.set('to', to);

    // Ensure we don't carry load-all/search accidentally
    // (by only using base + from/to)
    const url = qs.toString() ? (base + '&' + qs.toString()) : base;
    window.location.href = url;
    return false;
}

// Collapse logic: only one year open at a time + chevron update
document.addEventListener('DOMContentLoaded', () => {
    document.body.addEventListener('click', (ev) => {
        const btn = ev.target.closest('[data-year-toggle]');
        if (!btn) return;

        const targetId = btn.getAttribute('aria-controls');
        const target = document.getElementById(targetId);
        if (!target) return;

        document.querySelectorAll('[id^="yearMonths-"]').forEach(el => {
            if (el.id !== targetId) {
                el.classList.remove('show');
                const otherBtn = document.querySelector(`[data-year-toggle][aria-controls="${el.id}"]`);
                if (otherBtn) {
                    otherBtn.setAttribute('aria-expanded', 'false');
                    const icon = otherBtn.querySelector('.fa-chevron-down, .fa-chevron-right');
                    if (icon) {
                        icon.classList.remove('fa-chevron-down');
                        icon.classList.add('fa-chevron-right');
                    }
                }
            }
        });

        const willOpen = !target.classList.contains('show');
        target.classList.toggle('show', willOpen);
        btn.setAttribute('aria-expanded', willOpen ? 'true' : 'false');

        const icon = btn.querySelector('.fa-chevron-down, .fa-chevron-right');
        if (icon) {
            icon.classList.toggle('fa-chevron-down', willOpen);
            icon.classList.toggle('fa-chevron-right', !willOpen);
        }
    });
});

// Desktop sidebar toggle
document.addEventListener('DOMContentLoaded', () => {
    document.body.classList.add('sidebar-hidden');

    const btn = document.getElementById('toggleSidebar');
    const label = btn?.querySelector('.filters-label');

    function setFiltersLabel() {
        const open = !document.body.classList.contains('sidebar-hidden');
        if (label) label.textContent = open ? 'Close filters' : 'Open filters';
    }

    setFiltersLabel();

    if (btn) {
        btn.addEventListener('click', () => {
            document.body.classList.toggle('sidebar-hidden');
            setFiltersLabel();
        });
    }
});

// Statement modal opener
function showStatement(type, id, mode) {
    var dest = encodeURI(`${ROOT_URL}/includes/finance/${type}.php?mode=popup&${type}_number=${id}&tenant=${TENANT_URL}`);
    loadModalContent(dest, "statementBox", "modal-xxl", 1060, "true", `${type[0].toUpperCase() + type.slice(1).toLowerCase()} Statement`, "close");
}

// Revoke paid
let revokeInvId = null;
let revokeInvNumber = '';

function openRevokePaidModal(invId, invNumber) {
    revokeInvId = invId;
    revokeInvNumber = invNumber;

    const label = document.getElementById('revokeInvoiceNumber');
    if (label) label.textContent = invNumber;

    const modalEl = document.getElementById('revokePaidModal');
    if (!modalEl) return;

    if (!modalEl._mdbModal) {
        modalEl._mdbModal = new mdb.Modal(modalEl);
    }
    modalEl._mdbModal.show();
}

document.addEventListener('DOMContentLoaded', () => {
    const btnConfirm = document.getElementById('btnConfirmRevokePaid');
    if (!btnConfirm) return;

    btnConfirm.addEventListener('click', () => {
        if (!revokeInvId) {
            showResponse('danger', 'No invoice selected to revoke.');
            return;
        }

        const post = new URLSearchParams();
        post.append('FUNCTION', 'revokePaid');
        post.append('inv', revokeInvId);
        post.append('tenant', TENANT_URL);

        fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
                method: 'POST',
                body: post
            })
            .then(r => r.text())
            .then(txt => {
                const data = (txt || '').trim();

                if (data === 'success' || data.startsWith('success')) {
                    showResponse('success', 'Invoice ' + revokeInvNumber + ' has been set back to unpaid and related entries removed.');

                    const modalEl = document.getElementById('revokePaidModal');
                    if (modalEl && modalEl._mdbModal) modalEl._mdbModal.hide();

                    window.location.reload();
                    return;
                }

                if (data.startsWith('error|')) {
                    const msg = data.split('|')[1] || 'There was a problem revoking this invoice.';
                    showResponse('danger', msg);
                    return;
                }

                showResponse('danger', 'There was a problem revoking this invoice.');
            })
            .catch(() => showResponse('danger', 'There was a problem communicating with the server.'));
    });
});
</script>