<?php
// finance_renewals.php

require_once(ROOT_URL . '/includes/finance/finance_functions.php');

$now       = time();
$thirtyDay = 30 * 86400;

$overdue   = [];
$due30     = [];
$future    = [];

$stmt = $GLOBALS['con']->prepare("
    SELECT *
    FROM clientdetails
    WHERE renewal_date IS NOT NULL
      AND renewal_date <> 0
      AND renewal_status <> 'LAPSED'
      AND statuslive = 1
");
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();

while ($row = $res->fetch_assoc()) {
    $renewUnix = (int)($row['renewal_date'] ?? 0);
    if ($renewUnix <= 0) {
        continue;
    }

    $renewOptionsRaw = $row['renewOptions'] ?? '';
    $renewOptions    = [];
    if (!empty($renewOptionsRaw)) {
        $decoded = json_decode($renewOptionsRaw, true);
        if (is_array($decoded)) {
            $renewOptions = $decoded;
        }
    }

    $renewMode = 'unset';
    $renewId   = null;
    $name      = '';
    $email1    = null;
    $email2    = null;

    $notice = $renewOptions['notice'] ?? null;
    switch ($notice) {
        default:
            $renewMode = 'unset';
            break;

        case "0": // client
            $renewMode = 'client';
            $renewId   = $row['clientnumber'];
            $name      = $row['clientname'] ?? '';
            $name      = str_replace("&", "and", $name);
            $name      = str_replace("'&'", "", $name);
            $email1    = $row['billing_email'] ?? null;
            $email2    = $row['email'] ?? null;
            break;

        case "1": // agent
            $renewMode = 'agent';
            $renewId   = $row['agent_number'];
            if (!empty($renewId)) {
                $bc = mysqli_query(
                    $GLOBALS['con'],
                    "SELECT * FROM `agents` WHERE `agent_number`='" . (int)$renewId . "' "
                ) or die(mysqli_error($GLOBALS['con']));
                $nameData = mysqli_fetch_array($bc);
                if ($nameData) {
                    $name   = $nameData['agent_name'] ?? '';
                    $name   = str_replace("&", "and", $name);
                    $name   = str_replace("'&'", "", $name);
                    $email1 = $nameData['billing_email'] ?? null;
                    $email2 = $nameData['email'] ?? null;
                }
            }
            break;

        case "2": // broker
            $renewMode = 'broker';
            $renewId   = $row['broker_number'];
            if (!empty($renewId)) {
                $bc = mysqli_query(
                    $GLOBALS['con'],
                    "SELECT * FROM `brokers` WHERE `broker_number`='" . (int)$renewId . "' "
                ) or die(mysqli_error($GLOBALS['con']));
                $nameData = mysqli_fetch_array($bc);
                if ($nameData) {
                    $name   = $nameData['broker_name'] ?? '';
                    $name   = str_replace("&", "and", $name);
                    $name   = str_replace("'&'", "", $name);
                    $email1 = $nameData['billing_email'] ?? null;
                    $email2 = $nameData['email'] ?? null;
                }
            }
            break;
    }

    $rn      = mysqli_query(
        $GLOBALS['con'],
        "SELECT * FROM `renewals` WHERE `clientnumber`='" . (int)$row['clientnumber'] . "' AND `status`='0'"
    ) or die(mysqli_error($GLOBALS['con']));
    $rnCount = mysqli_num_rows($rn);
    $renewData = $rnCount ? mysqli_fetch_assoc($rn) : null;

    $autoIcon = '
    <span class="position-absolute end-0 top-0 me-n3 bg-dark text-light px-1 text-center d-flex align-items-center justify-content-center"
          style="font-size: 0.6rem; border-radius: 2px; min-width: 12px; height: 100%;">
      ' . ((int)($row['autoRenew'] ?? 0) === 1 ? 'A' : 'M') . '
    </span>';

    $clientnameClean = $row['clientname'] ?? '';
    $clientnameClean = str_replace("&", "and", $clientnameClean);
    $clientnameClean = str_replace("'&'", "", $clientnameClean);
    $clientnameClean = htmlspecialchars($clientnameClean, ENT_QUOTES, 'UTF-8');

    $row['renewMode']       = $renewMode;
    $row['renewName']       = $name;
    $row['renewEmail1']     = $email1;
    $row['renewEmail2']     = $email2;
    $row['renewRnCount']    = $rnCount;
    $row['renewData']       = $renewData;
    $row['autoIconHtml']    = $autoIcon;
    $row['clientnameClean'] = $clientnameClean;

    if ($renewUnix < $now) {
        $overdue[] = $row;
    } elseif ($renewUnix <= $now + $thirtyDay) {
        $due30[] = $row;
    } else {
        $future[] = $row;
    }
}

$sortByRenewal = function (array $a, array $b): int {
    return ((int)$a['renewal_date']) <=> ((int)$b['renewal_date']);
};
usort($overdue, $sortByRenewal);
usort($due30,   $sortByRenewal);
usort($future,  $sortByRenewal);

function renderRenewalRows(array $rows): void
{
    if (empty($rows)) {
        echo '<tr><td colspan="6" class="text-center text-muted">No records in this band.</td></tr>';
        return;
    }

    $nowLocal = time();

    foreach ($rows as $list) {
        $clientnumber  = (int)($list['clientnumber'] ?? 0);
        $agentNumber   = (int)($list['agent_number']  ?? 0);
        $brokerNumber  = (int)($list['broker_number'] ?? 0);
        $clientName    = htmlspecialchars($list['clientname'] ?? '', ENT_QUOTES, 'UTF-8');
        $clientNameDs  = $list['clientnameClean'] ?? $clientName;
        $renewalUnix   = (int)($list['renewal_date'] ?? 0);
        $renewalDate   = $renewalUnix > 0 ? date('d-m-Y', $renewalUnix) : 'N/A';
        $recipientType = $list['renewRecipientType'] ?? '';
        $recipientId   = (int)($list['renewRecipientId'] ?? 0);
        $recipientName = $list['renewRecipientName'] ?? '';

        $daysDiff      = (int)floor(($renewalUnix - $nowLocal) / 86400);

        if ($daysDiff < 0) {
            $dayLabel = abs($daysDiff) . ' day' . (abs($daysDiff) === 1 ? '' : 's') . ' overdue';
            $badge    = '<span class="badge bg-danger">' . $dayLabel . '</span>';
        } elseif ($daysDiff === 0) {
            $badge = '<span class="badge bg-warning text-dark">Due today</span>';
        } else {
            $dayLabel = $daysDiff . ' day' . ($daysDiff === 1 ? '' : 's') . ' to go';
            $badge    = '<span class="badge bg-info">' . $dayLabel . '</span>';
        }

        $rate          = isset($list['rate_per_hour']) ? (float)$list['rate_per_hour'] : 0.00;
        $rateFormatted = '&pound;' . number_format($rate, 2);

        $renewMode   = $list['renewMode']    ?? 'unset';
        $rnCount     = (int)($list['renewRnCount'] ?? 0);
        $renewData   = $list['renewData']    ?? null;
        $name        = $list['renewName']    ?? '';
        $email1      = $list['renewEmail1']  ?? '';
        $email2      = $list['renewEmail2']  ?? '';
        $autoIcon    = $list['autoIconHtml'] ?? '';
        $contract    = $list['contract_number'] ?? '';
        $modeLabel   = $renewMode; // 'client', 'agent', 'broker', 'unset'

        ?>
<tr id="R<?php echo $clientnumber; ?>">
    <td class="align-middle">
        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?php echo $clientnumber; ?>&view=edit">
            <?php echo $clientName; ?>
        </a>
    </td>
    <td class="align-middle">
        <?php
    // Prefer whoever the renewal is actually addressed to
    if ($recipientType === 'agent' && $recipientId > 0) {
        // Link to agent
        echo '<a href="index.php?t=includes/master&p=agent.php&agent_number=' .
             $recipientId . '&view=edit">' .
             htmlspecialchars($recipientName, ENT_QUOTES, 'UTF-8') .
             '</a>';
    } elseif ($recipientType === 'broker' && $recipientId > 0) {
        // Link to broker
        echo '<a href="index.php?t=includes/master&p=broker.php&broker_number=' .
             $recipientId . '&view=edit">' .
             htmlspecialchars($recipientName, ENT_QUOTES, 'UTF-8') .
             '</a>';
    } elseif ($agentNumber > 0) {
        // Fallback: show agent if present
        echo '<a href="index.php?t=includes/master&p=agent.php&agent_number=' .
             $agentNumber . '&view=edit">' .
             htmlspecialchars(getAgentName($agentNumber), ENT_QUOTES, 'UTF-8') .
             '</a>';
    } elseif ($brokerNumber > 0) {
        // Fallback: show broker if present
        echo '<a href="index.php?t=includes/master&p=broker.php&broker_number=' .
             $brokerNumber . '&view=edit">' .
             htmlspecialchars(getBrokerName($brokerNumber), ENT_QUOTES, 'UTF-8') .
             '</a>';
    } else {
        echo '<span class="text-muted">—</span>';
    }
    ?>
    </td>
    <td class="align-middle">
        <?php echo $renewalDate; ?>
    </td>
    <td class="align-middle">
        <?php echo $badge; ?>
    </td>
    <td class="align-middle text-center">
        <?php echo $rateFormatted; ?>
    </td>
    <td class="align-middle text-end noprint">

        <!-- Client information modal -->
        <button type="button" class="btn btn-secondary btn-sm m-0 px-3 py-2 me-3"
                onclick="loadModalContent('<?=ROOT_URL?>/includes/finance/renewals/renewal-client.php?clientnumber=<?= $clientnumber?>&tenant=<?= TENANT_URL?>','popupBox','modal-xl',1060,true,'Client Information')"
                data-toggle="tooltip"
                data-placement="top"
                title="View information"
                data-values="<?= $clientnumber?>">
            <i class="fad fa-circle-info"></i>
        </button>

        <a href="javascript:void(0)"
           onclick="loadModalContent('<?=ROOT_URL?>/includes/client/location-client.php?clientnumber=clientnumber=<?= $clientnumber?>&tenant=<?= TENANT_URL?>','popupBox','modal-xl',1060,true,'Plant Summary')"
           style="z-index:999"
           class="text-light btn btn-secondary btn-sm m-0 px-3 py-2 me-3"
           data-toggle="tooltip"
           data-placement="bottom"
           title="Client Plant Summary">
            <i class="fad fa-clipboard-list"></i>
        </a>

        <?php
                // Renewal setup + action button logic as per renewals_list
                if ($renewMode === 'unset') {
                    // Setup incomplete – red button linking to client edit
                    ?>
        <a
           href="index.php?t=includes/master&p=client.php&clientnumber=<?php echo $clientnumber; ?>&view=edit"
           id="renewButton<?php echo $clientnumber; ?>"
           class="btn btn-danger btn-sm m-0 px-3 py-2 me-3"
           data-mdb-tooltip-init
           data-mdb-placement="top"
           data-mdb-trigger="hover"
           title="Renewal Setup Incomplete">
            <i class="fad fa-person-walking-arrow-loop-left"></i>
        </a>
        <?php
                } else {
                    // We have a mode (client/agent/broker)
                    if ($rnCount === 1 && is_array($renewData)) {
                        // Already one renewal record – treat as "sent"
                        $buttonColor = "success sentButton";
                        $buttonText  = "Renewal Sent";

                        $sentDate    = !empty($renewData['date'])
                            ? date('d-m-Y', (int)$renewData['date'])
                            : $renewalDate;
                        $invoiceName = $renewData['invoiceName'] ?? '';
                        $renewId     = $renewData['id'] ?? '';
                        ?>
        <button
                type="button"
                id="A<?php echo $clientnumber; ?>"
                class="btn btn-<?php echo $buttonColor; ?> btn-sm m-0 px-3 py-2 me-3 position-relative text-dark"
                data-client="<?php echo $clientnumber; ?>"
                data-clientname="<?php echo $clientNameDs; ?>"
                data-mode="<?php echo htmlspecialchars($modeLabel, ENT_QUOTES, 'UTF-8'); ?>"
                data-name="<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?>"
                data-date="<?php echo $sentDate; ?>"
                data-rendate="<?php echo $renewalDate; ?>"
                data-email1="<?php echo htmlspecialchars((string)$email1, ENT_QUOTES, 'UTF-8'); ?>"
                data-email2="<?php echo htmlspecialchars((string)$email2, ENT_QUOTES, 'UTF-8'); ?>"
                data-id="<?php echo htmlspecialchars((string)$renewId, ENT_QUOTES, 'UTF-8'); ?>"
                data-file="<?php echo htmlspecialchars((string)$invoiceName, ENT_QUOTES, 'UTF-8'); ?>"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="<?php echo $buttonText; ?>">
            <i class="fad fa-person-walking-arrow-loop-left"></i>
            <?php echo $autoIcon; ?>
        </button>
        <?php
                    } else {
                        // No renewal yet – send renewal
                        $buttonColor = "secondary renewButton";
                        $buttonText  = "Send " . $modeLabel . " Renewal";

                        $renewId     = $renewData['id'] ?? '';
                        $sentDate    = !empty($renewData['date'])
                            ? date('d-m-Y', (int)$renewData['date'])
                            : $renewalDate;
                        $invoiceName = $renewData['invoiceName'] ?? '';
                        ?>
        <button
                type="button"
                id="A<?php echo $clientnumber; ?>"
                class="btn btn-<?php echo $buttonColor; ?> btn-sm m-0 px-3 py-2 me-3 position-relative text-dark"
                data-client="<?php echo $clientnumber; ?>"
                data-clientname="<?php echo $clientNameDs; ?>"
                data-mode="<?php echo htmlspecialchars($modeLabel, ENT_QUOTES, 'UTF-8'); ?>"
                data-name="<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?>"
                data-contract="<?php echo htmlspecialchars((string)($list['contract_number'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                data-fee="<?php echo htmlspecialchars((string)$rate, ENT_QUOTES, 'UTF-8'); ?>"
                data-date="<?php echo $sentDate; ?>"
                data-rendate="<?php echo $renewalDate; ?>"
                data-email1="<?php echo htmlspecialchars((string)$email1, ENT_QUOTES, 'UTF-8'); ?>"
                data-email2="<?php echo htmlspecialchars((string)$email2, ENT_QUOTES, 'UTF-8'); ?>"
                data-id="<?php echo htmlspecialchars((string)$renewId, ENT_QUOTES, 'UTF-8'); ?>"
                data-file="<?php echo htmlspecialchars((string)$invoiceName, ENT_QUOTES, 'UTF-8'); ?>"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="<?php echo $buttonText; ?>">
            <i class="fad fa-person-walking-arrow-loop-left"></i>
            <?php echo $autoIcon; ?>
        </button>
        <?php
                    }
                }
                ?>

    </td>
</tr>
<?php
    }
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="note note-light mb-3 col-12 col-md-9">
            <strong>Client Renewals:</strong> Overview of when each client’s subscription is due for renewal.
            Clients are grouped by urgency, allowing you to quickly identify overdue accounts, upcoming renewals, and those scheduled further ahead.
        </div>

        <div class="col-12 col-md-3">
            <span class="float-md-end noprint">
                <button
                        type="button"
                        id="btnRenewalsCsv"
                        class="btn btn-secondary"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Export renewals to CSV">
                    <i class="fad fa-file-csv me-2"></i>CSV
                </button>

                <button
                        type="button"
                        id="btnRenewalsPdf"
                        class="btn btn-secondary"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Generate printable PDF view">
                    <i class="fad fa-file-pdf me-2"></i>PDF
                </button>

                <button
                        type="button"
                        id="btnRenewalsPrint"
                        class="btn btn-secondary"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Print renewals">
                    <i class="fad fa-print me-2"></i>Print
                </button>
            </span>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card shadow-4-strong mb-5">
                <div class="card-body py-2">
                    <div class="row g-2">
                        <div class="col-12 col-md-4">
                            <div class="note note-danger mb-0">
                                <strong>Overdue:</strong> <?php echo count($overdue); ?>
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <div class="note note-warning mb-0">
                                <strong>Due in next 30 days:</strong> <?php echo count($due30); ?>
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <div class="note note-success mb-0">
                                <strong>Due in more than 30 days:</strong> <?php echo count($future); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            // Shared column widths so all three tables line up (your updated widths)
            $colgroup = '
                <colgroup>
                    <col style="width: 20%;">
                    <col style="width: 20%;">
                    <col style="width: 10%;">
                    <col style="width: 15%;">
                    <col style="width: 15%;">
                    <col style="width: 20%;">
                </colgroup>
            ';
            ?>
            <div id="renewalsContainer">
                <!-- 1. Overdue -->
                <div class="card shadow-4-strong my-5">
                    <div class="note note-danger d-flex justify-content-between align-items-center">
                        <span><i class="fad fa-exclamation-triangle me-2"></i>Overdue renewals</span>
                        <span class="badge bg-light text-dark noprint"><?php echo count($overdue); ?> client(s)</span>
                    </div>
                    <div class="card-body p-2">
                        <div class="table-responsive">
                            <table id="tbl_overdue" class="table table-sm table-striped align-middle mb-0" style="width: 100%">
                                <?php echo $colgroup; ?>
                                <thead>
                                    <tr>
                                        <th>Client</th>
                                        <th>Agent/Broker</th>
                                        <th>Renewal date</th>
                                        <th>Status</th>
                                        <th class="text-center">Rate</th>
                                        <th class="text-end noprint">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php renderRenewalRows($overdue); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 2. Due in next 30 days -->
                <div class="card shadow-4-strong my-5">
                    <div class="note note-warning d-flex justify-content-between align-items-center">
                        <span><i class="fad fa-hourglass-half me-2"></i>Due in next 30 days</span>
                        <span class="badge bg-light text-dark noprint"><?php echo count($due30); ?> client(s)</span>
                    </div>
                    <div class="card-body p-2">
                        <div class="table-responsive">
                            <table id="tbl_due30" class="table table-sm table-striped align-middle mb-0" style="width: 100%">
                                <?php echo $colgroup; ?>
                                <thead>
                                    <tr>
                                        <th>Client</th>
                                        <th>Agent/Broker</th>
                                        <th>Renewal date</th>
                                        <th>Status</th>
                                        <th class="text-center">Rate</th>
                                        <th class="text-end noprint">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php renderRenewalRows($due30); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 3. Due in more than 30 days -->
                <div class="card shadow-4-strong my-5">
                    <div class="note note-success d-flex justify-content-between align-items-center">
                        <span><i class="fad fa-calendar-alt me-2"></i>Due in more than 30 days</span>
                        <span class="badge bg-light text-dark noprint"><?php echo count($future); ?> client(s)</span>
                    </div>
                    <div class="card-body p-2">
                        <div class="table-responsive">
                            <table id="tbl_future" class="table table-sm table-striped align-middle mb-0" style="width: 100%">
                                <?php echo $colgroup; ?>
                                <thead>
                                    <tr>
                                        <th>Client</th>
                                        <th>Agent/Broker</th>
                                        <th>Renewal date</th>
                                        <th>Status</th>
                                        <th class="text-center">Rate</th>
                                        <th class="text-end noprint">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php renderRenewalRows($future); ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div> <!-- /col-12 -->
    </div> <!-- /row -->
</div> <!-- /container-fluid -->


<script>
window.addEventListener('enrep:emailSent', (e) => {
    if (e.detail && e.detail.success) {
        showResponse('success', 'Email sent successfully.');
        getRenewals('current'); // refresh renewals list
    } else {
        showResponse('warning', 'Email not sent or cancelled.');
    }
});
// --- function setLapse(i) ---
function setLapse(i) {
    const formData = new FormData();
    formData.append('FUNCTION', 'setLapse');
    formData.append('clientnumber', i);
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            if (data.trim() === "success") { // Use .trim() directly on string
                const element = document.getElementById('R' + i);
                if (element) {
                    element.style.backgroundColor = '#82e7d2';
                    element.style.border = '1px solid #169f85';
                }
                showResponse('success', 'The client status has been set to LAPSED');
                // Assuming confirmBox.modal('hide') is for an external modal library
                // You'll need to call the hide method on your modal instance.
                // Example if you have a modal instance: confirmModalInstance.hide();
                // If it's a global function:
                if (typeof confirmBox === 'function') { // Check if confirmBox exists and is a function
                    document.getElementById('confirmBox').modal(
                        'hide'); // Assuming this works with your modal library
                }


                setTimeout(() => {
                    if (element) {
                        element.style.transition = 'opacity 0.5s ease-out'; // Add transition for fadeOut
                        element.style.opacity = '0'; // Start fade
                        setTimeout(() => {
                            element.style.display = 'none'; // Hide after transition
                            element.style.removeProperty('transition'); // Clean up
                        }, 500); // Match transition duration
                    }
                }, 3000);
            }
        })
        .catch(error => {
            console.error('Error setting lapse:', error);
        });
}


