<?php // finance_vat.php?>
<div class="container-fluid">
    <div class="row">
        <div class="note note-light mb-3 col-12 col-md-9">
            <strong>VAT Reporting:</strong> This page provides a summary of VAT activity within a selected date range.
            It lists income (VAT on receipts) and expenditure (VAT on purchases or expenses) to support your VAT return.
            You can review totals, compare periods, export data to CSV, or generate a formatted PDF for record-keeping.
        </div>

        <div class="col-12 col-md-3">
            <span class="float-md-end 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 view to 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 and open report">
                    <i class="fad fa-file-pdf me-2"></i>Report
                </button>
                <button id="btnPrint" type="button" class="btn btn-secondary"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Print view">
                    <i class="fad fa-print me-2"></i>Print
                </button>
            </span>
        </div>
    </div>
    <div class="row g-3">
        <!-- Start -->
        <div class="col-12 col-md-3">
            <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <label for="sdate" class="form-label mb-2">Start date</label>
                <input type="text" id="sdate" name="sdate" class="form-control"
                       placeholder="DD-MM-YYYY"
                       value="<?= date('d-m-Y') ?>"
                       data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" />
            </div>
        </div>
        <!-- End -->
        <div class="col-12 col-md-3">
            <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <label for="edate" class="form-label mb-2">End date</label>
                <input type="text" id="edate" name="edate" class="form-control"
                       placeholder="DD-MM-YYYY"
                       value="<?= date('d-m-Y') ?>"
                       data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" />
            </div>
        </div>
        <!-- Mode -->
        <div class="col-12 col-md-3">
            <label for="vatMode" class="form-label mb-2">View</label>
            <select id="vatMode" class="form-select">
                <option value="in">Inputs (Receipts)</option>
                <option value="out">Outputs (Expenditure)</option>
                <option value="compare">Compare (In vs Out)</option>
            </select>
        </div>

        <div class="col-12 col-md-3 d-flex align-items-end">
            <button id="genButton" type="button" class="btn btn-info"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Load entries">
                <i class="fad fa-play me-2"></i>Load entries
            </button>
        </div>
    </div>

    <hr>
    <div id="resultBox"></div>
