<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin && !$isManager) {
    $_SESSION['flash_error'] = "You don't have permission to view payroll reports.";
    header("Location: dashboard.php");
    exit;
}

// Nothing below writes to the session, so release the lock now instead of
// holding it for the rest of this page's queries/rendering.
session_write_close();

$cycles = $conn->query("SELECT * FROM payroll_cycles ORDER BY payroll_year DESC, payroll_month DESC");
$groups = $conn->query("SELECT * FROM groups ORDER BY name ASC");
$company = $conn->query("SELECT * FROM company_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();

$initialCycleId = (int) ($_GET['cycle_id'] ?? 0);
$initialGroupId = isset($_GET['group_id']) && $_GET['group_id'] !== '' ? (int) $_GET['group_id'] : '';

$pageTitle = 'Payroll Reports';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs no-print">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-4">Filter Report</h3>
    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Payroll Cycle</label>
            <select id="filterCycle" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="">-- Select cycle --</option>
                <?php while ($c = $cycles->fetch_assoc()): ?>
                    <option value="<?= $c['id']; ?>" <?= $initialCycleId===(int)$c['id']?'selected':''; ?>><?= h($c['name']); ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Pay Group</label>
            <select id="filterGroup" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="">All Groups</option>
                <?php while ($g = $groups->fetch_assoc()): ?>
                    <option value="<?= $g['id']; ?>" <?= $initialGroupId===(int)$g['id']?'selected':''; ?>><?= h($g['name']); ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <button onclick="loadReport()" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">Run Report</button>
    </div>
</div>

<div id="loadingState" class="hidden text-center py-8 text-xs text-slate-400 font-semibold">Loading report...</div>

<div id="reportOutput" class="hidden">
    <div id="printArea">
        <!-- Letterhead: print only -->
        <div class="print-letterhead items-center gap-4 mb-4 pb-4 border-b-2 border-slate-900">
            <?php if (!empty($company['logo_path'])): ?>
                <img src="<?= h($company['logo_path']); ?>" alt="Logo" class="h-14 w-14 object-contain">
            <?php endif; ?>
            <div>
                <h1 class="text-lg font-black text-slate-900"><?= h($company['company_name'] ?? 'Your Company'); ?></h1>
                <h2 class="text-sm font-bold text-slate-600" id="printCycleName"></h2>
                <p class="text-[11px] text-slate-500 font-semibold" id="printCyclePeriod"></p>
            </div>
        </div>

        <div class="flex items-center justify-between mb-4 no-print">
            <div>
                <h2 class="text-sm font-black text-slate-900" id="onscreenCycleName"></h2>
                <p class="text-[11px] text-slate-500 font-semibold" id="onscreenCyclePeriod"></p>
            </div>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-5 gap-4 no-print">
            <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase">Gross</p>
                <p class="text-lg font-black text-slate-900" id="statGross"></p>
            </div>
            <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase">PAYE</p>
                <p class="text-lg font-black text-slate-900" id="statPaye"></p>
            </div>
            <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase">Other Deductions</p>
                <p class="text-lg font-black text-amber-700" id="statOtherDeductions"></p>
            </div>
            <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase">Total Deductions</p>
                <p class="text-lg font-black text-rose-700" id="statDeductions"></p>
            </div>
            <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs text-center">
                <p class="text-[9px] font-black text-slate-500 uppercase">Net Pay</p>
                <p class="text-lg font-black text-emerald-700" id="statNet"></p>
            </div>
        </div>

        <div class="bg-white border border-slate-200 rounded-xl shadow-xs overflow-hidden mt-6">
            <div class="p-4 border-b border-slate-100 flex items-center justify-between no-print">
                <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight" id="tableHeading">Payroll Detail</h3>
                <div class="flex items-center gap-4">
                    <button onclick="exportCSV()" class="text-xs font-bold text-indigo-600 hover:underline active:scale-95 transition inline-block">Export CSV</button>
                    <button onclick="exportExcel()" class="text-xs font-bold text-emerald-600 hover:underline active:scale-95 transition inline-block">Export Excel</button>
                    <button onclick="window.print()" class="text-xs font-bold text-slate-600 hover:underline active:scale-95 transition inline-block">Print</button>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-sm border-collapse" id="reportTable">
                    <thead id="reportThead" class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider"></thead>
                    <tbody class="divide-y divide-slate-100" id="reportTbody"></tbody>
                    <tfoot id="reportTfoot"></tfoot>
                </table>
            </div>
        </div>

        <!-- Footer: print only -->
        <?php if (!empty($company['footer_text'])): ?>
        <div class="print-footer-text mt-6 pt-3 border-t border-slate-300 text-[10px] text-slate-500 text-center">
            <?= h($company['footer_text']); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<style>
.print-letterhead, .print-footer-text { display: none; }
@media print {
    body * { visibility: hidden; }
    #printArea, #printArea * { visibility: visible; }
    #printArea { position: absolute; top: 0; left: 0; width: 100%; }
    .no-print { display: none !important; }
    .print-letterhead { display: flex !important; }
    .print-footer-text { display: block !important; }
}
#reportTable tbody tr:nth-child(even) { background-color: #f8fafc; }
#reportTable td, #reportTable th { white-space: nowrap; }
</style>
<script>
const ajaxUrl = 'reports_ajax.php';

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str ?? '';
    return div.innerHTML;
}

