<?php 
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
?>
<div class="row mt-0">
    <div class="col-12">
        <p class="lead">Broker Finances - <strong><?php echo getBrokerName($_REQUEST['broker_number']); ?></strong></p>
    </div>
</div>

<?php
function getPaymentStatus($s){
  if($s==1) return '<span class="badge badge-warning d-block" style="font-size:12px">Unpaid</span>';
  if($s==3) return '<span class="badge badge-success d-block" style="font-size:12px">Paid</span>';
}
function getPaymentStatusB($s){
  if($s==1) return 'Unpaid';
  if($s==3) return 'Paid';
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `broker`=? AND `status`!='5' AND `status`!='3'") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['broker_number']);
$stmt->execute();
$iv = $stmt->get_result();
$stmt->close();

$tdata=''; $sdata=''; $mTotal=0;

while($d=mysqli_fetch_array($iv)){
  $m = explode('|', $d['totals']);
  $m[0] = str_replace(',', '', $m[0]); // net
  $m[1] = str_replace(',', '', $m[1]); // vat
  $rowGross = ($m[0] + $m[1]);
  $commissionAmt = (float)$d['commission']; // monetary commission per invoice
  $rowTotal = ($rowGross - $commissionAmt);
  $mTotal  += $rowTotal;

  $tdata .= '<tr valign="middle">
    <td>'.sprintf("%06d", $d['invNo']).'</td>
    <td>'.getClientName($d['client']).'</td>
    <td>'.getPaymentStatus($d['status']).'</td>
    <td>'.date('d-m-Y',$d['date']).'</td>
    <td>'.$m[0].'</td>
    <td>'.$m[1].'</td>
    <td>&pound;'.number_format($commissionAmt,2).'</td>
    <td>&pound;'.number_format($rowTotal,2).'</td>
  </tr>';

  $sdata .= '<tr valign="middle">
    <td>'.sprintf("%06d", $d['invNo']).'</td>
    <td>'.getClientName($d['client']).'</td>
    <td>'.getPaymentStatusB($d['status']).'</td>
    <td>'.date('d-m-Y',$d['date']).'</td>
    <td>'.$m[0].'</td>
    <td>'.$m[1].'</td>
    <td>&pound;'.number_format($commissionAmt,2).'</td>
    <td>&pound;'.number_format($rowTotal,2).'</td>
  </tr>';
}
?>

<div id="pdfData">
    <table id="statementTable" class="table table-striped table-sm responsive w-100">
        <thead>
            <tr class="headCell">
                <th>Invoice Number</th>
                <th>Client</th>
                <th width="100px">Status</th>
                <th width="120px">Date Issued</th>
                <th>Net Fee</th>
                <th>VAT</th>
                <th>Commission</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody><?php echo $tdata; ?></tbody>
    </table>

    <div id="reportData" style="display:none">
        <div id="exportTitle" class="reportHeader">
            <?php echo getBrokerName($_REQUEST['broker_number']); ?> Statement - <?php echo date('d-m-Y'); ?>
        </div>
        <table class="table table-striped table-sm w-100">
            <thead>
                <tr>
                    <th width="100px" style="width:100px">Invoice Number</th>
                    <th>Client</th>
                    <th>Status</th>
                    <th>Date Issued</th>
                    <th>Net Fee</th>
                    <th>VAT</th>
                    <th>Commission</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody><?php echo $sdata; ?></tbody>
            <tfoot>
                <tr class="footCell">
                    <td colspan="7"></td>
                    <td>£<?php echo number_format($mTotal,2); ?> <small>Outstanding</small></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <?php
    $table="statementTable";
    $dateTarget = "3";
    $length = "25";
    $sortTarget = "";
    $sortCell = "";
    $logo = "yes";
    $scroller = "";
    $printTarget = 'exportDiv';
    $printHeader = 'Broker Statement';
    $popup = "false";
    require('../tables/finance_table.php');
  ?>

    <?php if($_REQUEST['mode']=="popup"){?>
    <div class="col-md-12 text-center">
        <button id="btnSend" type="button" class="btn btn-secondary"
                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Send statement as PDF">
            <i class="fad fa-file-chart-line me-1"></i> Send Statement
        </button>
    </div>
    <?php } else { ?>
    <div id="genRow" class="col-md-12 text-center">
        <button id="btnGenerate" type="button" class="btn btn-secondary"
                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Generate statement PDF">
            <i class="fad fa-file-chart-line me-1"></i> Generate Statement
        </button>
    </div>
    <?php } ?>

    <div class="alert alert-info float-end p-0 ps-2 pe-2 mt-4">
        Total Outstanding:&nbsp;<span class="float-end">£<?php echo number_format($mTotal,2); ?></span>
    </div>
</div>

<div class="spacer"></div>

<script>
(() => {
    const ENTITY = 'broker';
    const TENANT = TENANT_URL;
    const BROKER_NO = '<?= $_REQUEST['broker_number'] ?>';
    const CLIENT_NO = '<?= (int)($_REQUEST['clientnumber'] ?? $_REQUEST['client_number'] ?? $_REQUEST['client'] ?? 0) ?>';
    const DISPLAY_NAME = '<?= addslashes(getBrokerName($_REQUEST['broker_number'])) ?>';
    const TOTAL = '<?= number_format($mTotal,2) ?>';
    const DATE_UK = '<?= date('d-m-Y') ?>';
    const MAILER_ID = 'mailerBox';

    function ukHeader() {
        return DATE_UK;
    }

    if (window.__enrepStmtHandler) {
        document.removeEventListener('click', window.__enrepStmtHandler);
    }

    async function generatePdf() {
        const contentEl = document.getElementById('reportData');
        if (!contentEl) {
            showResponse('danger', 'No report content');
            return;
        }

        const payload = new URLSearchParams({
            tenant: TENANT,
            variant: 'statement',
            type: DISPLAY_NAME,
            header: ukHeader(),
            addressBox: ENTITY,
            number: BROKER_NO,
            total: TOTAL,
            content: contentEl.innerHTML,
            format: 'A4-L',
            show_page_numbers: '1',
            show_generated_date: '1'
        });

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

        let href = '';
        try {
            const j = JSON.parse((await res.text()).trim());
            if (j.ok) href = j.href;
        } catch (_) {}
        if (!href) {
            showResponse('danger', 'PDF generation failed');
            return;
        }

        const row = document.getElementById('genRow') || document.getElementById('pdfData');
        const btn = document.createElement('a');
        btn.className = 'btn btn-info mt-3';
        btn.target = '_blank';
        btn.href = href;
        btn.setAttribute('data-mdb-tooltip-init', '');
        btn.setAttribute('data-mdb-placement', 'top');
        btn.setAttribute('data-mdb-trigger', 'hover');
        btn.title = 'Open generated PDF';
        btn.innerHTML = '<i class="fad fa-file-pdf me-1"></i> View Statement';
        row.appendChild(btn);
        showResponse('success', 'Statement generated');
    }

    async function sendStatement() {
        if (window.__enrepMailerOpen) return;
        window.__enrepMailerOpen = true;

        try {
            const r1 = await fetch(`${ROOT_URL}/includes/finance/finance_functions.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    FUNCTION: 'sendStatement',
                    number: BROKER_NO,
                    mode: ENTITY,
                    tenant: TENANT
                })
            });
            const parts = (await r1.text()).trim().split('|');
            const disp = parts[2] || DISPLAY_NAME;
            const email = parts[3] || '';

            const contentEl = document.getElementById('reportData');
            const payload = new URLSearchParams({
                tenant: TENANT,
                variant: 'statement',
                type: DISPLAY_NAME,
                header: ukHeader(),
                addressBox: ENTITY,
                number: BROKER_NO,
                total: TOTAL,
                content: contentEl.innerHTML,
                format: 'A4-L',
                show_page_numbers: '1',
                show_generated_date: '1'
            });
            const r2 = await fetch(`${ROOT_URL}/includes/engines/report.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: payload.toString()
            });
            let file = '';
            try {
                const j = JSON.parse((await r2.text()).trim());
                if (j.ok) file = j.file;
            } catch (_) {}
            if (!file) {
                showResponse('danger', 'PDF generation failed');
                return;
            }

            const mailPayload = {
                clientNumber: CLIENT_NO,
                clientName: disp,
                primaryEmail: email,
                secondaryEmail: '',
                subject: 'Your Statement',
                message: 'Attached is your statement',
                filePath: 'output/reps/',
                fileName: file,
                invoiceNumber: '',
                addressMode: 'billing',
                mode: ENTITY
            };
            const dest = encodeURI(
                `${ROOT_URL}/includes/master/financeMailer.php?mode=popup&data=${encodeURIComponent(JSON.stringify(mailPayload))}&tenant=${TENANT}`
            );
            loadModalContent(dest, MAILER_ID, "modal-xl", 1060, "true", "Email Confirmation", "", '');

            if (typeof waitForEmailSentOnce !== 'function') {
                window.waitForEmailSentOnce = function(timeoutMs = 300000) {
                    return new Promise(resolve => {
                        let done = false;
                        const finish = ok => {
                            if (!done) {
                                done = true;
                                cleanup();
                                resolve(!!ok);
                            }
                        };
                        const to = setTimeout(() => finish(false), timeoutMs);
                        const onCustom = e => {
                            if (e?.detail) {
                                clearTimeout(to);
                                finish(!!e.detail.success);
                            }
                        };
                        window.addEventListener('enrep:emailSent', onCustom, {
                            once: true
                        });

                        function cleanup() {
                            window.removeEventListener('enrep:emailSent', onCustom, {
                                once: true
                            });
                        }
                    });
                };
            }

            const sent = await waitForEmailSentOnce(300000);
            killModal(MAILER_ID);
            showResponse(sent ? 'success' : 'warning', sent ? 'Email sent' : 'Email not sent or timed out');
        } catch (err) {
            showResponse('danger', 'Email process failed');
        } finally {
            window.__enrepMailerOpen = false;
        }
    }

    window.__enrepStmtHandler = function(e) {
        if (e.target.closest('#btnGenerate')) generatePdf();
        if (e.target.closest('#btnSend')) sendStatement();
    };
    document.addEventListener('click', window.__enrepStmtHandler);
})();
</script>