// --- Event listener for $(document).on('click', '.emailButton', function() { ... }) ---
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('emailButton')) {
        const popupBoxBody = document.querySelector('#popupBox .modal-body');
        if (popupBoxBody) {
            popupBoxBody.innerHTML = '';
        }

        const target = event.target.dataset.href;
        const string = event.target.dataset.values;
        const dest = encodeURI(
            `${target}?mode=popup&data=${string}`); // Use template literals for cleaner string concat

        // Assuming $('#popupBox').modal('show'); and .load() are for an external modal library
        // and its load functionality.
        const popupBox = document.getElementById('popupBox');
        if (popupBox && popupBox.modal) { // Check if modal function exists on the element
            popupBox.modal('show');
        } else {
            // Fallback or log if modal is not a direct function on the element
            console.warn('#popupBox.modal() not found. Ensure your modal library is correctly initialized.');
        }


        // The .load() function loads content via AJAX.
        // Pure JS equivalent would be fetching the content and inserting it.
        fetch(dest)
            .then(response => response.text())
            .then(html => {
                if (popupBoxBody) {
                    popupBoxBody.innerHTML = html;
                }
            })
            .catch(error => {
                console.error('Error loading popup content:', error);
            });
    }
});


document.addEventListener('click', function(event) {
    if (event.target.classList.contains('renewButton')) {
        const client = event.target.dataset.client;
        const clientname = event.target.dataset.clientname;
        const contract = event.target.dataset.contract;
        const fee = event.target.dataset.fee;
        const mode = event.target.dataset.mode;
        const name = event.target.dataset.name;
        const email1 = event.target.dataset.email1;
        const email2 = event.target.dataset.email2;
        const id = event.target.dataset.id;
        const formattedFee = new Intl.NumberFormat('en-GB', {
            style: 'currency',
            currency: 'GBP'
        }).format(fee);
        // Constructing the HTML string for confirmBox
        var dest = `
            <div class="row mb-5">
                <div class="col-12 text-center"><h6>Are you sure you wish to send renewal documentation to the ${mode}?</h6></div>
                <div class="col-12 text-center mt-4">Renewal of <strong>${clientname}</strong>, contract number <strong>${contract}</strong> - <strong>${formattedFee}</strong></div>
            </div>
            <div class="row">
                <div class="col-6">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" id="scheduleAttach">
                        <label class="form-check-label" for="scheduleAttach">Attach schedule</label>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" id="plantAttach" checked>
                        <label class="form-check-label" for="plantAttach">Attach plant list</label>
                    </div>
                </div>
            </div>
            <div id="loadingObject" style="position: fixed; top:50%; width:100%; display:none">
                <h1 class="text-center">
                    <i class="fad fa-file-invoice fa-spin fa-3x fa-fw" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i>
                    <br>Generating Renewal documents <br><small>Please wait</small>
                </h1>
            </div>
        `;


        loadModalContent(dest, "popupBox", "modal-lg", 1060, "true", `Renew ${mode}`, "cancelConfirm", () =>
            renew(client, clientname, mode, id, name, email1, email2));
    }
});


