<?php
// finance_commissions.php

// Default date
$date = isset($date) ? $date : date('d-m-Y');

// Finance helpers if needed
if (defined('ROOT_URL')) {
    require_once ROOT_URL . '/includes/finance/finance_functions.php';
}

// Payee lists (native select)
$agentsRes  = mysqli_query($GLOBALS['con'], "SELECT agent_number, agent_name FROM agents ORDER BY agent_name ASC");
$brokersRes = mysqli_query($GLOBALS['con'], "SELECT broker_number, broker_name FROM brokers ORDER BY broker_name ASC");
if (!$agentsRes)  { $agentsRes  = false; }
if (!$brokersRes) { $brokersRes = false; }
?>

<div class="container-fluid">

    <div class="row">
        <div class="note note-light mb-3 col-12 col-md-9">
            <strong>Commission Reporting:</strong>
            This page provides an overview of commissions earned on paid invoices within a selected date range.
            Use the filters to define the period, then review invoice, client, agent/broker and total commission values.
            You can export the report to CSV, generate a PDF, or print the current view for your records.
        </div>

        <div class="col-12 col-md-3 mb-3 mb-md-0 noprint">
            <span class="float-md-end">
                <button
                        id="btnCommissionCsv"
                        type="button"
                        class="btn btn-secondary me-2"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Export current commission view to CSV">
                    <i class="fad fa-file-csv me-2"></i>CSV
                </button>
                <button
                        id="btnCommissionPdf"
                        type="button"
                        class="btn btn-secondary me-2"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Generate a PDF of the current commission report">
                    <i class="fad fa-file-pdf me-2"></i>PDF
                </button>
                <button
                        id="btnPrint"
                        type="button"
                        class="btn btn-secondary"
                        data-mdb-tooltip-init
                        data-mdb-placement="top"
                        data-mdb-trigger="hover"
                        title="Print the current commission report">
                    <i class="fad fa-print me-2"></i>Print
                </button>
            </span>
        </div>
    </div>

    <div class="row g-2 align-items-end mb-3">
        <!-- Start date -->
        <div class="col-12 col-md-4 col-lg-3">
            <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <h5 class="mb-2">Start date</h5>
                <input
                       type="text"
                       id="sdate"
                       name="sdate"
                       class="form-control"
                       placeholder="Start date"
                       value="<?php echo htmlspecialchars($date, ENT_QUOTES); ?>"
                       data-mdb-confirmDateOnSelect
                       data-mdb-toggle="datepicker" />
            </div>
        </div>

        <!-- End date -->
        <div class="col-12 col-md-4 col-lg-3">
            <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <h5 class="mb-2">End date</h5>
                <input
                       type="text"
                       id="edate"
                       name="edate"
                       class="form-control"
                       placeholder="End date"
                       value="<?php echo htmlspecialchars($date, ENT_QUOTES); ?>"
                       data-mdb-confirmDateOnSelect
                       data-mdb-toggle="datepicker" />
            </div>
        </div>

        <!-- Payee filter -->
        <div class="col-12 col-md-4 col-lg-3">
            <h5 class="mb-2">Agent/Broker</h5>
            <select
                    id="payee"
                    name="payee"
                    class="form-select"
                    data-mdb-tooltip-init
                    data-mdb-placement="top"
                    data-mdb-trigger="hover"
                    title="Filter by a specific agent or broker">
                <option value="">All</option>

                <optgroup label="Agents">
                    <?php if ($agentsRes) { while ($a = mysqli_fetch_assoc($agentsRes)) { ?>
                    <option value="agent|<?php echo (int)$a['agent_number']; ?>">
                        <?php echo htmlspecialchars($a['agent_name'], ENT_QUOTES); ?>
                    </option>
                    <?php } } ?>
                </optgroup>

                <optgroup label="Brokers">
                    <?php if ($brokersRes) { while ($b = mysqli_fetch_assoc($brokersRes)) { ?>
                    <option value="broker|<?php echo (int)$b['broker_number']; ?>">
                        <?php echo htmlspecialchars($b['broker_name'], ENT_QUOTES); ?>
                    </option>
                    <?php } } ?>
                </optgroup>
            </select>
        </div>

        <!-- Load button -->
        <div class="col-12 col-md-4 col-lg-3">
            <button
                    id="loadButton"
                    type="button"
                    class="btn btn-info mt-4 mt-md-0 w-100"
                    data-mdb-tooltip-init
                    data-mdb-placement="top"
                    data-mdb-trigger="hover"
                    title="Load commission report for the selected period">
                <i class="fad fa-search me-2"></i>Load report
            </button>
        </div>
    </div>

    <hr>

    <div id="commissionData" class="mt-3"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Breadcrumb / nav trail
    const navBox = document.getElementById('navBox');
    if (navBox) {
        navBox.innerHTML =
            '<li class="breadrumb-item">' +
            'Finance' +
            '<i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i>' +
            '</li>' +
            '<li class="breadrumb-item active">Commission</li>';
    }

    const loadBtn = document.getElementById('loadButton');
    if (loadBtn) {
        loadBtn.addEventListener('click', handleLoadCommissionReport);
    }

    const btnCsv = document.getElementById('btnCommissionCsv');
    const btnPdf = document.getElementById('btnCommissionPdf');
    const btnPrint = document.getElementById('btnCommissionPrint');

    if (btnCsv) btnCsv.addEventListener('click', exportCommissionCsv);
    if (btnPdf) btnPdf.addEventListener('click', generateCommissionPdf);
    //if (btnPrint) btnPrint.addEventListener('click', printCommissionReport);
});

