let paymentsFilters = {
    quickRange: 'THIS_MONTH',
    start: null,
    end: null,
    search: ''
};

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

    // User info
    const fullEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    const initEl = document.getElementById('user-initial');
    if (fullEl) fullEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';
    if (initEl && user.FullName) initEl.textContent = user.FullName.charAt(0).toUpperCase();

    // Role-based navigation filter
    const userRole = user.Role;
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        const allowedRoles = link.getAttribute('data-role');
        if (!allowedRoles || allowedRoles === 'all') return;
        if (userRole === 'Director') return;
        const rolesArray = allowedRoles.split(',').map(r => r.trim());
        if (!rolesArray.includes(userRole)) {
            link.remove();
        }
    });

    // Mobile sidebar
    const mobileToggle = document.getElementById('mobile-toggle');
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');

    if (sidebar) {
        if (window.innerWidth < 1024) {
            sidebar.classList.add('-translate-x-full');
        } else {
            sidebar.classList.remove('-translate-x-full');
        }
    }

    if (mobileToggle && sidebar && overlay) {
        mobileToggle.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        });

        overlay.addEventListener('click', () => {
            sidebar.classList.add('-translate-x-full');
            overlay.classList.add('hidden');
        });

        window.addEventListener('resize', () => {
            if (window.innerWidth >= 1024) {
                sidebar.classList.remove('-translate-x-full');
                overlay.classList.add('hidden');
            } else {
                sidebar.classList.add('-translate-x-full');
            }
        });
    }

    // Search box
    const searchInput = document.getElementById('TxtSearch');
    if (searchInput) {
        searchInput.addEventListener('input', e => {
            paymentsFilters.search = e.target.value.trim();
            loadPayments();
        });
    }

    // Quick range
    const quickRange = document.getElementById('CmbQuickRange');
    if (quickRange) {
        quickRange.addEventListener('change', e => {
            const val = e.target.value || 'THIS_MONTH';
            applyQuickRange(val);
            loadPayments();
        });
    }

    // Date pickers
    const dpStart = document.getElementById('DpStart');
    const dpEnd = document.getElementById('DpEnd');
    if (dpStart) dpStart.addEventListener('change', onCustomDateChange);
    if (dpEnd) dpEnd.addEventListener('change', onCustomDateChange);

    // Refresh button
    const btnRefresh = document.getElementById('BtnRefresh');
    if (btnRefresh) {
        btnRefresh.addEventListener('click', loadPayments);
    }

    // Report buttons (HTML + Excel)
    const btnViewReport = document.getElementById('BtnViewReport');
    const btnExportExcel = document.getElementById('BtnExportExcel');
    const reportForm = document.getElementById('ReportForm');
    const rptStart = document.getElementById('RptStartDate');
    const rptEnd = document.getElementById('RptEndDate');
    const rptQuick = document.getElementById('RptQuickRange');
    const rptType = document.getElementById('RptExportType');

    function submitReport(exportType) {
        if (!reportForm || !rptStart || !rptEnd || !rptQuick || !rptType) return;

        rptStart.value = paymentsFilters.start || '';
        rptEnd.value = paymentsFilters.end || '';
        rptQuick.value = paymentsFilters.quickRange || '';
        rptType.value = exportType; // "HTML" or "EXCEL"

        reportForm.submit();
    }

    if (btnViewReport) {
        btnViewReport.addEventListener('click', () => {
            submitReport('HTML');
        });
    }

    if (btnExportExcel) {
        btnExportExcel.addEventListener('click', () => {
            submitReport('EXCEL');
        });
    }

    // Default range & initial load
    applyQuickRange('THIS_MONTH');
    loadPayments();
});

