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


switch ($_REQUEST['M']) {
    default:
        $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="navbar navbar-expand-lg">
    <div class="collapse navbar-collapse">
        <ul class="navbar-nav me-auto">
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_invoices-new.php" class="btn btn-secondary">New
                    Invoice</a>
            </li>
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_unpaid.php" class="btn btn-secondary">
                    Unpaid Invoices
                    <span class="badge rounded-pill bg-dark ms-2"><?= $unpaidCount ?></span>
                </a>
            </li>
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_paid.php" class="btn btn-secondary">Paid Invoices</a>
            </li>
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_invoice_blank.php" class="btn btn-secondary">Blank
                    Invoice</a>
            </li>
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_renewal_invoice.php" class="btn btn-secondary">
                    Renewal Invoice
                    <span class="badge rounded-pill bg-dark ms-2"><?= $renewalCount ?></span>
                </a>
            </li>
            <li class="nav-item me-2">
                <a href="index.php?t=includes/finance&p=finance_archive.php" class="btn btn-secondary"
                    style="box-shadow:0 2px 5px 0 rgb(183 28 28 / 16%), 0 2px 10px 0 rgb(183 28 28 / 12%);">
                    <span class="text-danger">Voided Invoices</span>
                </a>
            </li>
            <li class="nav-item">
                <form class="input-group">
                    <input id="searchTerm" class="form-control" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-dark" type="button" onclick="searchInvoices()">
                        <i class="fad fa-search"></i>
                    </button>
                </form>
            </li>
        </ul>
    </div>
</div>

<div id="searchResults"></div>
<div class="row mt-5"></div>
<div id="financeContent" class="row mt-5">
    <div class="col-12 col-md-6">

        <?php $stmt = $GLOBALS['con']->prepare("SELECT `date_due` FROM `invoices` WHERE `status`='1' or `status`='2' ORDER BY abs(invno) ASC") or die(mysqli_error($GLOBALS['con']));
                $stmt->execute();
                $i = $stmt->get_result();
                $stmt->close();
                $outstanding = 0;
                $overdue = 0;
                while ($run = mysqli_fetch_array($i)) {
                    if ($run['date_due'] > $now) {
                        $outstanding++;
                    }
                    if ($run['date_due'] < $now) {
                        $overdue++;
                    }
                } ?>
        <div class="row mb-3">
            <div class="col-12 col-md-6">
                <p class="lead">Outstanding Invoices - <span class="badge badge-secondary"><?= $outstanding ?></span>
                </p>
            </div>
            <div class="col-12 col-md-6">
                <p class="lead">Overdue Invoices - <span class="badge badge-secondary"><?= $overdue ?></span></p>
            </div>
        </div>

        <hr>
        <div id="renewalList">

            <div id="sending" class="col-md-12 text-center" style="color:#393939">
                <h1>
                    <i class="fad fa-rotate fa-spin fa-3x fa-fw mt-3"
                        style="--fa-primary-color: #2a3f54; --fa-secondary-color: gray; filter: drop-shadow(0 0 5px #000);"></i><br>Loading
                    Renewals<br><small>Please wait</small>

                </h1>
            </div>

        </div>
    </div>

    <div class="col-12 col-md-6">
        <?php $tax = explode('|', getCompanyDetails('taxYear'));
                $vat = explode('|', getCompanyDetails('vatData'));
                if ($vat['1'] == 1) {
                    $vs = "Monthly";
                }
                if ($vat['1'] == 3) {
                    $vs = "Quarterly";
                }
                if ($vat['1'] == 12) {
                    $vs = "Annually";
                }
                $ve = date("1-" . $vat['0'] . "-Y");
                $date = new DateTime($ve);
                $date->modify('+' . $vat['1'] . ' month'); // or you can use '-90 day' for deduct
                $date = $date->format('d-m-Y');
                $ve = $date;
                if (strtotime($ve) > $now) {
                    $badge = "info";
                    $disabled = '';
                }
                if (strtotime($ve) < $now) {
                    $badge = "danger";
                    $disabled = 'disabled';
                }
                ?>
        <div class="row mb-4">
            <div class="col-6 col-md-4 mb-2"><span class="lead">Tax YearEnd: </span><span class="badge badge-info"
                    style="font-size: 13px"><?= date('d-m-Y', $tax['1']) ?></span></div>
            <div class="col-6 col-md-4 mb-2"><span class="lead">Vat Cycle: </span><span class="badge badge-info"
                    style="font-size: 13px"><?= $vs ?></span></div>
            <div class="col-6 col-md-4 mb-2"><span class="lead">Vat Due: </span><a
                    href="index.php?t=includes/finance&p=finance_vat_submission.php"
                    class="<?= $disabled ?> badge badge-<?= $badge ?>" style="font-size: 13px"><?= $ve ?></a></div>
        </div>

        <canvas id="contractChart" width="400" height="150"></canvas>
        <script src="<?= ROOT_URL ?>/packages/Chart.js/src/chart.js"></script>
        <?php
                function monthCalc($m)
                {
                    $currentYear = date('Y');
                    $tot = 0;
                    $n = calendarMonth($m, $currentYear);
                    $s = strtotime("1-" . $m . "-" . $currentYear . " 00:00:00");
                    $e = strtotime($n . "-" . $m . "-" . $currentYear . " 23:59:59");
                    $stmt = $GLOBALS['con']->prepare("SELECT `rate_per_hour` FROM `clientdetails` WHERE `statuslive`='1' AND `renewal_date` BETWEEN '$s' AND '$e' ") or die(mysqli_error($GLOBALS['con']));
                    $stmt->execute();
                    $i = $stmt->get_result();
                    $stmt->close();
                    while ($mc = mysqli_fetch_array($i)) {
                        $tot = $tot + $mc['rate_per_hour'];
                    }
                    return $tot;
                }
                function invCalc($m)
                {
                    $currentYear = date('Y');
                    $tot = 0;
                    $n = calendarMonth($m, $currentYear);
                    $s = strtotime("1-" . $m . "-" . $currentYear . " 00:00:00");
                    $e = strtotime($n . "-" . $m . "-" . $currentYear . " 23:59:59");
                    $stmt = $GLOBALS['con']->prepare("SELECT `totals` FROM `invoices` WHERE `status`='3' AND `date_paid` BETWEEN '$s' AND '$e' ") or die(mysqli_error($GLOBALS['con']));
                    $stmt->execute();
                    $i = $stmt->get_result();
                    $stmt->close();
                    while ($mc = mysqli_fetch_array($i)) {
                        $t = explode('|', $mc['totals']);
                        $tot = $tot + $t[0];
                    }
                    return $tot;
                };
                ?>

        <script>
        var ctx = document.getElementById('contractChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            responsive: true,
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
                    'October', 'November', 'December'
                ],
                datasets: [{
                    label: 'Accounted Income',
                    data: [
                        <?= invCalc(1) ?>,
                        <?= invCalc(2) ?>,
                        <?= invCalc(3) ?>,
                        <?= invCalc(4) ?>,
                        <?= invCalc(5) ?>,
                        <?= invCalc(6) ?>,
                        <?= invCalc(7) ?>,
                        <?= invCalc(8) ?>,
                        <?= invCalc(9) ?>,
                        <?= invCalc(10) ?>,
                        <?= invCalc(11) ?>,
                        <?= invCalc(12) ?>
                    ],
                    backgroundColor: ['rgba(42, 63, 84, 0.5)'],
                    borderColor: ['rgba(255, 99, 132, 1)'],
                    borderWidth: 1
                }]
            },

            options: {
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
                        }
                    }
                },
                scales: {
                    yAxes: [{
                        ticks: {

                            beginAtZero: true
                        }
                    }]
                }
            }
        });
        </script>


        <?php $tax = explode('|', getCompanyDetails('taxYear'));
                $vat = explode('|', getCompanyDetails('vatData'));
                if ($vat['1'] == 1) {
                    $vs = "Monthly";
                }
                if ($vat['1'] == 3) {
                    $vs = "Quarterly";
                }
                if ($vat['1'] == 12) {
                    $vs = "Annually";
                }
                $ve = date("1-" . $vat['0'] . "-Y");
                $date = new DateTime($ve);
                $date->modify('+' . $vat['1'] . ' month'); // or you can use '-90 day' for deduct
                $date = $date->format('d-m-Y');
                $ve = $date;
                if (strtotime($ve) > $now) {
                    $badge = "info";
                }
                if (strtotime($ve) < $now) {
                    $badge = "danger";
                }
                ?>


        <canvas id="incomeChart" width="400" height="150"></canvas>
        <script src="<?= ROOT_URL ?>/packages/Chart.js/src/chart.js"></script>


    </div>
