<?php
// finance_renewal_invoice.php — Pending renewal invoices staged in invoices_temp

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

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

// 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 generated date
// Generated date = COALESCE(renewals.date, invoices_temp.date)
$timeMin = null;
$timeMax = null;

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 {
    // Default to this month
    $timeMin = mktime(0, 0, 0, (int)date('n'), 1, (int)date('Y'));
    $timeMax = strtotime('+1 month', $timeMin);
}

// -----------------------------
// Build Year/Month index counts for staged renewals
// Uses COALESCE(renewals.date, invoices_temp.date)
// -----------------------------
$idxSql = "
    SELECT COALESCE(r.date, it.date) AS d
    FROM invoices_temp it
    LEFT JOIN renewals r ON r.renewalNumber = it.invNo
";
$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['d'] ?? 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 from invoices_temp + renewals
// -----------------------------
$sql = "
    SELECT it.*,
           COALESCE(r.date, it.date) AS gen_date
    FROM invoices_temp it
    LEFT JOIN renewals r ON r.renewalNumber = it.invNo
    WHERE 1=1
";
$params = [];
$types  = '';

if ($timeMin !== null) {
    $sql .= " AND COALESCE(r.date, it.date) >= ?";
    $params[] = $timeMin;
    $types    .= 'i';
}
if ($timeMax !== null) {
    $sql .= " AND COALESCE(r.date, it.date) < ?";
    $params[] = $timeMax;
    $types    .= 'i';
}
$sql .= " ORDER BY ABS(it.invNo) DESC";

$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;
}

// latest temp inv id (unchanged behaviour)
$stmt = $GLOBALS['con']->prepare("SELECT invNo FROM invoices_temp WHERE invNo=(SELECT MAX(invNo) FROM invoices_temp)") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$i = $stmt->get_result();
$stmt->close();
$latest = mysqli_fetch_array($i);
$latestId = $latest['invNo'] ?? 0;
?>

