<?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 mb-4">
    <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)){
    $rowGross=0;
    $rowTotal=0;
$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">
    <!-- Hidden Raw Data Table -->
    <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="gsend" type="button" class="btn btn-secondary" data-mdb-toggle="tooltip" title="Send Report" onclick="sendStatement()"> <i class="fad fa-file-chart-line me-1"></i> SEND REPORT </button>
    </div>
    <?php else: ?>
    <div id="genRow" class="text-center px-3 my-3">
        <button id="expenseReport" type="button" class="btn btn-secondary" data-mdb-toggle="tooltip" title="Generate Report"> <i class="fad fa-file-chart-line me-1"></i> GENERATE REPORT</button>
    </div>
    <?php endif; ?>

    <!-- Print Version -->
    <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>

            </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');
 ?>
<!-- Initialize Tooltips -->
<script>
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-mdb-toggle="tooltip"]').forEach(el => new mdb.Tooltip(el));
});
</script>




<script>
var REQUEST_MODE = '<?php echo $_REQUEST['mode'] ?? ''; ?>';
var CLIENT_NUMBER = '<?php echo $_REQUEST['clientnumber'] ?? ''; ?>';
var CURRENT_DATE = '<?php echo date('d-m-Y'); ?>';
var GET_CLIENT_NAME = '<?php echo getClientName($_REQUEST['clientnumber'] ?? ''); ?>';
var SDATA_ENCODED = '<?php echo urlencode($sdata ?? ''); ?>';
var MTOTAL_FORMATTED = '<?php echo number_format($mTotal ?? 0, 2); ?>';


(async function() { // Self-executing anonymous function to encapsulate and run immediately
    var expenseReportButton = document.getElementById('reportData');
    if (expenseReportButton) {
        expenseReportButton.addEventListener('click', async () => {
            var start = document.getElementById('sdate').value; // Assuming 'sdate' input exists
            var end = document.getElementById('edate').value; // Assuming 'edate' input exists
            var reportDataContent = document.getElementById('reportData').innerHTML; // Assuming 'reportData' div exists

            try {
                var response = await fetch(`${ROOT_URL}/includes/engines/report.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        'clientnumber': CLIENT_NUMBER,
                        type: `${GET_CLIENT_NAME}_com_generated_${CURRENT_DATE}`,
                        content: reportDataContent,
                        format: 'L',
                        tenant: TENANT_URL
                    })
                });
                var ret = await response.text(); // Assuming 'ret' is just a string filename/path

                var genRowElement = document.getElementById('genRow'); // Assuming 'genRow' div exists
                if (genRowElement) {
                    genRowElement.innerHTML = `
                        <a href="output/reps/000_${GET_CLIENT_NAME}_com_generated_${CURRENT_DATE}.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.');
            }
        });
    }

    // --- Navigation Box HTML ---
    if (REQUEST_MODE !== "popup") {
        var navBoxElement = document.getElementById('navBox'); // Assuming 'navBox' exists
        if (navBoxElement) {
            navBoxElement.innerHTML = `
                <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>
                <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=${CLIENT_NUMBER}&view=edit">${GET_CLIENT_NAME}</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>
                <li class="breadcrumb-item active">Broker Finances</li>
            `;
        }
    }
})(); // End of self-executing function


async function setPaid(ino) {
    try {
        var response = await fetch('includes/finance/finance_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'setBrokerPaid',
                inv: ino
            })
        });
        var data = await response.text();

        if (data.trim() === "success") {
            showResponse('success', 'The commission payment status has been updated');
        } else {
            console.error('setPaid failed:', data);
            showResponse('error', 'Failed to update commission payment status.');
        }
    } catch (error) {
        console.error('Error in setPaid:', error);
        showResponse('error', 'An error occurred during payment status update.');
    }
}


async function sendStatement() {
    try {
        // First AJAX: Get email details
        var emailDetailsResponse = 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_NUMBER,
                mode: 'client',
                tenant: TENANT_URL
            })
        });
        var emailRetRaw = await emailDetailsResponse.text();
        var emailData = emailRetRaw.trim().split('|');

        var contentData = document.getElementById('reportData').innerHTML; // Assuming 'reportData' div exists
        var generateReportResponse = await fetch(`${ROOT_URL}/includes/engines/report.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                content: contentData,
                name: emailData[1], // Assuming data[1] is the name from getEmailDetails
                type: 'statement',
                clientnumber: CLIENT_NUMBER, // Correct variable for CLIENT_NUMBER
                version: 'unpaid',
                format: 'L',
                addressBox: 'client',
                sdata: SDATA_ENCODED,
                total: MTOTAL_FORMATTED,
                tenant: TENANT_URL
            })
        });
        var destFileRaw = await generateReportResponse.text();
        var destFile = destFileRaw.trim(); // The PDF filename/path

        var string = `${emailData[1]}|${emailData[2]}|${emailData[3]}|Your Statement|Attached is your statement|output/reps/|${destFile}`;

        var dest = encodeURI(`${ROOT_URL}/includes/master/financeMailer.php?data=${string}&tenant=${TENANT_URL}`);
        loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Send Statement");
    } catch (error) {
        console.error('Error in sendStatement:', error);
        showResponse('error', 'An error occurred while sending the statement.');
    }
}
</script>