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

$stmt = $GLOBALS['con']->prepare("SELECT `invNo` FROM `invoices` WHERE invNo=(SELECT MAX(invNo) FROM `invoices`)")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$i=$stmt->get_result();$stmt->close();
$latest=mysqli_fetch_array($i);
$latestId=$latest['invNo'];

$stmt = $GLOBALS['con']->prepare("SELECT * 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();
while($id=mysqli_fetch_array($i)){$data[]=$id;}
?>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadrumb-item"><a class="text-light" href="index.php?t=includes/finance&p=finance_invoices.php">Finance - Invoices</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadrumb-item active">Outstanding</li>';
</script>
<div id="invoiceData" class="container-fluid px-0 my-4">
    <!-- Header -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start mb-3 px-3">
        <div class="mb-2 mb-md-0">

            <div class="note note-light mb-3"> <strong>You can print or action responses for all outstanding invoices:</strong> To manually mark as paid, select the payment method used before applying the confirmation.</div>

        </div>
        <a href="index.php?t=includes/finance&p=invoiceUnPaid_reports.php"
           class="btn btn-secondary me-3"
           data-mdb-toggle="tooltip"
           title="View Reports">
            <i class="fad fa-file-invoice me-1"></i> View Reports
        </a>
    </div>

    <div class="row mb-4">
    <div class="col-12 mt-3 text-center text-md-start">
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn danger-color-dark text-light filterButtons btn-sm" onclick="addSearch('OVERDUE','expenseTable')" data-mdb-original-title="Filter Overdue invoices">OVERDUE</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn warning-color-dark text-light filterButtons btn-sm" onclick="addSearch('NOT SENT','expenseTable')" data-mdb-original-title="Filter unsent invoices">NOT SENT</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn success-color-dark text-light filterButtons btn-sm" onclick="addSearch('SENT','expenseTable')" data-mdb-original-title="Filter invoices sent">SENT</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn color bg-white filterButtons btn-sm" onclick="clearSearch('expenseTable')" data-mdb-original-title="Reset filters"><i class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters</button>

    </div>
</div>

    <table id="expenseTable" class="table table-striped table-hover align-middle w-100 table-sm">
        <thead class="table-dark">
            <tr>
                <th>Invoice #</th>
                <th>Client</th>
                <th>Agent/Broker</th>
                <th>Contract #</th>
                <th>Amount</th>
                <th>Date of Invoice</th>
                <th>Status</th>
                <th>Payment Type</th>
                <th>Payee</th>
                <th>Date Paid</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php $mTotal=0;
                foreach($data as $row):
          // Invoice basics
          $invNoFormatted = sprintf("%06d", $row['invNo']);
          $address = unserialize($row['address']);
          $totals = explode('|', $row['totals']);
          $sub = (float)str_replace(',', '', $totals[0]);
          $vat = (float)str_replace(',', '', $totals[1]);
          $grandTotal = $sub + $vat;
          $invoiceDate = date('d-m-Y', $row['date']);
          $isOverdue = ($row['date_due'] < time());
          
          $mTotal += $grandTotal;
          $grandTotal = number_format($grandTotal, 2);
          // Status badge
          $statusBadge = '';

            if (!empty($row['sent']) && $row['sent'] != 0) {
                $statusBadge = $isOverdue
                    ? '<span class="badge bg-danger">OVERDUE</span>'
                    : '';
            }
          // Name & Agent/Broker link
          $nameLink = '';
          $agentLink = '';
           $stmt = $con->prepare("SELECT billing_name, billing_email, clientname, clientnumber FROM clientdetails WHERE clientnumber=?");
              $stmt->bind_param('i', $row['client']);
              $stmt->execute();
              $cd = $stmt->get_result()->fetch_assoc();
              $stmt->close();
              $clientLink = '<a href="javascript:void(0)" ' .
                          'data-mdb-toggle="tooltip" title="View Statement" ' .
                          'onclick="showStatement(\'client\',' . $row['client'] . ',\'outstanding\')">' .
                          htmlspecialchars($cd['clientname']) . '</a>';
                         $cd['clientname']=str_replace('&#39;','',$row['client']);
                        $cd['billing_name']=str_replace('&#39;','',$cd['billing_name']);
                        $clientName= preg_replace('/[^A-Za-z0-9\-]/', ' ', $cd['clientname']);
                        $billingName= preg_replace('/[^A-Za-z0-9\-]/', ' ', $cd['billing_name']);
                        $email=$cd['email'];
                        $billingEmail=$cd['billing_email'];
          switch($row['target']) {

            case 'agent':
              $stmt = $con->prepare("SELECT agent_name, email, billing_email, agent_number FROM agents WHERE agent_number=?");
              $stmt->bind_param('i', $row['agent']);
              $stmt->execute();
              $ad = $stmt->get_result()->fetch_assoc();
              $stmt->close();
              $nameLink = '<a href="javascript:void(0)" ' .
                          'data-mdb-toggle="tooltip" title="View Statement" ' .
                          'onclick="showStatement(\'agent\',' . $row['agent'] . ',\'outstanding\')">' .
                          htmlspecialchars($ad['agent_name']) . '</a>';
                $email=$ad['email'];
                $billingEmail=$ad['billing_email'];
              break;
            case 'broker':
              $stmt = $con->prepare("SELECT broker_name, email, billing_email, broker_number FROM brokers WHERE broker_number=?");
              $stmt->bind_param('i', $row['broker']);
              $stmt->execute();
              $bd = $stmt->get_result()->fetch_assoc();
              $stmt->close();
              $nameLink = '<a href="javascript:void(0)" ' .
                          'data-mdb-toggle="tooltip" title="View Statement" ' .
                          'onclick="showStatement(\'broker\',' . $row['broker'] . ',\'outstanding\')">' .
                          htmlspecialchars($bd['broker_name']) . '</a>';
                $email=$bd['email'];
                $billingEmail=$bd['billing_email'];
              break;
            default:
              $nameLink = '';
          }
          // Email alert row if missing
          $emailAlert = '';
      
          // Email button
          $type = $row['target']; // client, agent, broker
            $invNo = sprintf("%06d", $row['invNo']);
            $name = $cd['clientname'] ?? ($ad['agent_name'] ?? ($bd['broker_name'] ?? ''));            
            $subject = "Invoice {$invNo}";
            $message = "Your invoice is attached.";
            $filePath = 'invoices';
            $fileName = ($type === 'client') ? "{$row['invNo']}_invoice.pdf" : "{$row['invNo']}_{$type}.pdf";

            if ($row['sent']) {
                $emailBtn = '<a class="badge bg-success text-white" data-mdb-toggle="tooltip" title="Email Invoice">SENT</a>';
            } else {
                $emailBtn = '<a href="javascript:void(0)" class="emailButton badge bg-warning text-light" ' .
                    'data-client-number="' . $row['client'] . '" ' .
                    'data-client-name="' . htmlspecialchars($name) . '" ' .
                    'data-primary-email="' . htmlspecialchars($email) . '" ' .
                    'data-secondary-email="' . htmlspecialchars($billingEmail) . '" ' . // fallback
                    'data-subject="' . htmlspecialchars($subject) . '" ' .
                    'data-message="' . htmlspecialchars($message) . '" ' .
                    'data-file-path="' . $filePath . '" ' .
                    'data-file-name="' . $fileName . '" ' .
                    'data-invoice-number="' . $invNo . '" ' .
                    'data-mode="popup" ' .
                    'data-mdb-toggle="tooltip" title="Email Invoice">' .
                    'NOT SENT</a>';
            }
          // Latest delete button
          $latestBtn = ($latestId == $row['invNo'])
            ? '<button class="btn btn-sm btn-danger" data-mdb-toggle="tooltip" title="Remove Invoice">' .
              '<i class="fad fa-trash-alt"></i></button>'
            : '';
      ?>

            <tr id="R<?= $invNoFormatted ?>">
                <td><?= $invNoFormatted ?></td>
                <td><?= $clientLink ?></td>
                <td><?= $nameLink ?></td>
                <td><?= htmlspecialchars($address['contract_number']) ?></td>
                <td>£<?= $grandTotal ?></td>
                <td><?= $invoiceDate ?></td>
                <td><?= $emailBtn ?? '' ?> <?= $statusBadge ?></td>
                <!-- Payment Type (hidden on print) -->
                <td class="noprint align-middle">
                    <select id="payment_type_<?= $row['invNo'] ?>" class="form-select form-select-sm ptype">
                        <option value="0">NONE</option>
                        <option value="BACS" selected="">BACS</option>
                        <option value="CHEQUE">CHEQUE</option>
                        <option value="CASH">CASH</option>
                        <option value="PAYPAL">PAYPAL</option>
                        <option value="CREDIT">CREDIT</option>
                    </select>
                    <div style="display: none;" id="P00<?= $row['invNo'] ?>" class="cno"><input id="chequeNo_<?= $row['invNo'] ?>" type="text" class="form-control-sm chequeNo" name="chequeNo_<?= $row['invNo'] ?>"
                               placeholder="Cheque Number"></div>
                </td>
                <!-- Payee (hidden on print) -->
                <td class="d-print-table-cell">
                    <select id="payee_<?= $row['invNo'] ?>" class="form-select form-select-sm">
                        <option value="C_<?= $row['client'] ?>" <?= $row['target']=='client' ? 'selected' : '' ?>>Client</option>
                        <option value="A_<?= $row['client'] ?>" <?= $row['target']=='agent' ? 'selected' : '' ?>>Agent</option>
                        <option value="B_<?= $row['client'] ?>" <?= $row['target']=='broker' ? 'selected' : '' ?>>Broker</option>
                        <option value="BL_<?= $row['invNo'] ?>" <?= $row['target']=='blank' ? 'selected' : '' ?>>Other</option>
                    </select>
                </td>
                <!-- Payment Date -->
                <td>
                    <div class="date-picker" data-date-type="open" data-mdb-toggle-button="false" data-format="dd-mm-yyyy">
                        <input class="form-control-sm border-0" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" type="text" name="payment_date_<?= $row['invNo'] ?>" id="payment_date_<?= $row['invNo'] ?>" value="" placeholder="Select date" />
                    </div>


                </td>
                <!-- Actions -->
                <td class="text-end">
                    <div class="" role="group" aria-label="Actions">
                        <?php if($isOverdue): ?>
                        <button type="button" class="btn btn-secondary btn-sm me-2" data-mdb-toggle="tooltip" title="Email Reminder"><i class="fad fa-envelope"></i></button>
                        <?php endif; ?>
                        <a href="tel:<?= getClientContact($address['client_name'],'phone') ?>" class="btn btn-secondary btn-sm me-2" data-mdb-toggle="tooltip" title="Phone Client"><i class="fad fa-phone"></i></a>
                        <a href="index.php?t=includes/finance&p=finance_preview.php&invNo=<?= $row['invNo'] ?>&type=outstanding" class="btn btn-secondary btn-sm me-2" data-mdb-toggle="tooltip" title="View Invoice"><i
                               class="fad fa-eye"></i></a>
                        <a href="index.php?t=includes/finance&p=finance_invoices-edit.php&invNo=<?= $row['invNo'] ?>" class="btn btn-secondary btn-sm me-2" data-mdb-toggle="tooltip" title="Edit Invoice"><i class="fad fa-edit"></i></a>
                        <button id="paidButton<?= $row['invNo'] ?>" data-invid="<?= $row['invNo'] ?>" data-client-name="<?= $row['client'] ?>" data-target="<?= $row['target']?>" class="btn btn-secondary btn-sm me-2 paidButton"
                                data-mdb-toggle="tooltip" title="Mark as Paid"><i
                               class="fad fa-check-circle text-success"></i></button>
                        <button id="removeButton<?= $row['invNo'] ?>" data-clientName="<?= $row['client'] ?>" class="btn btn-secondary btn-sm me-2 removeButton" data-mdb-toggle="tooltip" title="Void Invoice"><i
                               class="fad fa-ban text-danger"></i></button>
                        <?= $latestBtn ?>
                    </div>
                </td>
            </tr>
            <?= $emailAlert ?? '' ?>
            <?php endforeach; ?>
        </tbody>
    </table>


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

<div id="exportDiv" style="display: none">
    <div id="exportTitle">Invoices Unpaid - <small>Generated <?php echo date('d-m-Y')?></small></div>
    <table id="exportTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr>
                <th>Invoice Number</th>
                <th>Client</th>
                <th>Agent/Broker</th>
                <th>Contract Number</th>
                <th>Status</th>
                <th>Amount</th>
                <th>Date of Invoice</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($data as $id){
        if(file_exists('invoices/'.$id['invNo'].'_broker.zip')){$broker="yes";}else{$broker="no";}
        $address = json_decode($row['address'], true);
        $items = json_decode($id['items'], true);
        $totals=explode('|',$id['totals']);
        $sub=str_replace(',','',$totals[0]);
        $vat=str_replace(',','',$totals[1]);
        $gtotal=$sub+$vat;
        $invno="";
        $invno=sprintf("%06d", $id['invNo']);
        ?>
            <tr id="R<?php echo $invno?>">
                <td><?php echo $invno?></td>
                <td><?php echo getClientName($address['client_name'])?></td>
                <td><?php echo $address['agent_name']?></td>

                <td><?php echo $address['contract_number']?></td>
                <td><?= $emailBtn ?? '' ?> <?= $statusBadge ?></td>
                <td>£<?php echo $totals[0]?></td>
                <td><?php echo date('d-m-Y',$id['date'])?></td>
            </tr>
            <?php }?>
        </tbody>

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

<div id="genRow" class="col-md-12 text-center remove">
    <button id="expenseReport" type="button" class="btn btn-secondary"><i class="fad fa-file-chart-line"></i> GENERATE REPORT</button>
</div>

<?php

$table="expenseTable";
        $dateTarget="5";        
        $length="25";
        $sortTarget="1";
        $sortCell="";
        $logo="yes";
        $scroller="";
        $printTarget='exportDiv';
        $printHeader='Outstanding Payments';
        $popup="false";
        require(ROOT_URL.'/includes/tables/finance_table.php');
?>


<script>
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-mdb-toggle="tooltip"]').forEach(el => new mdb.Tooltip(el));

});