// --- function renew(...) ---
function renew(client, clientname, mode, id, name, email1, email2) {
    showLoadingIndicator("Generating Renewal Documantation", 'fa-file-invoice fa-spin', 'popupBox')

    const scheduleAttach = document.getElementById('scheduleAttach');
    const plantAttach = document.getElementById('plantAttach');

    const shed = scheduleAttach && scheduleAttach.checked ? "1" : "0";
    const plant = plantAttach && plantAttach.checked ? "1" : "0";

    const formData1 = new FormData();
    formData1.append('mode', mode);
    formData1.append('clientnumber', client);
    formData1.append('tenant', TENANT_URL);

    fetch(ROOT_URL + '/includes/finance/renewals/processRenew.php', {
            method: 'POST',
            body: formData1
        })
        .then(response => response.text())
        .then(ret => {
            //debug(ret)
            const inv = ret.trim();
            if (inv !== "error") {
                const formData2 = new FormData();
                formData2.append('clientnumber', client);
                formData2.append('invNo', inv);
                formData2.append('rtype', mode);
                formData2.append('schedule', shed);
                formData2.append('plantlist', plant);
                formData2.append('id', id);
                formData2.append('tenant', TENANT_URL);

                fetch(ROOT_URL + '/includes/engines/renewal.php', {
                        method: 'POST',
                        body: formData2
                    })
                    .then(response => response.text())
                    .then(ret2 => {
                        const payload = {
                            clientNumber: client,
                            clientName: name,
                            primaryEmail: email1,
                            secondaryEmail: email2,
                            subject: `${clientname} renewal `,
                            message: 'Your Contract Renewal Notice',
                            filePath: 'renewals',
                            fileName: `${inv}_${client}_renewal.pdf`,
                            invoiceNumber: inv,
                            mode: mode
                        };

                        const encoded = encodeURIComponent(JSON.stringify(payload));
                        const popupBoxBody = document.querySelector('#popupBox .modal-body');
                        if (popupBoxBody) {
                            popupBoxBody.innerHTML = '';
                        }
                        killModal('popupBox')
                        const dest = encodeURI(ROOT_URL +
                            `/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`
                        );
                        loadModalContent(dest, "emailBox", "modal-xl", 1060, "true", "Send Renewal");

                    })
                    .catch(error => {
                        console.error('Error in renewal.php fetch:', error);
                    });
            }
        })
        .catch(error => {
            console.error('Error in processRenew.php fetch:', error);
        });
}