</div>

<style>
#renewalList .row .remove {
    display: none;
}
</style>
<script>
function getRenewals(rMode) {
    const params = `rMode=${encodeURIComponent(rMode)}&tenant=${encodeURIComponent(TENANT_URL)}`;
    const url = ROOT_URL + '/includes/finance/renewals/renewals_list.php';

    loadContentAndExecuteScripts(url, 'renewalList', params, () => {
        console.log('Renewals loaded and scripts executed.');
    });
}

document.addEventListener('DOMContentLoaded', () => {
    getRenewals('current');
});


// --- function searchInvoices() ---
function searchInvoices() {
    const searchTermInput = document.getElementById('searchTerm');
    const outputTerm = searchTermInput ? searchTermInput.value : '';

    const formData = new FormData();
    formData.append('FUNCTION', 'searchInvoices');
    formData.append('searchterm', outputTerm);
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(ret => {
            // debug(ret)
            const searchResults = document.getElementById('searchResults');
            const financeContent = document.getElementById('financeContent');

            if (searchResults) {
                searchResults.style.display = 'block';
                searchResults.style.opacity = '0';

                setTimeout(() => {
                    searchResults.style.transition = 'opacity 0.4s ease-in-out';
                    searchResults.style.opacity = '1';
                    searchResults.innerHTML = ret;
                }, 0);

            }
            if (financeContent) {
                financeContent.style.opacity = '0.2';
            }
        })
        .catch(error => {
            console.error('Error searching invoices:', error);
        });
}