const CURRENT_DATE_DMY = '<?php echo date("d-m-Y"); ?>';

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

function loadInvoice(type, inv) {
    window.open(`invoices/${inv}_${type}.pdf`);
}

function markSent(invoice) {
    var dest = '<p>Mark this invoice as sent?</p>'
    loadModalContent(dest, "statementBox", "modal-md", 1060, "true", 'Mark Send', "cancelConfirm", () => confirmSent(`${invoice}`));

}

async function confirmSent(invoice) {
    try {
        const response = await fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'setDelivered',
                inv: invoice,
                tenant: TENANT_URL
            })
        });
        const data = await response.text();

        if (data.trim() === "success") {
            hideMdbModal('confirmBox'); // Hide confirmBox
            showResponse('success', 'Set as delivered successfully'); // Assuming showResponse is global
            const element = document.getElementById(`em${invoice}`);
            if (element) {
                element.innerHTML = '<span class="badge badge-success m-0" style="font-size:12px; display:block">SENT</span>';
            }
        } else {
            console.error('confirmSent failed:', data);
            showResponse('error', 'Failed to mark as delivered.');
        }
    } catch (error) {
        console.error('Error in confirmSent:', error);
        showResponse('error', 'An error occurred.');
    }
}

async function setDelete(i) {
    try {
        const response = await fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'setDelete',
                inv: i,
                tenant: TENANT_URL
            })
        });
        const data = await response.text();

        if (data.trim() === "success") {
            const inv = pad(i, 6); // Assuming pad is a global function
            const element = document.getElementById(`R${inv}`);
            if (element) {
                element.style.backgroundColor = '#82e7d2';
                element.style.border = '1px solid #169f85';
            }
            showResponse('success', `The invoice has been deleted and numbering reset to ${i}`);
            hideMdbModal('confirmBox'); // Hide confirmBox

            setTimeout(() => {
                if (element) {
                    // Manual fadeOut effect (or use CSS transitions if available)
                    element.style.transition = 'opacity 0.5s ease-out';
                    element.style.opacity = '0';
                    setTimeout(() => {
                        element.style.display = 'none';
                    }, 500); // Wait for fadeOut transition
                }
            }, 3000);
        } else {
            console.error('setDelete failed:', data);
            showResponse('error', 'Failed to delete invoice.');
        }
    } catch (error) {
        console.error('Error in setDelete:', error);
        showResponse('error', 'An error occurred during deletion.');
    }
}