// --- function renewResend(...) ---
function renewResend(id, clientname, mode, client, name, email1, email2, file) {
    showLoadingIndicator("Rebuilding Renewal Documents", 'fa-file-invoice fa-spin', 'confirmBox')

    const formData = new FormData();
    formData.append('clientnumber', client);
    formData.append('rtype', mode);
    formData.append('id', id);
    formData.append('tenant', TENANT_URL);
    //alert(client)
    fetch(ROOT_URL + '/includes/engines/renewal.php', {
            method: 'POST',
            body: formData
        })

        .then(ret2 => {

            const payload = {
                clientNumber: client,
                clientName: name,
                primaryEmail: email1,
                secondaryEmail: email2,
                subject: `${clientname} renewal `,
                message: 'Your Contract Renewal Notice',
                filePath: 'renewals',
                fileName: `${file}`,
                //invoiceNumber: inv,
                mode: mode
            };
            const encoded = encodeURIComponent(JSON.stringify(payload));
            killModal('confirmBox')
            const dest = encodeURI(ROOT_URL +
                `/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`);
            loadModalContent(dest, "emailBox", "modal-xl", 1060, "true", "Resend Renewal");

            fetch(dest)
                .then(response => response.text())

                .catch(error => {
                    console.error('Error loading resend mailer popup content:', error);
                });
        })
        .catch(error => {
            console.error('Error in renewResend renewal.php fetch:', error);
        });
}