function naira(n) {
    return '₦' + Number(n).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function fmtDays(n) {
    const s = Number(n).toFixed(2).replace(/\.?0+$/, '');
    return s === '' ? '0' : s;
}

function fmtDate(d) {
    if (!d) return '';
    const dt = new Date(d + 'T00:00:00');
    return dt.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
}

async function loadReport() {
    const cycleId = document.getElementById('filterCycle').value;
    const groupId = document.getElementById('filterGroup').value;

    if (!cycleId) {
        alert('Select a payroll cycle first.');
        return;
    }

    document.getElementById('reportOutput').classList.add('hidden');
    document.getElementById('loadingState').classList.remove('hidden');

    const params = new URLSearchParams({ action: 'load_report', cycle_id: cycleId });
    if (groupId) params.set('group_id', groupId);

    history.replaceState(null, '', `reports.php?${params.toString()}`);

    let data;
    try {
        const res = await fetch(`${ajaxUrl}?${params.toString()}`);
        if (!res.ok) throw new Error(`Server returned ${res.status}`);
        data = await res.json();
    } catch (e) {
        document.getElementById('loadingState').classList.add('hidden');
        alert('Failed to load report -- ' + e.message);
        return;
    }

    document.getElementById('loadingState').classList.add('hidden');

    if (data.error) {
        alert(data.error);
        return;
    }

    renderReport(data);
}

function renderReport(data) {
    const period = `${fmtDate(data.cycle.start_date)} – ${fmtDate(data.cycle.end_date)}`;
    document.getElementById('printCycleName').textContent = `${data.cycle.name} — Payroll Report`;
    document.getElementById('printCyclePeriod').textContent = `Pay Cycle Period: ${period}`;
    document.getElementById('onscreenCycleName').textContent = `${data.cycle.name} — Payroll Report`;
    document.getElementById('onscreenCyclePeriod').textContent = `Pay Cycle Period: ${period}`;
    document.getElementById('tableHeading').textContent = `Payroll Detail (${data.rows.length} employees)`;

    const otherDeductions = data.totals.deductions - data.totals.paye - data.totals.pension - data.totals.nhf - data.totals.nhis;

    document.getElementById('statGross').textContent = '₦' + Math.round(data.totals.gross).toLocaleString('en-NG');
    document.getElementById('statPaye').textContent = '₦' + Math.round(data.totals.paye).toLocaleString('en-NG');
    document.getElementById('statOtherDeductions').textContent = '₦' + Math.round(otherDeductions).toLocaleString('en-NG');
    document.getElementById('statDeductions').textContent = '₦' + Math.round(data.totals.deductions).toLocaleString('en-NG');
    document.getElementById('statNet').textContent = '₦' + Math.round(data.totals.net).toLocaleString('en-NG');

    // Statutory columns only appear if switched on in Settings right now
    const cols = data.columns || { show_pension: true, show_nhf: true, show_nhis: true };

    const headerCells = [
        '<th class="text-left p-3">Employee No</th>',
        '<th class="text-left p-3">Name</th>',
        '<th class="text-left p-3">Designation</th>',
        '<th class="text-left p-3">Group</th>',
        '<th class="text-right p-3">Gross</th>',
        '<th class="text-right p-3">Days Worked</th>',
        '<th class="text-right p-3">Absent Days</th>',
        '<th class="text-right p-3">LOP</th>',
        '<th class="text-right p-3">Surcharge</th>',
        '<th class="text-right p-3">PAYE</th>',
        cols.show_pension ? '<th class="text-right p-3">Pension</th>' : '',
        cols.show_nhf ? '<th class="text-right p-3">NHF</th>' : '',
        cols.show_nhis ? '<th class="text-right p-3">NHIS</th>' : '',
        '<th class="text-right p-3">Total Deductions</th>',
        '<th class="text-right p-3">Net Pay</th>',
    ].join('');
    document.getElementById('reportThead').innerHTML = `<tr>${headerCells}</tr>`;

    const tbody = document.getElementById('reportTbody');
    tbody.innerHTML = data.rows.map(r => `
        <tr class="hover:bg-indigo-50/40 transition">
            <td class="p-3 font-mono text-slate-500">${escapeHtml(r.employee_no)}</td>
            <td class="p-3 font-bold text-slate-900">${escapeHtml(r.name)}</td>
            <td class="p-3 text-slate-500">${escapeHtml(r.designation || '—')}</td>
            <td class="p-3 text-slate-500">${escapeHtml(r.group_name || '—')}</td>
            <td class="p-3 text-right font-mono">${naira(r.gross_earnings)}</td>
            <td class="p-3 text-right font-mono text-slate-600">${r.days_worked}</td>
            <td class="p-3 text-right font-mono ${r.absent_days > 0 ? 'text-rose-600 font-bold' : 'text-slate-400'}">${fmtDays(r.absent_days)}</td>
            <td class="p-3 text-right font-mono ${r.lop_amount > 0 ? 'text-rose-600' : 'text-slate-400'}">${naira(r.lop_amount)}</td>
            <td class="p-3 text-right font-mono ${r.surcharge_amount > 0 ? 'text-rose-600' : 'text-slate-400'}">${naira(r.surcharge_amount)}</td>
            <td class="p-3 text-right font-mono">${naira(r.paye_tax)}</td>
            ${cols.show_pension ? `<td class="p-3 text-right font-mono">${naira(r.pension_employee)}</td>` : ''}
            ${cols.show_nhf ? `<td class="p-3 text-right font-mono">${naira(r.nhf)}</td>` : ''}
            ${cols.show_nhis ? `<td class="p-3 text-right font-mono">${naira(r.nhis)}</td>` : ''}
            <td class="p-3 text-right font-mono font-bold text-rose-700">${naira(r.total_deductions)}</td>
            <td class="p-3 text-right font-mono font-black text-emerald-700">${naira(r.net_pay)}</td>
        </tr>
    `).join('');

    const totalColspan = 4;
    document.getElementById('reportTfoot').innerHTML = `
        <tr class="bg-slate-100 font-black border-t-2 border-slate-300">
            <td class="p-3" colspan="${totalColspan}">Totals</td>
            <td class="p-3 text-right font-mono">${naira(data.totals.gross)}</td>
            <td class="p-3 text-right font-mono">${data.totals.days_worked}</td>
            <td class="p-3 text-right font-mono">${fmtDays(data.totals.absent_days)}</td>
            <td class="p-3 text-right font-mono">${naira(data.totals.lop)}</td>
            <td class="p-3 text-right font-mono">${naira(data.totals.surcharge)}</td>
            <td class="p-3 text-right font-mono">${naira(data.totals.paye)}</td>
            ${cols.show_pension ? `<td class="p-3 text-right font-mono">${naira(data.totals.pension)}</td>` : ''}
            ${cols.show_nhf ? `<td class="p-3 text-right font-mono">${naira(data.totals.nhf)}</td>` : ''}
            ${cols.show_nhis ? `<td class="p-3 text-right font-mono">${naira(data.totals.nhis)}</td>` : ''}
            <td class="p-3 text-right font-mono text-rose-700">${naira(data.totals.deductions)}</td>
            <td class="p-3 text-right font-mono text-emerald-700">${naira(data.totals.net)}</td>
        </tr>
    `;

    document.getElementById('reportOutput').classList.remove('hidden');
}

function exportCSV() {
    const table = document.getElementById('reportTable');
    let csv = [];
    for (const row of table.rows) {
        const cols = Array.from(row.cells).map(c => '"' + c.innerText.replace(/"/g,'""') + '"');
        csv.push(cols.join(','));
    }
    const blob = new Blob([csv.join('\n')], { type: 'text/csv' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'payroll_report.csv';
    link.click();
}

function exportExcel() {
    const table = document.getElementById('reportTable');
    const wb = XLSX.utils.table_to_book(table, { sheet: 'Payroll Report' });
    XLSX.writeFile(wb, 'payroll_report.xlsx');
}

<?php if ($initialCycleId): ?>
loadReport();
<?php endif; ?>
</script>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