async function setPaid(i, c, f) {
    const invoice = i;
    const paid = document.getElementById(`payment_type_${i}`).value;
    const date = document.getElementById(`payment_date_${i}`).value;
    const cno = document.getElementById(`chequeNo_${i}`) ? document.getElementById(`chequeNo_${i}`).value : '';
    const pe = document.getElementById(`payee_${i}`) ? document.getElementById(`payee_${i}`).value : '';

    if (paid == 0 || date == "") {
        showResponse('warning', 'PLEASE SELECT A PAYMENT METHOD AND DATE');
        const paymentTypeElement = document.getElementById(`payment_type_${i}`);
        if (paymentTypeElement) {
            paymentTypeElement.focus();
        }
        return;
    }

    try {
        const response = await fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'setPaid',
                inv: invoice,
                payment_type: paid,
                chequeNo: cno,
                payee: pe,
                date: date,
                tenant: TENANT_URL
            })
        });
        const data = await response.text();

        if (data.trim() == "success") {
            if (f === "blank") {
                const invElement = document.getElementById(`R${i}`);
                if (invElement) {
                    invElement.style.backgroundColor = '#82e7d2';
                    invElement.style.border = '1px solid #169f85';
                }
                showResponse('success', 'The invoice has been set to Paid');
                killAllModals('confirmBox');
                setTimeout(() => {
                    if (invElement) {
                        invElement.style.transition = 'opacity 0.5s ease-out';
                        invElement.style.opacity = '0';
                        setTimeout(() => {
                            invElement.style.display = 'none';
                        }, 500);
                    }
                }, 3000);
            } else {

                const emailResponse = await fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        FUNCTION: 'getEmailDetails',
                        client: c,
                        target: f,
                        tenant: TENANT_URL
                    })
                });

                const emailDataRaw = await emailResponse.text();
                const emailData = emailDataRaw.trim().split('|');
                const mailerTarget = ROOT_URL + '/includes/master/financeMailer.php';
                const mailerString = `${emailData[0]}|${emailData[1]}|${emailData[2]}|Invoice Payment Confirmation |Thank you for your payment for invoice: ${String(invoice).padStart(6, '0')}`;
                const dest = encodeURI(`${mailerTarget}?mode=popup&data=${mailerString}&tenant=${TENANT_URL}`);

                loadModalContent(dest, "mailerBox", "modal-xl", 1060, "true", "Email Confirmation", "", '');

            }

            // Common success actions (from original 'else' block)
            const invElement = document.getElementById(`R${pad(i, 6)}`);
            if (invElement) {
                invElement.style.backgroundColor = '#82e7d2';
                invElement.style.border = '1px solid #169f85';
            }
            showResponse('success', 'The invoice has been set to Paid');
            killAllModals('confirmBox');
            setTimeout(() => {
                if (invElement) {
                    invElement.style.transition = 'opacity 0.5s ease-out';
                    invElement.style.opacity = '0';
                    setTimeout(() => {
                        invElement.style.display = 'none';
                    }, 500);
                }
            }, 3000);
        }

    } catch (error) {
        console.error('Error in setPaid:', error);
        showResponse('danger', 'An error occurred during payment update.');
    }
}