document.addEventListener('click', function(event) {
    if (event.target.classList.contains('sentButton')) {
        const client = event.target.dataset.client;
        const clientname = event.target.dataset.clientname;
        const name = event.target.dataset.name;
        const email1 = event.target.dataset.email1;
        const email2 = event.target.dataset.email2;
        const file = event.target.dataset.file;
        const target = event.target.dataset.client;
        const mode = event.target.dataset.mode;
        const date = event.target.dataset.date;
        const renDate = event.target.dataset.rendate;
        const id = event.target.dataset.id;

        const confirmBoxContent = `
          <div class="position-relative">
  <div class="modal-body">


    <div class="alert alert-warning p-1 mt-n4" role="alert">      
      <i class="fad fa-exclamation-triangle me-2 text-warning"></i> <strong>You sent the ${mode} a renewal notice on ${date}.</strong>    
    </div>

    <div class="row align-items-center mb-4">
        <div class="col-12 col-md-6  d-flex justify-content-start">
            <label for="renewDate" class="col-sm-4 col-form-label">Date of Renewal:</label>
            <div class="col-sm-8">
                <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <input type="text" id="renewDate" name="renewDate" class="form-control" placeholder="Select date" value="${renDate}" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" />
                </div>
            </div>
        </div>
        <div class="col-12 col-md-6 d-flex justify-content-end">
            <label for="renewDate" class="col-sm-4 col-form-label">Purchase Order No:</label>
            <div class="col-sm-8">
                <div class="w-100">
                <input type="text" id="purchaseOrder" class="form-control" value="" placeholder="only enter if required">
                </div>
            </div>
        </div>
    </div>

    <fieldset class="mb-4">
      <legend class="visually-hidden">Renewal Actions</legend>
      <div class="row text-center g-3">
        <div class="col-4">
          <div class="form-check d-flex justify-content-start">
            <input class="form-check-input" type="radio" name="invoiceSend" id="resend" value="3"/>
            <label class="form-check-label" for="resend">Resend Renewal</label>
          </div>
        </div>
        <div class="col-4 d-flex justify-content-center">
          <a href="renewals/${file}" target="_blank" class="btn btn-outline-secondary">View Renewal</a>
        </div>
        <div class="col-4">
          <div class="form-check d-flex justify-content-end">
            <input class="form-check-input" type="radio" name="invoiceSend" id="revoke" value="4" />
            <label class="form-check-label" for="revoke">Cancel Renewal</label>
          </div>
        </div>
      </div>
    </fieldset>

    <fieldset>
      <legend class="visually-hidden">Invoice Options</legend>
      <div class="row text-center g-3">
        <div class="col-4">
          <div class="form-check d-flex justify-content-start">
            <input class="form-check-input" type="radio" name="invoiceSend" id="invoiceYes" value="1" checked />
            <label class="form-check-label" for="invoiceYes">Renew & Send Invoice</label>
          </div>
        </div>
        <div class="col-4">
          <div class="form-check d-flex justify-content-center">
            <input class="form-check-input" type="radio" name="invoiceSend" id="invoiceNo" value="0" />
            <label class="form-check-label" for="invoiceNo">Just Renew</label>
          </div>
        </div>
        <div class="col-4 d-flex justify-content-end">
          <div class="form-check">
            <input class="form-check-input" type="radio" name="invoiceSend" id="invoiceLapse" value="2" />
            <label class="form-check-label text-danger" for="invoiceLapse">Lapse</label>
          </div>
        </div>
      </div>
    </fieldset>

  </div>
</div>

        `;


        loadModalContent(confirmBoxContent, 'confirmBox', 'modal-xl', 1060, 'true', `Renew ${mode}`,
            'cancelConfirm', () => renewConfirm(id, target, client, clientname, mode, name, email1, email2,
                file))

    }
});


