<?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 – 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 content = expenseDataEl.innerHTML;
        const typeKey = currentReportType || 'report';
        const start = currentReportStart || '';
        const end = currentReportEnd || '';

        const pdfName = 'finance_' + typeKey + '_' + start + '_' + end;

        const formData = new URLSearchParams();
        formData.append('clientnumber', '000'); // neutral
        formData.append('type', pdfName);
        formData.append('content', content);
        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();
        });
    }

    // === PRINT (using jsprint.js if available, else simple fallback) ===
    const printReport = () => {
        const expenseDataEl = document.getElementById('expenseData');
        const containerEl = document.getElementById('financeReportContainer');
        const sourceEl = expenseDataEl || containerEl;

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

        if (typeof printContainer === 'function') {
            // Use shared print helper
            printContainer('expenseData', {
                orientation: 'landscape',
                header: '',
                footer: '',
                styles: [], // you can push extra CSS here if needed
                margin: 10
            });
        } else {
            // Fallback simple print
            const printWindow = window.open('', '_blank', 'width=1024,height=768');
            if (!printWindow) {
                showResponse('danger', 'Popup blocked. Please allow popups for this site to print.');
                return;
            }

            const doc = printWindow.document;
            doc.open();
            doc.write('<html><head><title>Finance Report</title>');
            doc.write('<style>' +
                'body { font-family: Arial, sans-serif; font-size: 12px; margin: 10px; }' +
                'table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }' +
                'th, td { border: 1px solid #ccc; padding: 4px; text-align: left; }' +
                'th { background: #f5f5f5; }' +
                '.text-end { text-align: right; }' +
                '</style>');
            doc.write('</head><body>');
            doc.write(sourceEl.innerHTML);
            doc.write('</body></html>');
            doc.close();

            printWindow.focus();
            printWindow.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>