<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">Pending Renewal Invoices</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">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 active">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-toggle="tooltip" 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>Renewals:</strong> Pending renewal invoices</code>.
            <small>Use <em>Issue invoice</em> to generate and send the renewal invoice, or view/void.</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') ?>">
                        This Month (<?= date('M Y') ?>)
                    </a>
                </div>

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

                <!-- Year / Month index (collapsible, one open at a time) -->
                <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">
                            <!-- Toggle months (no navigation) -->
                            <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>

                            <!-- View Year (does filter) -->
                            <a class="btn btn-info btn-sm me-2"
                               href="<?= $SELF ?>&y=<?= $y ?>"
                               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 staged renewals found.</div>
                    <?php endif; ?>
                </div>

                <!-- Date Range -->
                <hr class="my-3">
                <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">Search</button>
                        <a href="<?= $SELF ?>" class="btn btn-outline-secondary btn-sm w-100">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">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</th>
                        <th>Contract #</th>
                        <th>Amount</th>
                        <th>Date Generated</th>
                        <th>Renewal Date</th>
                        <th class="text-end noExport">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
          $mTotal = 0;
          foreach ($data as $row):
            $invNo = (int)$row['invNo'];
            $invNoFormatted = sprintf("%06d", $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;

            // generated date from joined query
            $rnDate = !empty($row['gen_date']) ? date('d-m-Y', (int)$row['gen_date']) : '';

            // client name + renewal date
            $clientNumber = (int)($address['client_name'] ?? 0);
            $clientName = '';
            $renewalDate = '';
            if ($clientNumber > 0) {
              $stmt = $GLOBALS['con']->prepare("SELECT clientname, renewal_date FROM clientdetails WHERE clientnumber=? LIMIT 1");
              $stmt->bind_param('i', $clientNumber);
              $stmt->execute();
              $cx = $stmt->get_result();
              $stmt->close();
              if ($cx && $cx->num_rows) {
                $cd = mysqli_fetch_assoc($cx);
                $clientName = $cd['clientname'];
                $renewalDate = !empty($cd['renewal_date']) ? date('d-m-Y', (int)$cd['renewal_date']) : '';
              }
            }
            $agentName  = trim($address['agent_name'] ?? '');
            $grandFmt   = number_format($grandTotal, 2);
            $contractNum= htmlspecialchars($address['contract_number'] ?? '');
          ?>
                    <tr id="R<?= $invNoFormatted ?>">
                        <td><?= $invNoFormatted ?></td>
                        <td><?= htmlspecialchars($clientName ?: 'Unknown') ?></td>
                        <td><?= htmlspecialchars($agentName) ?></td>
                        <td><?= $contractNum ?></td>
                        <td>£<?= $grandFmt ?></td>
                        <td><?= $rnDate ?></td>
                        <td><?= $renewalDate ?: '-' ?></td>
                        <td class="text-end">
                            <div role="group">
                                <!-- ALWAYS show Issue Invoice -->
                                <button type="button"
                                        class="btn btn-secondary btn-sm me-2 sentButton"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                        title="Issue Invoice"
                                        data-action="issue"
                                        data-inv="<?= $invNo ?>">
                                    <i class="fad fa-file-arrow-up"></i> Issue invoice
                                </button>

                                <a href="index.php?t=includes/finance&p=finance_preview.php&invNo=<?= $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-secondary btn-sm me-2"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                        title="Void Invoice"
                                        data-action="void"
                                        data-inv="<?= $invNo ?>"
                                        data-amount="£<?= $grandFmt ?>">
                                    <i class="fad fa-ban text-danger"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

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

<div id="exportDiv" style="display:none">
    <div id="exportTitle">Pending Renewal Invoices - <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</th>
                <th>Contract Number</th>
                <th>Amount</th>
                <th>Date Generated</th>
                <th>Renewal Date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $row):
        $invNo = (int)$row['invNo'];
        $invNoFormatted = sprintf("%06d", $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;

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

        $clientNumber = (int)($address['client_name'] ?? 0);
        $clientName = '';
        $renewalDate = '';
        if ($clientNumber > 0) {
          $stmt = $GLOBALS['con']->prepare("SELECT clientname, renewal_date FROM clientdetails WHERE clientnumber=? LIMIT 1");
          $stmt->bind_param('i', $clientNumber);
          $stmt->execute();
          $cx = $stmt->get_result();
          $stmt->close();
          if ($cx && $cx->num_rows) {
            $cd = mysqli_fetch_assoc($cx);
            $clientName = $cd['clientname'];
            $renewalDate = !empty($cd['renewal_date']) ? date('d-m-Y', (int)$cd['renewal_date']) : '';
          }
        }
      ?>
            <tr id="R<?= $invNoFormatted ?>">
                <td><?= $invNoFormatted ?></td>
                <td><?= htmlspecialchars($clientName ?: 'Unknown') ?></td>
                <td><?= htmlspecialchars($address['agent_name'] ?? '') ?></td>
                <td><?= htmlspecialchars($address['contract_number'] ?? '') ?></td>
                <td>£<?= number_format($grandTotal, 2) ?></td>
                <td><?= $rnDate ?></td>
                <td><?= $renewalDate ?: '-' ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php
// DataTable config (same pattern as paid)
$table = "expenseTable";
$dateTarget = "5"; // "Date Generated" column
$length = "25";
$sortTarget = "1";
$sortCell = "";
$logo = "yes";
$scroller = "";
$printTarget = 'exportDiv';
$printHeader = 'Pending Renewal Invoices';
$popup = "false";
require(ROOT_URL . '/includes/tables/finance_table.php');
?>

<script>
// Tooltips (MDB auto-inits via data-mdb-tooltip-init; this is a safety init)
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => new mdb.Tooltip(el));
});

// Date range submit → redirect preserving t & p
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);
    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;

        // Close others
        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');
                    }
                }
            }
        });

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

        // Update chevron
        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', () => {
    // Ensure closed on load
    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();
        });
    }
});

// Helper
function pad(n, w) {
    n = String(n);
    return n.length >= w ? n : new Array(w - n.length + 1).join('0') + n;
}

// Listen for mailer success (same pattern as paid)
window.addEventListener('enrep:emailSent', (e) => {
    if (e?.detail?.success) {
        if (typeof getRenewals === 'function') getRenewals('current'); // if you have a refresher hook
        showResponse('success', 'Email sent. List refreshed.');
    }
}, {
    once: false
});