function renewConfirm(id, target, client, clientname, mode, name, email1, email2, file) {
    const renewDateInput = document.getElementById('renewDate');
    const purchaseOrder = document.getElementById('purchaseOrder')?.value.trim() || '';
    const date = renewDateInput ? renewDateInput.value : '';

    const invoiceSendRadios = document.querySelectorAll('input[name="invoiceSend"]');
    let selectedMode = '';
    for (const radio of invoiceSendRadios) {
        if (radio.checked) {
            selectedMode = radio.value;
            break;
        }
    }

    if (date === '') {
        showResponse('warning', 'You must set a date of renewal');
        return false;
    }

    // Common function for making post requests
    const makePostRequest = (func, params, successCallback) => {
        const formData = new URLSearchParams();
        formData.append('FUNCTION', func);
        for (const key in params) {
            formData.append(key, params[key]);
        }
        formData.append('tenant', TENANT_URL);

        fetch(ROOT_URL + '/includes/finance/renewals/renewal_functions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {

                if (successCallback) {
                    successCallback(data);
                }
            })
            .catch(error => {
                console.error(`Error in ${func} request:`, error);
            });
    };


    if (selectedMode === '0') {
        makePostRequest('setJustRenewed', {
            id,
            date
        }, () => {
            showResponse('success', 'Renewal completed successfully');
            killModal('confirmBox')
            getRenewals('current');
        });
    } else
    if (selectedMode === '1') {
        makePostRequest('setRenewed', {
            id,
            date,
            purchaseOrder
        }, (ret) => {
            const data = JSON.parse(ret);
            const brokercom = data.target === "broker" ? 1 : 0;
            const agentcom = data.target === "agent" ? 1 : 0;

            const invoiceFormData = new URLSearchParams();
            invoiceFormData.append('invNo', data.invoice);
            invoiceFormData.append('rtype', 'client');
            invoiceFormData.append('brokerCom', brokercom);
            invoiceFormData.append('agentCom', agentcom);
            invoiceFormData.append('tenant', TENANT_URL);
            invoiceFormData.append('purchaseOrder', purchaseOrder);

            fetch(ROOT_URL + '/includes/engines/invoice.php', {
                    method: 'POST',
                    body: invoiceFormData
                })
                .then(response => response.text())
                .then(() => {
                    // 🔔 Listen once for the email-sent event and refresh renewals
                    const onEmailSent = (e) => {
                        const ok = !!(e && e.detail && e.detail.success);
                        if (ok) {
                            showResponse('success', 'Renewal invoice email sent.');
                            getRenewals('current');
                        } else {
                            showResponse('warning', 'Email window closed without sending.');
                        }
                    };
                    window.addEventListener('enrep:emailSent', onEmailSent, {
                        once: true
                    });

                    const payload = {
                        clientNumber: data.client,
                        clientName: data.clientName,
                        primaryEmail: data.billingEmail,
                        secondaryEmail: data.email,
                        subject: data.emailSubject,
                        message: data.emailMessage,
                        filePath: data.emailFolder,
                        fileName: data.emailFile,
                        emailFunction: 'renewalInvoice',
                        invoiceNumber: data.emailInvoice,
                        mode: mode // keep your existing mode
                    };
                    const encoded = encodeURIComponent(JSON.stringify(payload));
                    killModal('confirmBox');
                    const dest = encodeURI(
                        ROOT_URL + `/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`
                    );
                    loadModalContent(dest, "emailBox", "modal-xl", 1060, "true", "Send Renewal Invoice");
                })
                .catch(error => {
                    console.error('Error in invoice.php fetch:', error);
                    showResponse('danger', 'Failed to generate renewal invoice PDF.');
                });
        });
    } else if (selectedMode === '2') {
        makePostRequest('setLapse', {
            clientnumber: target,
            date
        }, () => {
            showResponse('success', 'Client lapsed successfully');
            killModal('confirmBox')
            getRenewals('current');
        });
    } else if (selectedMode === '3') {
        renewResend(id, clientname, mode, client, name, email1, email2, file);

    } else if (selectedMode === '4') {
        makePostRequest('revoke', {
            id
        }, () => {
            showResponse('success', 'Renewal removed successfully');
            killModal('confirmBox')
            getRenewals('current');
        });
    }
    return true; // Original function returned true, so preserving
}


