<?php
// finance_reports.php

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

// Last day of previous month
$today = date('d-m-Y', strtotime('last day of previous month'));
// First day of previous month
$lastMonth = date('01-m-Y', strtotime('-1 month', strtotime($today)));
?>

<div class="container-fluid">
    <div class="row">
        <div class="note note-light mb-3 col-12 col-md-9">
            <strong>Finance Reports:</strong>
            Select a date range and report type to review invoices, expenses, receipts, and VAT summaries.
        </div>

        <!-- Export buttons -->
        <div class="col-12 col-md-3 text-md-end mb-3 mb-md-0 noprint">
            <button id="btnExportCsv" type="button" class="btn btn-secondary me-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Export current report view as CSV">
                <i class="fad fa-file-csv me-2"></i>CSV
            </button>
            <button id="btnGenPdf" type="button" class="btn btn-secondary me-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Generate a PDF from the current 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 report">
                <i class="fad fa-print me-2"></i>Print
            </button>
        </div>
    </div>

    <div class="row g-3 align-items-end">

        <!-- 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-3">Start date</h5>
                <input
                       type="text"
                       id="reportStart"
                       name="reportStart"
                       class="form-control"
                       placeholder="Start date"
                       value="<?php echo $lastMonth; ?>"
                       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-3">End date</h5>
                <input
                       type="text"
                       id="reportEnd"
                       name="reportEnd"
                       class="form-control"
                       placeholder="End date"
                       value="<?php echo $today; ?>"
                       data-mdb-confirmDateOnSelect
                       data-mdb-toggle="datepicker" />
            </div>
        </div>

        <!-- Report type -->
        <div class="col-12 col-md-4 col-lg-3">
            <h5 class="mb-3">Report type</h5>
            <select id="reportType" name="reportType" class="form-select">
                <option value="">Select report type</option>
                <option value="inv_paid">Invoices – Paid</option>
                <option value="inv_outstanding">Invoices – Outstanding</option>
                <option value="inv_all">Invoices – All</option>
                <option value="outgoings">Expenses / Outgoings</option>
               <option value="outgoings_by_category">Expenses / Outgoings – By Category</option>
                <option value="receipts">Receipts</option>
                <option value="receipts_by_category">Receipts – By Payee</option>
                <option value="vat_in">VAT – Income (Receipts)</option>
                <option value="vat_out">VAT – Outgoing (Expenses)</option>
            </select>
        </div>

        <!-- Load button -->
        <div class="col-12 col-lg-3 d-flex justify-content-center justify-content-lg-start">
            <button id="btnLoadReport"
                    type="button"
                    class="btn btn-info w-100"
                    data-mdb-tooltip-init
                    data-mdb-placement="top"
                    data-mdb-trigger="hover"
                    title="Generate report for selected dates and type">
                <i class="fad fa-file-chart-line me-2"></i>Generate report
            </button>
        </div>
    </div>

    <hr class="my-4" />

    <div id="financeReportContainer"></div>