function toIso(d) {
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${d.getFullYear()}-${m}-${day}`;
}

function applyQuickRange(tag) {
    paymentsFilters.quickRange = tag;
    const today = new Date();
    let start = null, end = null;

    const clone = d => new Date(d.getFullYear(), d.getMonth(), d.getDate());

    switch (tag) {
        case 'TODAY':
            start = end = clone(today);
            break;
        case 'YESTERDAY':
            start = end = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
            break;
        case 'LAST7':
            end = clone(today);
            start = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6);
            break;
        case 'THIS_MONTH':
            start = new Date(today.getFullYear(), today.getMonth(), 1);
            end = clone(today);
            break;
        case 'LAST_MONTH':
            start = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            end = new Date(today.getFullYear(), today.getMonth(), 0);
            break;
        case 'THIS_YEAR':
            start = new Date(today.getFullYear(), 0, 1);
            end = clone(today);
            break;
        case 'LAST_YEAR':
            start = new Date(today.getFullYear() - 1, 0, 1);
            end = new Date(today.getFullYear() - 1, 11, 31);
            break;
        case 'CUSTOM':
            // user will edit date inputs manually
            return;
        default:
            start = null;
            end = null;
            break;
    }

    paymentsFilters.start = start ? toIso(start) : null;
    paymentsFilters.end = end ? toIso(end) : null;

    const dpStart = document.getElementById('DpStart');
    const dpEnd = document.getElementById('DpEnd');
    if (dpStart && start) dpStart.value = paymentsFilters.start;
    if (dpEnd && end) dpEnd.value = paymentsFilters.end;
}

function onCustomDateChange() {
    paymentsFilters.quickRange = 'CUSTOM';
    const dpStart = document.getElementById('DpStart');
    const dpEnd = document.getElementById('DpEnd');
    paymentsFilters.start = dpStart && dpStart.value ? dpStart.value : null;
    paymentsFilters.end = dpEnd && dpEnd.value ? dpEnd.value : null;
    loadPayments();
}

async function loadPayments() {
    try {
        const params = new URLSearchParams();
        if (paymentsFilters.start) params.append('start', paymentsFilters.start);
        if (paymentsFilters.end) params.append('end', paymentsFilters.end);
        if (paymentsFilters.search) params.append('search', paymentsFilters.search);

        const res = await fetch(`../api/get_payments_summary.php?${params.toString()}`);
        const data = await res.json();

        if (!res.ok) {
            console.error('Payments API error', data);
            return;
        }

        const summary = data.summary || {};
        const list = Array.isArray(data.payments) ? data.payments : [];

        renderKpis(summary);
        renderPayments(list);
    } catch (err) {
        console.error('Failed to load payments', err);
    }
}

function renderKpis(summary) {
    const nf = v => '₦' + Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: 2 });

    const totalReceived = summary.totalReceived || 0;
    const totalExpected = summary.totalExpected || 0;
    const totalOutstanding = summary.totalOutstanding || 0;

    const r = document.getElementById('TxtTotalReceived');
    const e = document.getElementById('TxtTotalExpected');
    const o = document.getElementById('TxtTotalOutstanding');

    if (r) r.textContent = nf(totalReceived);
    if (e) e.textContent = nf(totalExpected);
    if (o) o.textContent = nf(totalOutstanding);
}

function renderPayments(list) {
    const tbody = document.getElementById('PaymentsTableBody');
    if (!tbody) return;

    if (!list.length) {
        tbody.innerHTML = `
            <tr>
                <td colspan="10" class="py-6 text-center text-gray-400 text-sm">
                    No payments found for the selected filters
                </td>
            </tr>`;
        return;
    }

    const nf = v => '₦' + Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: 2 });

    tbody.innerHTML = list.map(p => {
        const date = p.PaymentDateFormatted || p.PaymentDate || '';
        const invoice = p.InvoiceNumber || '';
        const client = p.ClientName || '';
        const area = p.AreaName || '';
        const plot = p.PlotCode || '';
        const amount = nf(p.Amount || 0);
        const method = p.Method || '';
        const reference = p.Reference || '';
        const paymentId = p.Id;

        const proofPath = p.ProofFilePath || p.ProofOfPaymentPath || '';
        const hasProof = !!proofPath;
        const proofUrl = hasProof ? `../${proofPath}` : '#';

        const proofCell = hasProof
            ? `<button
                    class="inline-flex items-center justify-center px-3 py-1.5 rounded-lg bg-emerald-50 text-emerald-700 text-[11px] font-semibold hover:bg-emerald-100 border border-emerald-100 transition"
                    onclick="openProof('${encodeURIComponent(proofUrl)}')"
                    title="View uploaded proof">
                    <i class="fas fa-file-image mr-1 text-xs"></i> View
               </button>`
            : `<span class="inline-flex items-center px-3 py-1.5 rounded-lg bg-gray-100 text-gray-400 text-[10px] font-semibold">
                    <i class="fas fa-file-circle-xmark mr-1 text-xs"></i> None
               </span>`;

        return `
            <tr class="hover:bg-[#f6f9fc] transition-colors">
                <td class="px-4 py-3 font-semibold text-gray-800">${date}</td>
                <td class="px-4 py-3 font-semibold text-gray-700">${invoice}</td>
                <td class="px-4 py-3 font-semibold text-gray-900">${client}</td>
                <td class="px-4 py-3 text-gray-600">${area}</td>
                <td class="px-4 py-3 font-semibold text-[#3baa15]">${plot}</td>
                <td class="px-4 py-3 font-bold text-green-600 text-right">${amount}</td>
                <td class="px-4 py-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold
                                ${methodBadgeBg(method)} ${methodBadgeText(method)}">
                        ${method || 'N/A'}
                    </span>
                </td>
                <td class="px-4 py-3 text-[11px] text-gray-500 font-mono">${reference || ''}</td>
                <td class="px-4 py-3 text-center">
                    ${proofCell}
                </td>
                <td class="px-4 py-3 text-center">
                    <button
                        class="inline-flex items-center justify-center px-3 py-1.5 rounded-lg bg-[#3baa15] text-white text-[11px] font-semibold hover:bg-[#257b0b] transition-all"
                        onclick="openReceipt(${paymentId})"
                        title="View Receipt">
                        <i class="fas fa-receipt mr-1 text-xs"></i> Receipt
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

function openProof(encodedUrl) {
    const url = decodeURIComponent(encodedUrl);
    if (!url || url === '#') return;
    window.open(url, '_blank');
}

function methodBadgeBg(method) {
    const m = (method || '').toLowerCase();
    if (m === 'cash') return 'bg-green-50';
    if (m === 'bank transfer') return 'bg-[var(--brand-blue-soft)]';
    if (m === 'cheque') return 'bg-amber-50';
    if (m === 'pos' || m === 'card') return 'bg-indigo-50';
    return 'bg-gray-100';
}

function methodBadgeText(method) {
    const m = (method || '').toLowerCase();
    if (m === 'cash') return 'text-green-600';
    if (m === 'bank transfer') return 'text-[var(--brand-blue)]';
    if (m === 'cheque') return 'text-amber-700';
    if (m === 'pos' || m === 'card') return 'text-indigo-600';
    return 'text-gray-700';
}

function openReceipt(paymentId) {
    if (!paymentId) return;
    window.open(`templates/receipt.html?paymentId=${encodeURIComponent(paymentId)}`, '_blank');
}

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