// --- Event listener for $('#financeContent').click(function() { closeSearch() }) ---
document.addEventListener('click', function(event) {
    const financeContent = document.getElementById('financeContent');
    // Check if the clicked element is #financeContent or is inside it
    if (financeContent && financeContent.contains(event.target) && event.target === financeContent) {
        closeSearch();
    }
});


// --- function closeSearch() ---
function closeSearch() {
    const searchResults = document.getElementById('searchResults');
    const financeContent = document.getElementById('financeContent');

    if (searchResults) {
        searchResults.style.transition = 'opacity 0.4s ease-in-out';
        searchResults.style.opacity = '0'; // Start fade out

        // Use a timeout to simulate jQuery's fadeOut callback
        setTimeout(() => {
            searchResults.style.display = 'none'; // Hide after fading
            searchResults.innerHTML = ''; // Clear content
            searchResults.style.removeProperty('transition'); // Clean up transition style
        }, 400); // Match the transition duration
    }

    if (financeContent) {
        financeContent.style.opacity = '1';
    }
}


// --- Event listener for $('#datatable').on('click', '.removeButton', function() { ... }) ---
document.addEventListener('click', function(event) {
    // Check if the clicked element has the class 'removeButton' AND is inside '#datatable'
    const datatable = document.getElementById('datatable');
    if (datatable && event.target.classList.contains('removeButton') && datatable.contains(event.target)) {
        const str = event.target.dataset.values; // Access data attributes using .dataset
        confirmBox('Confirm Lapse', 'Are you sure you wish to manually Lapse this client?',
            `setLapse('${str}')`);
    }
});


// --- 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 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;

        // Constructing the HTML string for confirmBox
        var dest = `
            <div class="row mb-5">
                <div class="col-12">Are you sure you wish to send renewal documentation to the ${mode}?</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 + '/functions/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}_${id}_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 d-flex align-items-start" role="alert">
      <i class="fad fa-exclamation-triangle fa-lg me-2 mt-1 text-warning"></i>
      <div>
        <strong>You sent the ${mode} a renewal notice on ${date}.</strong>
        <div>Are you sure you wish to confirm renewal for the client?</div>
      </div>
    </div>

    <div class="row align-items-center mb-4">
        <div class="col-12 col-md-6">
            <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-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" data-mdb-format="dd-mm-yyyy" />
                </div>
            </div>
        </div>
        <div class="col-12 col-md-6">
            <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">
            <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">
            <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">
            <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">
            <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">
          <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');
    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
        }, (ret) => {

            const data = JSON.parse(ret); // Use JSON.parse           
            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(() => {
                    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
                    };
                    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);
                });
        });
    } else if (selectedMode === '2') {
        makePostRequest('setLapse', {
            clientnumber: target,
            date
        }, () => {
            showResponse('success', 'Client lapsed successfully');
            killModal('confirmBox')
        });
    } 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);
        });
}
</script>
<?php
        break;
}
?>
<div id="loading"></div>