document.addEventListener('DOMContentLoaded', () => {
    const userJson = localStorage.getItem('user');
    if (!userJson) {
        window.location.href = '../index.html';
        return;
    }
    const user = JSON.parse(userJson);

    const fullnameEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    if (fullnameEl) fullnameEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';

    document.getElementById('btn-apply-filters')
        .addEventListener('click', loadReports);

    // initial load
    loadAreasFilter();
    loadReports();
});

function getFilters() {
    return {
        from: document.getElementById('filter-from')?.value || '',
        to: document.getElementById('filter-to')?.value || '',
        areaId: document.getElementById('filter-area')?.value || '',
        status: document.getElementById('filter-status')?.value || '',
        search: document.getElementById('filter-search')?.value || ''
    };
}

async function loadAreasFilter() {
    try {
        const res = await fetch('../api/get_areas.php');
        if (!res.ok) return;
        const areas = await res.json();
        const select = document.getElementById('filter-area');
        if (!select) return;
        select.innerHTML = '<option value="">All areas</option>' +
            areas.map(a => `<option value="${a.Id}">${a.Name}</option>`).join('');
    } catch (e) {
        console.error('loadAreasFilter', e);
    }
}

async function loadReports() {
    const filters = getFilters();
    const params = new URLSearchParams(filters).toString();

    try {
        const res = await fetch('../api/get_reports.php?' + params);
        if (!res.ok) throw new Error('Failed to load reports');
        const data = await res.json();

        renderKpis(data.kpi || {});
        renderSalesSummary(data.sales || []);
        renderRevenue(data.payments || []);
        renderOutstanding(data.outstanding || []);
    } catch (e) {
        console.error('loadReports', e);
    }
}

function nf(v) {
    return '₦' + Number(v || 0).toLocaleString();
}

// 1) KPI cards
function renderKpis(kpi) {
    const setText = (id, value) => {
        const el = document.getElementById(id);
        if (el) el.textContent = value;
    };

    setText('kpi-total-clients', kpi.totalClients ?? 0);
    setText('kpi-total-contracts', kpi.totalContracts ?? 0);
    setText('kpi-total-revenue', nf(kpi.totalRevenue));
    setText('kpi-total-collected', nf(kpi.totalCollected));
    setText('kpi-outstanding', nf(kpi.outstanding));
    setText('kpi-plots-sold', kpi.plotsSold ?? 0);
}

// 2) Sales summary
function renderSalesSummary(rows) {
    const tbody = document.getElementById('sales-tbody');
    if (!tbody) return;
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="9" class="px-3 py-3 text-center text-gray-400 text-[11px]">No data.</td></tr>';
        return;
    }

    tbody.innerHTML = rows.map(r => `
        <tr class="hover:bg-gray-50">
            <td class="px-3 py-2">${r.ContractCode}</td>
            <td class="px-3 py-2">${r.ClientName}</td>
            <td class="px-3 py-2">${r.PlotCode}</td>
            <td class="px-3 py-2">${r.AreaName}</td>
            <td class="px-3 py-2 text-right">${nf(r.OriginalPrice)}</td>
            <td class="px-3 py-2 text-right text-amber-600">${nf(r.DiscountAmount)}</td>
            <td class="px-3 py-2 text-right font-semibold">${nf(r.FinalPrice)}</td>
            <td class="px-3 py-2">${r.Status}</td>
            <td class="px-3 py-2">${r.CreatedAt}</td>
        </tr>
    `).join('');
}

// 3) Revenue collection
function renderRevenue(rows) {
    const tbody = document.getElementById('payments-tbody');
    if (!tbody) return;
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="7" class="px-3 py-3 text-center text-gray-400 text-[11px]">No payments.</td></tr>';
        return;
    }

    tbody.innerHTML = rows.map(r => `
        <tr class="hover:bg-gray-50">
            <td class="px-3 py-2">${r.InvoiceNumber || '-'}</td>
            <td class="px-3 py-2">${r.ClientName}</td>
            <td class="px-3 py-2">${r.ContractCode}</td>
            <td class="px-3 py-2">${r.PaymentDate}</td>
            <td class="px-3 py-2 text-right font-semibold">${nf(r.Amount)}</td>
            <td class="px-3 py-2">${r.Method || '-'}</td>
            <td class="px-3 py-2">${r.Reference || '-'}</td>
        </tr>
    `).join('');
}

// 4) Outstanding payments
function renderOutstanding(rows) {
    const tbody = document.getElementById('outstanding-tbody');
    if (!tbody) return;
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="6" class="px-3 py-3 text-center text-gray-400 text-[11px]">No outstanding balances.</td></tr>';
        return;
    }

    tbody.innerHTML = rows.map(r => `
        <tr class="hover:bg-gray-50">
            <td class="px-3 py-2">${r.ClientName}</td>
            <td class="px-3 py-2">${r.PlotCode}</td>
            <td class="px-3 py-2 text-right">${nf(r.FinalPrice)}</td>
            <td class="px-3 py-2 text-right text-emerald-600">${nf(r.AmountPaid)}</td>
            <td class="px-3 py-2 text-right text-red-500">${nf(r.Outstanding)}</td>
            <td class="px-3 py-2">${r.Status}</td>
        </tr>
    `).join('');
}

// CSV export helper
function exportTableToCsv(tableId, filename) {
    const table = document.getElementById(tableId);
    if (!table) return;

    const rows = Array.from(table.querySelectorAll('tr'));
    const csv = rows.map(tr =>
        Array.from(tr.querySelectorAll('th,td'))
            .map(td => `"${td.innerText.replace(/"/g, '""')}"`)
            .join(',')
    ).join('\n');

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename + '.csv';
    link.click();
}

// logout reused
function logout() {
    localStorage.removeItem('user');
    window.location.replace('../index.html');
}