/**
 * Load commission data for the selected date range (+ payee filter).
 */
function handleLoadCommissionReport() {
    const sInput = document.getElementById('sdate');
    const eInput = document.getElementById('edate');
    const pInput = document.getElementById('payee');

    const s = sInput ? sInput.value.trim() : '';
    const e = eInput ? eInput.value.trim() : '';
    const payee = pInput ? pInput.value.trim() : '';

    if (!s || !e) {
        if (typeof showResponse === 'function') {
            showResponse('danger', 'You must set a START and END date to report on');
        } else {
            alert('You must set a START and END date to report on');
        }
        return;
    }

    const commissionData = document.getElementById('commissionData');
    if (commissionData) {
        commissionData.innerHTML =
            '<div class="text-center my-4">' +
            '<div class="spinner-border text-info" role="status">' +
            '<span class="visually-hidden">Loading...</span>' +
            '</div>' +
            '</div>';
    }

    const formData = new URLSearchParams();
    formData.append('start', s);
    formData.append('end', e);
    if (payee) formData.append('payee', payee);
    if (typeof TENANT_URL !== 'undefined') formData.append('tenant', TENANT_URL);

    const url = (typeof ROOT_URL !== 'undefined' ?
        ROOT_URL + '/includes/finance/commission/finance_commission_data.php' :
        'includes/finance/commission/finance_commission_data.php');

    fetch(url, {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(html => {
            if (commissionData) commissionData.innerHTML = html;
        })
        .catch(err => {
            console.error('Commission load error:', err);
            if (commissionData) {
                commissionData.innerHTML =
                    '<div class="alert alert-danger">An error occurred while loading the commission data.</div>';
            }
            if (typeof showResponse === 'function') {
                showResponse('danger', 'There was a problem loading the commission report.');
            }
        });
}

/**
 * Export the current commission table to CSV (VAT-style CSV export).
 */
function exportCommissionCsv() {
    const table = document.getElementById('commissionrep');
    if (!table) {
        if (typeof showResponse === 'function') {
            showResponse('warning', 'No commission data to export. Please load a report first.');
        } else {
            alert('No commission data to export. Please load a report first.');
        }
        return;
    }

    const rows = Array.from(table.querySelectorAll('tr'));
    const lines = [];

    rows.forEach((row) => {
        const cells = Array.from(row.querySelectorAll('th,td'))
            .filter(cell => !cell.classList.contains('noExport'));

        if (!cells.length) return;

        const line = cells.map(cell => {
            let text = cell.innerText || '';

            // normalise whitespace
            text = text.replace(/\r?\n|\r/g, ' ').trim();

            // strip currency symbols (handles £ and Â£)
            text = text.replace(/Â£|£/g, '').trim();

            // escape CSV if needed
            if (text.indexOf(',') !== -1 || text.indexOf('"') !== -1) {
                text = '"' + text.replace(/"/g, '""') + '"';
            }

            return text;
        }).join(',');
        lines.push(line);
    });

    if (!lines.length) {
        if (typeof showResponse === 'function') {
            showResponse('warning', 'No exportable data found in the commission table.');
        } else {
            alert('No exportable data found in the commission table.');
        }
        return;
    }

    const sInput = document.getElementById('sdate');
    const eInput = document.getElementById('edate');
    const pInput = document.getElementById('payee');

    const s = sInput ? sInput.value.trim().replace(/[^0-9]/g, '') : '';
    const e = eInput ? eInput.value.trim().replace(/[^0-9]/g, '') : '';

    // Include payee slug in filename to avoid overwriting different filtered exports
    let payeeSlug = 'all';
    if (pInput && pInput.value) {
        payeeSlug = pInput.value.replace(/[^\w|]+/g, '').replace('|', '_');
    }

    const filename = 'Commission_Report_' + payeeSlug + '_' + (s || 'start') + '_to_' + (e || 'end') + '.csv';
    const csvContent = lines.join('\r\n');

    const blob = new Blob([csvContent], {
        type: 'text/csv;charset=utf-8;'
    });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

/**
 * Generate a PDF for the current commission report (VAT-style PDF generation).
 */
function generateCommissionPdf() {
    const repdataEl = document.getElementById('repdata');
    if (!repdataEl) {
        if (typeof showResponse === 'function') {
            showResponse('warning', 'No commission data to generate. Please load a report first.');
        } else {
            alert('No commission data to generate. Please load a report first.');
        }
        return;
    }

    const content = repdataEl.innerHTML;
    if (!content.trim()) {
        if (typeof showResponse === 'function') {
            showResponse('warning', 'No commission data to generate. Please load a report first.');
        } else {
            alert('No commission data to generate. Please load a report first.');
        }
        return;
    }

    const sInput = document.getElementById('sdate');
    const eInput = document.getElementById('edate');
    const pInput = document.getElementById('payee');

    const start = sInput ? sInput.value.trim() : '';
    const end = eInput ? eInput.value.trim() : '';
    const payee = pInput ? pInput.value.trim() : '';

    if (!start || !end) {
        if (typeof showResponse === 'function') {
            showResponse('danger', 'You must set a START and END date to generate a PDF.');
        } else {
            alert('You must set a START and END date to generate a PDF.');
        }
        return;
    }

    // Include payee slug in type to prevent overwriting PDFs for same date range
    let payeeSlug = 'all';
    if (payee) {
        payeeSlug = payee.replace(/[^\w|]+/g, '').replace('|', '_');
    }

    const formData = new URLSearchParams();
    formData.append('clientnumber', '000'); // Generic / admin-level report
    formData.append('type', 'commission_' + payeeSlug + '_' + start + '_' + end);
    formData.append('content', content);
    formData.append('format', 'A4-L'); // Landscape
    if (typeof TENANT_URL !== 'undefined') formData.append('tenant', TENANT_URL);

    const url = (typeof ROOT_URL !== 'undefined' ?
        ROOT_URL + '/includes/engines/report.php' :
        'includes/engines/report.php');

    fetch(url, {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(ret => {

            const pdfHref = 'output/reps/commission_' + payeeSlug + '_' + start + '_' + end + '.pdf';

            window.open(pdfHref, '_blank');

            if (typeof showResponse === 'function') {
                showResponse('success', 'Commission report PDF has been generated.');
            }
        })
        .catch(err => {
            console.error('Commission PDF generation error:', err);
            if (typeof showResponse === 'function') {
                showResponse('danger', 'There was a problem generating the commission report PDF.');
            } else {
                alert('There was a problem generating the commission report PDF.');
            }
        });
}

/**
 * Print the current commission report (VAT-style print).
 */

// Print
document.getElementById('btnPrint')?.addEventListener('click', () => {
    const wrap = document.getElementById('repdata');
    const flt_from = document.getElementById('sdate').value;
    const flt_to = document.getElementById('edate').value;
    const contentHtml = wrap ? wrap.innerHTML : '';
    if (!contentHtml.trim()) {
        showResponse('warning', 'Nothing to print');
        return;
    }
    const header = "Report of Commission: " + flt_from + " to " + flt_to;
    try {
        if (typeof printContainer === 'function') {
            printContainer(contentHtml, {
                orientation: 'landscape',
                header: `<p>${header}</p>`,
                footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
                logoUrl: 'images/company/logo.jpg',
                styles: [
                    `${ROOT_URL}/src/css/print.css`,
                ],
            });
        } else {
            window.print();
        }
    } catch {
        showResponse('danger', 'Print unavailable');
    }
});
</script>