async function setArchive(i) {
    try {
        const response = 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: i
            })
        });
        const data = await response.text();

        if (data.trim() === "success") {
            const inv = pad(i, 6);
            const element = document.getElementById(`R${inv}`);
            if (element) {
                element.style.backgroundColor = '#82e7d2';
                element.style.border = '1px solid #169f85';
            }
            showResponse('success', 'The invoice has been voided');
            hideMdbModal('confirmBox');
            setTimeout(() => {
                if (element) {
                    element.style.transition = 'opacity 0.5s ease-out';
                    element.style.opacity = '0';
                    setTimeout(() => {
                        element.style.display = 'none';
                    }, 500);
                }
            }, 3000);
        } else {
            console.error('setArchive failed:', data);
            showResponse('error', 'Failed to void invoice.');
        }
    } catch (error) {
        console.error('Error in setArchive:', error);
        showResponse('error', 'An error occurred during voiding.');
    }
}


document.addEventListener('DOMContentLoaded', () => { 

    document.body.addEventListener('click', (event) => {
        const el = event.target.closest('.emailButton');
        if (!el) return;

        const payload = {
            clientNumber: el.dataset.clientNumber,
            clientName: el.dataset.clientName,
            primaryEmail: el.dataset.primaryEmail,
            secondaryEmail: el.dataset.secondaryEmail,
            subject: el.dataset.subject,
            message: el.dataset.message,
            filePath: el.dataset.filePath,
            fileName: el.dataset.fileName,
            invoiceNumber: el.dataset.invoiceNumber,
            mode: el.dataset.mode
        };

        const encoded = encodeURIComponent(JSON.stringify(payload));
        const dest = `${ROOT_URL}/includes/master/financeMailer.php?mode=popup&data=${encoded}&tenant=${TENANT_URL}`;

        loadModalContent(dest, "mailerBox", "modal-xl", 1060, "true", "Email Invoice", "", '');
    });


    // Paid Button Click Handler
    document.body.addEventListener('click', (event) => {
        const targetElement = event.target.closest('.paidButton');
        if (targetElement) {
            const str = targetElement.dataset.invid;
            const clientNames = targetElement.dataset.clientName;
            const paid = document.getElementById('payment_type_' + str).value;
            const date = document.getElementById('payment_date_' + str).value;
            const target = targetElement.dataset.target;

            if (paid == 0 || date == "") {
                showResponse('warning', 'PLEASE SELECT A PAYMENT METHOD AND DATE');
                const paymentTypeElement = document.getElementById(`payment_type_${str}`);
                if (paymentTypeElement) {
                    paymentTypeElement.focus();
                }
            } else {


                const dest = `<p>Are you sure this invoice for <b>${str}</b> has been paid?</p>`;
                loadModalContent(dest, "confirmBox", "modal-md", 1060, "true", "Mark Paid", "cancelConfirm", () => setPaid(str, clientNames, target));

            }
        }
    });


    // Delete Button Click Handler
    document.body.addEventListener('click', (event) => {
        const targetElement = event.target.closest('.deleteButton');
        if (targetElement) {
            const str = targetElement.dataset.values;
            // Assuming confirmBox is a custom global function
            confirmBox('Void Invoice', 'Are you sure this invoice is to be deleted and numbering reset?<br><span class="text-danger"><small>THIS CANNOT BE UNDONE</small></span>', `setDelete('${str}')`);
        }
    });


    // Remove Button Click Handler (Void Invoice)
    document.body.addEventListener('click', (event) => {
        const targetElement = event.target.closest('.removeButton');
        if (targetElement) {
            const str = targetElement.dataset.values;
            const d = str.split("|");
            // Assuming confirmBox is a custom global function
            confirmBox('Void Invoice', 'Are you sure this invoice is to be voided?', `setArchive('${d[0]}')`);
        }
    });


    // Payment Type Change Handler
    document.body.addEventListener('change', (event) => {
        const targetElement = event.target.closest('.ptype');
        if (targetElement) {
            const sel = targetElement.value;
            const parentTd = targetElement.closest('td');
            if (sel === "CHEQUE") {
                const cnoElement = parentTd ? parentTd.querySelector('.cno') : null;
                if (cnoElement) {
                    cnoElement.style.display = 'block';
                }
            } else {
                const chequeNoElement = parentTd ? parentTd.querySelector('.chequeNo') : null;
                const cnoElement = parentTd ? parentTd.querySelector('.cno') : null;
                if (chequeNoElement) {
                    chequeNoElement.value = '';
                }
                if (cnoElement) {
                    cnoElement.style.display = 'none';
                }
            }
        }
    });


    // Expense Report Click Handler
    document.getElementById('expenseReport').addEventListener('click', async () => {

        const exportDiv = document.getElementById('exportDiv');
        const dataContent = exportDiv ? exportDiv.innerHTML : ''; // Get content of exportDiv

        try {
            const response = await fetch(ROOT_URL + '/includes/engines/report.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'clientnumber': '000',
                    type: `invoicesUnPaid_generated_${CURRENT_DATE_DMY}`,
                    content: dataContent,
                    format: 'L'
                })
            });
            const ret = await response.text();
            debug(ret)
            const genRowElement = document.getElementById('genRow');
            if (genRowElement) {
                genRowElement.innerHTML = `<a href="output/reps/000_invoicesUnPaid_generated_${CURRENT_DATE_DMY}.pdf" target="blank" class="btn btn-info"><i class="fad fa-file-pdf"></i> VIEW REPORT</a>`;
            }
        } catch (error) {
            console.error('Error generating report:', error);
            showResponse('error', 'An error occurred during report generation.');
        }
    });

});
</script>