</div>
<script>
(function() {
    // Normalise "d-m-yyyy" to "dd-mm-yyyy"
    function parseDMY(str) {
        if (typeof str !== 'string') return null;
        str = str.trim().replace(/\//g, '-');
        const m = str.match(/^\s*(\d{1,2})-(\d{1,2})-(\d{4})\s*$/);
        if (!m) return null;
        const d = Number(m[1]),
            mo = Number(m[2]),
            y = Number(m[3]);
        const dt = new Date(y, mo - 1, d);
        if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d) return null;
        return String(d).padStart(2, '0') + '-' + String(mo).padStart(2, '0') + '-' + y;
    }

    function modeLabel(v) {
        if (v === 'out') return 'Outputs (Expenditure)';
        if (v === 'compare') return 'Comparison (In vs Out)';
        return 'Inputs (Receipts)';
    }

    function headerText() {
        const s = document.getElementById('sdate')?.value || '';
        const e = document.getElementById('edate')?.value || '';
        const m = (document.getElementById('vatMode')?.value || 'in').trim();
        return `VAT Report — ${modeLabel(m)} — ${s} to ${e}`;
    }

    // Generate PDF and open in a new tab
    async function generatePdfAndOpen() {
        const wrap = document.getElementById('resultBox');
        const container = wrap?.querySelector('#vatContent') || wrap;
        if (!container) {
            showResponse('danger', 'Nothing to export');
            return;
        }

        const mode = (document.getElementById('vatMode')?.value || 'in').trim();
        const edUK = document.getElementById('edate')?.value || '';
        const title = `vat_${mode}_${edUK}`;

        const payload = new URLSearchParams({
            tenant: TENANT_URL,
            clientnumber: '0',
            type: title,
            content: container.innerHTML,
            format: 'A4-L'
        });

        let href = '';
        try {
            const res = await fetch(ROOT_URL + '/includes/engines/report.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: payload.toString()
            });
            const txt = (await res.text()).trim();
            try {
                const j = JSON.parse(txt);
                if (j && j.href) href = j.href;
            } catch (_) {
                if (txt.endsWith('.pdf')) href = txt;
            }
        } catch (_) {}

        if (!href) href = `output/reps/0_${title}.pdf`;

        // Open immediately
        try {
            window.open(href, '_blank');
        } catch (_) {}
        showResponse('success', 'Report generated');
    }

    // Delegated click
    document.addEventListener('click', async function(e) {
        // Load
        if (e.target.closest('#genButton')) {
            const s = parseDMY(document.getElementById('sdate')?.value || '');
            const ed = parseDMY(document.getElementById('edate')?.value || '');
            const mode = (document.getElementById('vatMode')?.value || 'in').trim();

            if (!s || !ed) {
                showResponse('danger', 'Select a complete date range');
                return;
            }

            const url = ROOT_URL + '/includes/finance/vat/finance_vat_data.php';
            const body = new URLSearchParams({
                action: 'table',
                mode: mode, // in | out | compare
                start: s,
                end: ed,
                tenant: TENANT_URL
            });

            const box = document.getElementById('resultBox');
            box.innerHTML = '<div class="text-center p-3">Loading…</div>';

            try {
                const res = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: body.toString()
                });
                const html = await res.text();
                box.innerHTML = html;
                // execute inline scripts if any
                box.querySelectorAll('script').forEach(el => {
                    const sEl = document.createElement('script');
                    if (el.src) sEl.src = el.src;
                    else sEl.textContent = el.textContent;
                    document.body.appendChild(sEl);
                    sEl.remove();
                });
            } catch {
                showResponse('danger', 'Failed to load VAT data');
            }
            return;
        }

        // CSV
        if (e.target.closest('#btnExportCsv')) {
            const s = parseDMY(document.getElementById('sdate')?.value || '');
            const ed = parseDMY(document.getElementById('edate')?.value || '');
            const mode = (document.getElementById('vatMode')?.value || 'in').trim();
            if (!s || !ed) {
                showResponse('danger', 'Select a complete date range');
                return;
            }

            const form = document.createElement('form');
            form.method = 'POST';
            form.target = '_blank';
            form.action = ROOT_URL + '/includes/finance/vat/finance_vat_data.php';
            [
                ['action', 'csv'],
                ['mode', mode],
                ['start', s],
                ['end', ed],
                ['tenant', TENANT_URL]
            ].forEach(([k, v]) => {
                const inp = document.createElement('input');
                inp.type = 'hidden';
                inp.name = k;
                inp.value = v;
                form.appendChild(inp);
            });
            document.body.appendChild(form);
            form.submit();
            form.remove();
            return;
        }

        // Report button → generate and open
        if (e.target.closest('#btnGenPdf')) {
            generatePdfAndOpen();
            return;
        }

        // Print -> use provided printContent()
        if (e.target.closest('#btnPrint')) {
            const wrap = document.getElementById('resultBox');
            const targetId = wrap?.querySelector('#vatContent') ? 'vatContent' : 'resultBox';
            if (typeof printContent === 'function') {
                printContent(targetId, headerText());
            } else if (typeof printContainer === 'function') {
                // Fallback if printContent not available
                printContainer(targetId, {
                    orientation: 'landscape',
                    header: `<p>${headerText()}</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']
                });
            } else {
                window.print();
            }
        }
    });

    // Init MDB datepickers
    document.querySelectorAll(".date-picker").forEach(function(el) {
        try {
            new mdb.Datepicker(el, {
                confirmDateOnSelect: true,
                format: "dd-mm-yyyy"
            });
        } catch (_) {}
    });
})();

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item ">Finance - Vat Reporting</li> ';
</script>