// --- function renewButtonSwitch(target) ---
function renewButtonSwitch(target) {
    const elementA = document.getElementById('A' + target);
    if (elementA) {
        elementA.classList.remove('renewButton', 'btn-secondary');
        elementA.classList.add('sentButton', 'btn-success');
    }
    getRenewals('current');
}


// --- function renewButtonHide(target) ---
function renewButtonHide(target) {
    const elementR = document.getElementById('R' + target);
    if (elementR) {
        elementR.style.transition = 'opacity 0.5s ease-out';
        elementR.style.opacity = '0';
        setTimeout(() => {
            elementR.style.display = 'none';
            elementR.style.removeProperty('transition');
        }, 500);
    }
}


// --- function confirmSent(invoice) ---
function confirmSent(invoice) {
    const formData = new FormData();
    formData.append('FUNCTION', 'setDelivered');
    formData.append('inv', invoice);
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            if (typeof confirmBox === 'function') {
                document.getElementById('confirmBox').modal('hide');
            }
            showResponse('success', 'Set as delivered successfully');
            // If you were toggling a badge, uncomment this:
            // const emElement = document.getElementById('em' + invoice);
            // if (emElement) {
            //     emElement.innerHTML = '<span class="badge badge-success m-0" style="font-size:12px; display:block">SENT</span>';
            // }
        })
        .catch(error => {
            console.error('Error confirming sent status:', error);
        });
}



document.addEventListener('DOMContentLoaded', function() {
    // === BUTTON HANDLERS ===
    var btnCsv = document.getElementById('btnRenewalsCsv');
    var btnPdf = document.getElementById('btnRenewalsPdf');
    var btnPrint = document.getElementById('btnRenewalsPrint');

    if (btnCsv) {
        btnCsv.addEventListener('click', function() {
            exportRenewalsCsv();
        });
    }

    if (btnPdf) {
        btnPdf.addEventListener('click', function() {
            generateRenewalsPdfAndOpen();
        });
    }

    if (btnPrint) {
        btnPrint.addEventListener('click', function() {
            const src = document.getElementById('renewalsContainer');
            if (!src) {
                showResponse('danger', 'Nothing to print');
                return;
            }

            // Remove any previous temp container
            const existing = document.getElementById('renewalsPrintContainer');
            if (existing) existing.remove();

            // Clone, strip links + Actions column, and hide
            const clone = src.cloneNode(true);
            stripLinksFromElement(clone);
            stripActionsColumn(clone);
            clone.id = 'renewalsPrintContainer';
            clone.style.display = 'none';
            document.body.appendChild(clone);

            // Now print the cleaned clone
            printContainer('renewalsPrintContainer', {
                orientation: 'landscape', // or 'portrait'
                header: `<p>Renewals</p>`,
                footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
                logoUrl: 'images/company/logo.jpg',
                styles: [
                    `${ROOT_URL}/src/css/print.css`,
                ],
            });
        });
    }
});