</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const btnLoadReport = document.getElementById('btnLoadReport');
    const reportStartInput = document.getElementById('reportStart');
    const reportEndInput = document.getElementById('reportEnd');
    const reportTypeSelect = document.getElementById('reportType');
    const loadingOverlay = document.getElementById('reportLoading');
    const containerId = 'financeReportContainer';

    const btnCsv = document.getElementById('btnExportCsv');
    const btnPdf = document.getElementById('btnGenPdf');
    const btnPrint = document.getElementById('btnPrint');

    let currentReportType = '';
    let currentReportStart = '';
    let currentReportEnd = '';

    const showLoading = () => {
        if (loadingOverlay) loadingOverlay.style.display = 'block';
    };

    const hideLoading = () => {
        if (loadingOverlay) loadingOverlay.style.display = 'none';
    };

    const getParams = () => {
        const start = (reportStartInput?.value || '').trim();
        const end = (reportEndInput?.value || '').trim();
        const type = (reportTypeSelect?.value || '').trim();
        return {
            start,
            end,
            type
        };
    };

    const validateParams = () => {
        const {
            start,
            end,
            type
        } = getParams();

        if (!start || !end || !type) {
            showResponse('danger', 'Please select a START date, END date, and report type before generating a report.');
            return false;
        }

        return true;
    };

    const loadReport = () => {
        if (!validateParams()) return;

        const {
            start,
            end,
            type
        } = getParams();

        currentReportType = type;
        currentReportStart = start;
        currentReportEnd = end;

        const params = new URLSearchParams();
        params.append('type', type);
        params.append('start', start);
        params.append('end', end);
        params.append('tenant', TENANT_URL);

        const url = ROOT_URL + '/includes/finance/reports/finance_reports_data.php?' + params.toString();

        showLoading();

        loadContentAndExecuteScripts(url, containerId, () => {
            hideLoading();
        });
    };

    if (btnLoadReport) {
        btnLoadReport.addEventListener('click', (e) => {
            e.preventDefault();
            loadReport();
        });
    }

    // === CSV EXPORT ===
    const exportCsv = () => {
        const container = document.getElementById('financeReportContainer');
        if (!container) {
            showResponse('warning', 'No report content available to export.');
            return;
        }

        const tables = container.querySelectorAll('table');
        if (!tables.length) {
            showResponse('warning', 'No table data found in the current report.');
            return;
        }

        const lines = [];
        const sanitise = (val) => {
            let v = (val || '').toString().trim().replace(/\s+/g, ' ');
            if (v.indexOf('"') !== -1) v = v.replace(/"/g, '""');
            if (v.indexOf(',') !== -1 || v.indexOf('"') !== -1) v = '"' + v + '"';
            return v;
        };

        tables.forEach((table, index) => {
            // If there is a heading immediately before this table, add as a section label
            let headingText = '';
            let prev = table.previousElementSibling;
            while (prev && prev.tagName && prev.tagName.toLowerCase() === 'table') {
                prev = prev.previousElementSibling;
            }
            if (prev && /^h[1-6]$/i.test(prev.tagName)) {
                headingText = prev.textContent.trim();
            }

            if (index > 0) {
                // Blank line between tables
                lines.push('');
            }

            if (headingText) {
                lines.push(sanitise(headingText));
            }

            const theadRows = table.tHead ? Array.from(table.tHead.rows) : [];
            const tbodyRows = table.tBodies.length ? Array.from(table.tBodies[0].rows) : [];

            theadRows.forEach(row => {
                const cells = Array.from(row.cells).map(cell => sanitise(cell.textContent));
                lines.push(cells.join(','));
            });

            tbodyRows.forEach(row => {
                const cells = Array.from(row.cells).map(cell => sanitise(cell.textContent));
                lines.push(cells.join(','));
            });
        });

        const csvContent = '\uFEFF' + lines.join('\r\n'); // BOM for Excel
        const blob = new Blob([csvContent], {
            type: 'text/csv;charset=utf-8;'
        });

        const typePart = currentReportType || 'report';
        const startPart = currentReportStart || 'start';
        const endPart = currentReportEnd || 'end';
        const filename = 'finance_' + typePart + '_' + startPart + '_' + endPart + '.csv';

        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } else {
            showResponse('warning', 'CSV download is not supported in this browser.');
        }
    };

    if (btnCsv) {
        btnCsv.addEventListener('click', (e) => {
            e.preventDefault();
            exportCsv();
        });
    }

    // === PDF EXPORT (using standard engines/report.php) ===
    const exportPdf = () => {
    const expenseDataEl = document.getElementById('expenseData');
    if (!expenseDataEl) {
        showResponse('warning', 'Please generate a report before exporting to PDF.');
        return;
    }

    const wrapper = expenseDataEl.cloneNode(true);

    wrapper.querySelectorAll('.noprint').forEach((el) => {
        el.remove();
    });

    const maxRowsPerPdfTable = 25;

    wrapper.querySelectorAll('table').forEach((table) => {
        const tbody = table.querySelector('tbody');
        if (!tbody) {
            return;
        }

        const bodyRows = Array.from(tbody.querySelectorAll('tr'));
        if (bodyRows.length <= maxRowsPerPdfTable) {
            return;
        }

        const parent = table.parentNode;
        const tableClasses = table.className;
        const thead = table.querySelector('thead');
        const tfoot = table.querySelector('tfoot');

        const chunks = [];
        for (let i = 0; i < bodyRows.length; i += maxRowsPerPdfTable) {
            chunks.push(bodyRows.slice(i, i + maxRowsPerPdfTable));
        }

        const fragment = document.createDocumentFragment();

        chunks.forEach((chunkRows, index) => {
            const newTable = document.createElement('table');
            newTable.className = tableClasses;
            newTable.setAttribute('width', '100%');
            newTable.style.width = '100%';
            newTable.style.borderCollapse = 'collapse';
            newTable.style.marginBottom = '12px';

            if (thead) {
                newTable.appendChild(thead.cloneNode(true));
            }

            const newTbody = document.createElement('tbody');
            chunkRows.forEach((row) => {
                newTbody.appendChild(row.cloneNode(true));
            });
            newTable.appendChild(newTbody);

            if (tfoot && index === chunks.length - 1) {
                newTable.appendChild(tfoot.cloneNode(true));
            }

            fragment.appendChild(newTable);
        });

        parent.replaceChild(fragment, table);
    });

    const typeKey = currentReportType || 'report';
    const start = currentReportStart || '';
    const end = currentReportEnd || '';
    const pdfName = 'finance_' + typeKey + '_' + start + '_' + end;

    const formData = new URLSearchParams();
    formData.append('clientnumber', '000');
    formData.append('type', pdfName);
    formData.append('content', wrapper.innerHTML);
    formData.append('format', 'A4-L');
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL + '/includes/engines/report.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(() => {
        const href = 'output/reps/' + encodeURIComponent(pdfName) + '.pdf';
        window.open(href, '_blank');
    })
    .catch(() => {
        showResponse('danger', 'There was a problem generating the report PDF.');
    });
};

    if (btnPdf) {
        btnPdf.addEventListener('click', (e) => {
            e.preventDefault();
            exportPdf();
        });
    }

function headerText() {
    const el = document.getElementById('exportTitle');
    return el ? el.innerHTML.trim() : '';
}
    
    const printReport = () => {
    // pick the real printable container in priority order
    const ids = ['expenseData', 'vatContent', 'financeReportContainer', 'resultBox'];
    let targetId = null;

    for (const id of ids) {
        if (document.getElementById(id)) {
            targetId = id;
            break;
        }
    }

    if (!targetId) {
        showResponse('warning', 'No report content available to print.');
        return;
    }

    const header = (typeof headerText === 'function') ? headerText() : '';

    if (typeof printContent === 'function') {
        printContent(targetId, header);
        return;
    }

    if (typeof printContainer === 'function') {
        printContainer(targetId, {
            orientation: 'landscape',
            header: header ? `<p>${header}</p>` : '',
            footer: `<p>Generated by EnRep Reporting System: <?= date('d-m-Y')?></p>`,
            logoUrl: 'images/company/logo.jpg',
            styles: [ROOT_URL + '/src/css/print.css'],
            margin: 10
        });
        return;
    }

    window.print();
};



    if (btnPrint) {
        btnPrint.addEventListener('click', (e) => {
            e.preventDefault();
            printReport();
        });
    }

    // Breadcrumb
    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">Reports</li>';
    }
});
</script>