<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }

$_REQUEST['clientnumber']=$_REQUEST['client_number'];
?>
<div class="row mt-0">
    <div class="note note-secondary">
        <p class="lead">Client Finances - <strong><?= getClientName($_REQUEST['clientnumber'])?></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 `client`=? AND `date_paid`='' AND `status`!='5' AND `status`!='3'")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i',$_REQUEST['clientnumber']);$stmt->execute();$iv=$stmt->get_result();$stmt->close();

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

while($d=mysqli_fetch_array($iv)){
  $m=explode('|',$d['totals']);
  $m[0]=str_replace(',','',$m[0]);
  $m[1]=str_replace(',','',$m[1]);
  $rowGross=($m[0]+$m[1]);
  $rowTotal=($rowGross-$d['commission']);

  $tTotal=$tTotal+$d['commission'];
  $gTotal=$tTotal+$rowTotal;
  $mTotal=$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>&pound;'.number_format($m[0],2).'</td>
    <td>&pound;'.number_format($m[1],2).'</td>
    <td>&pound;'.number_format($d['commission'],2).'</td>
    <td>&pound;'.number_format($rowTotal,2).'</td>
  </tr>';

  $sdata.='<tr valign="middle">
    <td><a class="btn-info" href="https://[REPORT_PATH]/invoicePreview.php?invoicenumber='.$d['invNo'].'" alt="View full report online" title="View full report online">'.sprintf("%06d", $d['invNo']).'</a></td>
    <td>'.getClientName($d['client']).'</td>
    <td>'.getPaymentStatus($d['status']).'</td>
    <td>'.date('d-m-Y',$d['date']).'</td>
    <td>&pound;'.number_format($m[0],2).'</td>
    <td>&pound;'.number_format($m[1],2).'</td>
    <td>&pound;'.number_format($d['commission'],2).'</td>
    <td>&pound;'.number_format($rowTotal,2).'</td>
  </tr>';
}?>

<div id="pdfData" class="container-fluid px-0 my-4">
    <div id="statementContainer" class="table-responsive w-100 px-3">
        <table id="statementTable" class="table table-striped table-hover table-bordered align-middle w-100 table-sm">
            <thead class="table-dark">
                <tr>
                    <th style="max-width:50px">Invoice #</th>
                    <th style="width:200px">Client</th>
                    <th style="width:100px">Status</th>
                    <th style="width:100px">Date Issued</th>
                    <th>Net Fee</th>
                    <th>VAT</th>
                    <th>Commission</th>
                    <th>Total <small class="text-muted">(less commission)</small></th>
                </tr>
            </thead>
            <tbody><?= $tdata ?></tbody>
        </table>
    </div>

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

    <?php if($_REQUEST['mode'] === "popup"): ?>
    <div class="text-center px-3 my-3">
        <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="text-center px-3 my-3">
        <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 endif; ?>

    <div id="reportData" class="d-none px-3">
        <div class="table-responsive w-100">
            <table class="table table-striped table-hover table-bordered align-middle w-100">
                <thead class="table-dark">
                    <tr>
                        <th width="200">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 <small class="text-muted">(less commission)</small></th>
                    </tr>
                </thead>
                <tbody><?= $sdata ?></tbody>
                <tfoot>
                    <tr class="footCell">
                        <td colspan="7"></td>
                        <td>£<?= number_format($mTotal,2) ?> <small>Outstanding</small></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="d-flex justify-content-end px-3 mt-3 w-100">
            <span class="fw-bold" style="float:right">Total Outstanding: £<?= number_format($mTotal,2) ?></span>
        </div>
    </div>
</div>

<?php
  $table="statementTable";
  $dateTarget="3";
  $sortTarget="1";
  $length="25";
  $sortCell="";
  $logo="yes";
  $scroller="";
  $printTarget='reportData';
  $printHeader=getClientName($_REQUEST['clientnumber']).' Statement';
  require_once('../tables/finance_table.php');
?>

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

(() => {
    const ENTITY = 'client';
    const TENANT = TENANT_URL;
    const CLIENT_NO = '<?= $_REQUEST['clientnumber'] ?? '';?>';
    const DISPLAY_NAME = '<?= addslashes(getClientName($_REQUEST['clientnumber'] ?? ''));?>';
    const TOTAL = '<?= number_format($mTotal ?? 0, 2);?>';
    const DATE_UK = '<?= date('d-m-Y');?>';
    const MAILER_ID = 'mailerBox'; // unify

    function ukHeader() {
        return DATE_UK;
    }

    // remove any previous global handler, then register one shared handler
    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,
            clientnumber: CLIENT_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() {
        // global lock prevents double-open even if a stray handler exists
        if (window.__enrepMailerOpen) return;
        window.__enrepMailerOpen = true;

        try {
            // 1) Email details
            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: CLIENT_NO,
                    mode: ENTITY,
                    tenant: TENANT
                })
            });
            const parts = (await r1.text()).trim().split('|');
            const disp = parts[2] || DISPLAY_NAME;
            const email = parts[3] || '';

            // 2) Generate PDF
            const contentEl = document.getElementById('reportData');
            const payload = new URLSearchParams({
                tenant: TENANT,
                variant: 'statement',
                type: DISPLAY_NAME,
                header: ukHeader(),
                addressBox: ENTITY,
                clientnumber: CLIENT_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;
            }

            // 3) Open mailer and wait once
            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", "Send Statement", "", '');

            // helper: define only if missing
            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;
        }
    }

    // single shared handler used by ALL statement views to avoid stacking
    window.__enrepStmtHandler = function(e) {
        if (e.target.closest('#btnGenerate')) generatePdf();
        if (e.target.closest('#btnSend')) sendStatement();
    };
    document.addEventListener('click', window.__enrepStmtHandler);
})();
</script>