/* ===== CSV EXPORT (unchanged) ===== */

function exportRenewalsCsv() {
    var tableIds = ['tbl_overdue', 'tbl_due30', 'tbl_future'];
    var rows = [];
    var headerCaptured = false;

    tableIds.forEach(function(id) {
        var table = document.getElementById(id);
        if (!table) return;

        var thead = table.tHead;
        var tbody = table.tBodies[0];

        if (!headerCaptured && thead && thead.rows.length) {
            var headerCells = thead.rows[0].cells;
            var headerRow = [];
            for (var i = 0; i < headerCells.length; i++) {
                headerRow.push(cleanCellText(headerCells[i].innerText));
            }
            rows.push(headerRow);
            headerCaptured = true;
        }

        if (!tbody) return;
        Array.prototype.forEach.call(tbody.rows, function(tr) {
            if (tr.style.display === 'none') {
                // Respect current filtering/search (skip hidden rows)
                return;
            }
            var cells = tr.cells;
            var row = [];
            for (var j = 0; j < cells.length; j++) {
                row.push(cleanCellText(cells[j].innerText));
            }
            rows.push(row);
        });
    });

    if (!rows.length) {
        showResponse('warning', 'No renewal records to export.');
        return;
    }

    var csvContent = rows.map(function(row) {
        return row.map(csvEscape).join(',');
    }).join('\r\n');

    // Add BOM for Excel
    var blob = new Blob(['\uFEFF' + csvContent], {
        type: 'text/csv;charset=utf-8;'
    });
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = 'renewals_' + formatNowForFilename() + '.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

function cleanCellText(text) {
    if (!text) return '';
    return text.replace(/\s+/g, ' ').trim();
}

function csvEscape(value) {
    if (value == null) value = '';
    value = String(value);
    if (/[",\r\n]/.test(value)) {
        value = '"' + value.replace(/"/g, '""') + '"';
    }
    return value;
}

function formatNowForFilename() {
    var d = new Date();
    var pad = function(n) {
        return n < 10 ? '0' + n : n;
    };
    return d.getFullYear() +
        '' + pad(d.getMonth() + 1) +
        '' + pad(d.getDate()) +
        '_' + pad(d.getHours()) +
        '' + pad(d.getMinutes());
}

/* ===== PDF (using report.php) ===== */

async function generateRenewalsPdfAndOpen() {
    const src = document.getElementById('renewalsContainer');
    if (!src) {
        showResponse('danger', 'Nothing to export');
        return;
    }

    // Build title
    const today = new Date();
    const pad = (n) => (n < 10 ? '0' + n : n);
    const dStr = `${pad(today.getDate())}-${pad(today.getMonth() + 1)}-${today.getFullYear()}`;
    const title = `renewals_${dStr}`;

    // Create a cleaned clone (no links, no Actions col)
    const clone = src.cloneNode(true);
    stripLinksFromElement(clone);
    stripActionsColumn(clone);
    const cleanHtml = clone.innerHTML;

    const payload = new URLSearchParams({
        tenant: TENANT_URL,
        clientnumber: '0',
        type: title,
        content: cleanHtml,
        format: 'A4-L'
    });

    let href = '';
    try {
        const res = await fetch(ROOT_URL + '/includes/engines/report.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: payload.toString()
        });

        const txt = (await res.text()).trim();

        try {
            const j = JSON.parse(txt);
            if (j && j.href) href = j.href;
        } catch (_) {
            if (txt.endsWith('.pdf')) href = txt;
        }
    } catch (_) {
        // fall through, we'll use default path
    }

    if (!href) {
        href = `output/reps/0_${title}.pdf`;
    }

    try {
        window.open(href, '_blank');
    } catch (_) {}

    showResponse('success', 'Renewals report generated');
}

/* ===== HELPERS FOR LINK + ACTIONS REMOVAL ===== */

function stripLinksFromElement(rootEl) {
    if (!rootEl) return;
    const links = rootEl.querySelectorAll('a');
    links.forEach((a) => {
        const span = document.createElement('span');
        span.innerHTML = a.innerHTML; // keep inner content
        if (a.className) span.className = a.className;
        a.replaceWith(span);
    });
}

function stripActionsColumn(rootEl) {
    if (!rootEl) return;

    const tables = rootEl.querySelectorAll('table');
    tables.forEach((table) => {
        // Remove last <col> from colgroup (Actions column)
        const colgroup = table.querySelector('colgroup');
        if (colgroup && colgroup.lastElementChild) {
            colgroup.removeChild(colgroup.lastElementChild);
        }

        // Remove last header cell
        if (table.tHead && table.tHead.rows.length) {
            const headerRow = table.tHead.rows[0];
            if (headerRow.cells.length > 0) {
                headerRow.deleteCell(-1);
            }
        }

        // Remove last cell from each body row
        Array.prototype.forEach.call(table.tBodies, (tbody) => {
            Array.prototype.forEach.call(tbody.rows, (row) => {
                if (row.cells.length > 0) {
                    row.deleteCell(-1);
                }
            });
        });
    });
}


document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item ">Finance - Renewals</li> ';
</script>