// Actions: issue / void
document.addEventListener('click', async (ev) => {
    const btn = ev.target.closest('button, a');
    if (!btn) return;
    const action = btn.dataset.action;

    if (action === 'void') {
        const inv = btn.dataset.inv;
        const html = `<h5 class="text-center">Are you sure invoice <b>#${pad(inv,6)}</b> is to be voided?<br><span class="text-danger"><small>THIS CANNOT BE UNDONE</small></span></h5>`;
        loadModalContent(html, "confirmBox", "modal-md", 1060, "true", "Void Invoice", "cancelConfirm", () => setArchive(inv));
        return;
    }

    if (action === 'issue') {
        const inv = btn.dataset.inv;
        const html = `<h5 class="text-center">Are you sure you wish to issue this invoice?</h5>`;
        loadModalContent(html, "confirmBox", "modal-md", 1060, "true", "Issue Invoice", "cancelConfirm", () => invoiceConfirm(inv));
        return;
    }
});

// Void/archive via finance_functions
async function setArchive(inv) {
    try {
        const res = await fetch(`${ROOT_URL}/includes/finance/finance_functions.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                FUNCTION: 'setArchive',
                inv,
                tenant: TENANT_URL
            }).toString()
        });
        const txt = (await res.text()).trim();
        if (txt === 'success') {
            const row = document.getElementById(`R${pad(inv,6)}`) || document.getElementById(`R${inv}`);
            if (row) {
                row.style.backgroundColor = '#e2d38e';
                row.style.border = '1px solid #e6be0f';
                setTimeout(() => {
                    row.style.transition = 'opacity .5s';
                    row.style.opacity = '0';
                    setTimeout(() => {
                        row.style.display = 'none';
                    }, 100);
                }, 800);
            }
            showResponse('success', 'The invoice has been voided');
            killModal('confirmBox');
        } else {
            showResponse('danger', 'Failed to void invoice.');
        }
    } catch (e) {
        showResponse('danger', 'An error occurred during voiding.');
    }
}

// Issue renewal: sendInvoice -> invoice.php -> open mailer; refresh after emailSent
async function invoiceConfirm(invId) {
    try {
        const spinner = document.getElementById('loadingObject2');
        if (spinner) spinner.style.display = 'block';

        // Step 1: prepare send metadata
        const sendRes = await fetch(`${ROOT_URL}/includes/finance/finance_functions.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                FUNCTION: 'sendInvoice',
                id: invId,
                tenant: TENANT_URL
            }).toString()
        });
        const raw = await sendRes.text();
        let j;
        try {
            j = JSON.parse(raw);
        } catch {
            j = {
                status: 'error',
                message: raw
            };
        }

        if (j.status !== 'success') {
            if (spinner) spinner.style.display = 'none';
            showResponse('danger', `Failed to prepare invoice: ${j.message || 'Unknown error'}`);
            return;
        }

        // Step 2: build PDFs/ZIP
        const target = (j.target || 'client').toLowerCase();
        const brokerCom = target === 'broker' ? 1 : 0;
        const agentCom = target === 'agent' ? 1 : 0;

        const post = new URLSearchParams();
        post.append('invNo', String(j.invoice || invId));
        post.append('rtype', target);
        post.append('brokerCom', brokerCom);
        post.append('agentCom', agentCom);
        if (j.broker_number) post.append('broker_number', j.broker_number);
        if (j.agent_number) post.append('agent_number', j.agent_number);
        post.append('tenant', TENANT_URL);

        try {
            const invRes = await fetch(`${ROOT_URL}/includes/engines/invoice.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: post.toString()
            });
            const text = await invRes.text();
            if (!invRes.ok) throw new Error(`HTTP ${invRes.status}`);
            if (!text.trim()) throw new Error('Empty response from invoice.php');
            console.log('Invoice.php response:', text);
        } catch (err) {
            console.error('invoice.php call failed:', err);
            showResponse('danger', `Failed to call invoice.php: ${err.message}`);
            return;
        }

        // Step 3: open mailer
        let mailerUrl = '';
        if (j.mailerPayload && typeof j.mailerPayload === 'object') {
            const encoded = encodeURIComponent(JSON.stringify(j.mailerPayload));
            mailerUrl = `${ROOT_URL}/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`;
        } else if (j.email && typeof j.email === 'string') {
            const encoded = encodeURIComponent(j.email);
            mailerUrl = `${ROOT_URL}/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`;
        } else {
            if (spinner) spinner.style.display = 'none';
            showResponse('danger', 'Mailer payload missing.');
            return;
        }

        killModal('confirmBox');
        loadModalContent(mailerUrl, "popupBox", "modal-xl", 1060, "true", "Email Invoice", "", '');

    } catch (e) {
        showResponse('danger', `Failed to issue invoice: ${e.message}`);
    }
}
</script>