let filters = {
    quickRange: 'THIS_MONTH',
    start: null,
    end: null,
    status: 'ALL',
    planType: 'ALL',
    search: ''
};

document.addEventListener('DOMContentLoaded', () => {
    const userJson = localStorage.getItem('user');
    if (!userJson) {
        window.location.href = '../index.html';
        return;
    }
    const user = JSON.parse(userJson);
    document.getElementById('user-fullname').textContent = user.FullName || '';
    document.getElementById('user-role').textContent = user.Role || '';
    document.getElementById('user-initial').textContent = (user.FullName || 'A').charAt(0).toUpperCase();

    // NEW: role-based navigation filter (same as dashboard.js)
    const userRole = user.Role;
    const navLinks = document.querySelectorAll('.nav-link');

    navLinks.forEach(link => {
        const allowedRoles = link.getAttribute('data-role');
        if (!allowedRoles || allowedRoles === 'all') return;

        // Director sees everything
        if (userRole === 'Director') return;

        const rolesArray = allowedRoles.split(',').map(r => r.trim());
        if (!rolesArray.includes(userRole)) {
            link.remove();
        }
    });

    // === MOBILE SIDEBAR (copied from clients.js) ===
    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');
            }
        });
    }
    // === END MOBILE SIDEBAR ===

    wireFilters();
    applyQuickRange('THIS_MONTH');
    loadSales();
});

function wireFilters() {
    const quickRange = document.getElementById('CmbQuickRange');
    if (quickRange) {
        quickRange.addEventListener('change', e => {
            const selected = e.target.value || e.target.selectedOptions?.[0]?.dataset.tag;
            applyQuickRange(selected || 'THIS_MONTH');
            loadSales();
        });
    }

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

    const statusSel = document.getElementById('CmbStatusFilter');
    if (statusSel) {
        statusSel.addEventListener('change', () => {
            filters.status = statusSel.value || 'ALL';
            loadSales();
        });
    }

    const planSel = document.getElementById('CmbPlanTypeFilter');
    if (planSel) {
        planSel.addEventListener('change', () => {
            filters.planType = planSel.value || 'ALL';
            loadSales();
        });
    }

    const txtSearch = document.getElementById('TxtSearch');
    if (txtSearch) {
        txtSearch.addEventListener('input', e => {
            filters.search = e.target.value.trim();
            loadSales();
        });
    }

    const btnRefresh = document.getElementById('BtnRefresh');
    if (btnRefresh) {
        btnRefresh.addEventListener('click', loadSales);
    }
}

function applyQuickRange(tag) {
    filters.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 'THIS_WEEK': {
            const day = today.getDay(); // 0=Sun
            const diff = (day + 6) % 7; // Monday-based
            start = new Date(today.getFullYear(), today.getMonth(), today.getDate() - diff);
            end = clone(today);
            break;
        }
        case 'LAST_WEEK': {
            const day = today.getDay();
            const diff = (day + 6) % 7;
            const thisMonday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - diff);
            start = new Date(thisMonday.getFullYear(), thisMonday.getMonth(), thisMonday.getDate() - 7);
            end = new Date(thisMonday.getFullYear(), thisMonday.getMonth(), thisMonday.getDate() - 1);
            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 'ALL_TIME':
            start = null;
            end = null;
            break;
        case 'CUSTOM':
            // leave current dates; user will set DpStart/DpEnd
            return;
    }

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

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

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 onCustomDateChange() {
    filters.quickRange = 'CUSTOM';
    const dpStart = document.getElementById('DpStart');
    const dpEnd = document.getElementById('DpEnd');
    filters.start = dpStart && dpStart.value ? dpStart.value : null;
    filters.end = dpEnd && dpEnd.value ? dpEnd.value : null;
    loadSales();
}

async function loadSales() {
    try {
        const params = new URLSearchParams();
        if (filters.start) params.append('start', filters.start);
        if (filters.end) params.append('end', filters.end);
        if (filters.status) params.append('status', filters.status);
        if (filters.planType) params.append('planType', filters.planType);
        if (filters.search) params.append('search', filters.search);

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

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

        renderKpis(data.summary || {});
        renderContracts(data.contracts || []);
    } catch (err) {
        console.error('Failed to load sales summary', err);
    }
}

function renderKpis(summary) {
    const totalContracts = summary.totalContracts || 0;
    const totalValue = summary.totalValue || 0;
    const totalPaid = summary.totalPaid || 0;
    const totalOutstanding = summary.totalOutstanding || 0;

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

    const elTotalContracts = document.getElementById('TxtTotalContracts');
    const elTotalValue = document.getElementById('TxtTotalValue');
    const elTotalPaid = document.getElementById('TxtTotalPaid');
    const elOutstanding = document.getElementById('TxtTotalOutstanding');

    if (elTotalContracts) elTotalContracts.textContent = totalContracts.toString();
    if (elTotalValue) elTotalValue.textContent = nf(totalValue);
    if (elTotalPaid) elTotalPaid.textContent = nf(totalPaid);
    if (elOutstanding) elOutstanding.textContent = nf(totalOutstanding);
}

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

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

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

    tbody.innerHTML = list.map(row => {
        const status = (row.Status || '').trim();
        let badgeBg = 'bg-gray-100';
        let badgeText = 'text-gray-700';
        if (status === 'Active') { badgeBg = 'bg-green-50'; badgeText = 'text-green-600'; }
        if (status === 'Completed') { badgeBg = 'bg-indigo-50'; badgeText = 'text-indigo-600'; }
        if (status === 'Cancelled') { badgeBg = 'bg-red-50'; badgeText = 'text-red-600'; }

        const planType = row.PlanType || '';
        let planBg = 'bg-gray-100';
        let planText = 'text-gray-700';
        if (planType === 'Full Payment') { planBg = 'bg-green-50'; planText = 'text-green-600'; }
        if (planType === 'Installment') { planBg = 'bg-amber-50'; planText = 'text-amber-600'; }

        const created = row.CreatedAt ? new Date(row.CreatedAt).toLocaleDateString(undefined, {
            day: '2-digit', month: 'short', year: 'numeric'
        }) : '';

        return `
            <tr class="hover:bg-[#f6f9fc] transition-colors">
                <td class="px-4 py-3 font-semibold text-gray-800">${created}</td>
                <td class="px-4 py-3 font-semibold text-gray-900">${row.ClientName || ''}</td>
                <td class="px-4 py-3 text-gray-600">${row.AreaName || ''}</td>
                <td class="px-4 py-3 font-semibold text-[#3baa15]">${row.PlotCode || ''}</td>
                <td class="px-4 py-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold ${planBg} ${planText}">
                        ${planType}
                    </span>
                </td>
                <td class="px-4 py-3 text-center text-gray-600">
                    ${row.PlanMonths || 0}
                </td>
                <td class="px-4 py-3 font-bold text-[#125db8] text-sm">
                    ${nf(row.FinalPrice)}
                </td>
                <td class="px-4 py-3 font-semibold text-green-600 text-sm">
                    ${nf(row.AmountPaid)}
                </td>
                <td class="px-4 py-3 font-semibold text-red-600 text-sm">
                    ${nf(row.Outstanding)}
                </td>
                <td class="px-4 py-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold ${badgeBg} ${badgeText}">
                        ${status}
                    </span>
                </td>
            </tr>
        `;
    }).join('');
}

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