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

    // 2. Hydrate User Session Info
    const fullnameEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    const initialEl = document.getElementById('user-initial');

    if (fullnameEl) fullnameEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';
    if (initialEl && user.FullName) {
        initialEl.textContent = user.FullName.charAt(0).toUpperCase();
    }

    // 3. 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;

        // Director = super admin
        if (userRole === 'Director') return;

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

    // 4. Mobile Sidebar & Overlay Toggle
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    const mobileToggle = document.getElementById('mobile-toggle');

    const toggleSidebar = () => {
        if (!sidebar || !overlay) return;
        sidebar.classList.toggle('-translate-x-full');
        overlay.classList.toggle('hidden');
    };

    if (mobileToggle) mobileToggle.addEventListener('click', toggleSidebar);
    if (overlay) overlay.addEventListener('click', toggleSidebar);

    // 5. Form Submission for New Area
    const addAreaForm = document.getElementById('addAreaForm');
    if (addAreaForm) {
        addAreaForm.addEventListener('submit', handleAddArea);
    }

    // 6. Add plot form
    const addPlotForm = document.getElementById('addPlotForm');
    if (addPlotForm) {
        addPlotForm.addEventListener('submit', handleAddPlot);
    }

    // 7. Initial Data Load
    fetchAreas();
});


// --- AREA MODAL CONTROLS ---
function openAreaModal() {
    const modal = document.getElementById('area-modal');
    const container = document.getElementById('modal-container');
    if (!modal || !container) return;

    modal.classList.remove('hidden');
    modal.classList.add('flex');

    setTimeout(() => {
        container.classList.remove('scale-95', 'opacity-0');
        container.classList.add('scale-100', 'opacity-100');
    }, 10);
}

function closeAreaModal() {
    const modal = document.getElementById('area-modal');
    const container = document.getElementById('modal-container');
    const errorMsg = document.getElementById('modal-error');
    const form = document.getElementById('addAreaForm');

    if (!modal || !container) return;

    container.classList.add('scale-95', 'opacity-0');
    if (errorMsg) errorMsg.classList.add('hidden');

    setTimeout(() => {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        if (form) form.reset();
    }, 200);
}


// --- PLOTS MODAL CONTROLS ---
let currentAreaId = null;
let currentAreaName = '';

function openPlotsModal(areaId, areaName) {
    currentAreaId = areaId;
    currentAreaName = areaName;

    const modal = document.getElementById('plots-modal');
    const container = document.getElementById('plots-modal-container');
    const title = document.getElementById('plots-modal-title');

    if (!modal || !container) return;

    if (title) title.textContent = `Plots in ${areaName}`;

    modal.classList.remove('hidden');
    modal.classList.add('flex');

    setTimeout(() => {
        container.classList.remove('scale-95', 'opacity-0');
        container.classList.add('scale-100', 'opacity-100');
    }, 10);

    // Wire quick add button
    const quickBtn = document.getElementById('btn-quick-add-plot');
    if (quickBtn) {
        quickBtn.onclick = () => quickAddPlot(areaId, areaName);
    }

    // reset details panel
    resetPlotDetailsPanel();

    fetchPlotsForArea(areaId);
}

function closePlotsModal() {
    const modal = document.getElementById('plots-modal');
    const container = document.getElementById('plots-modal-container');
    if (!modal || !container) return;

    container.classList.add('scale-95', 'opacity-0');

    setTimeout(() => {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        const grid = document.getElementById('plots-grid');
        const empty = document.getElementById('plots-empty-state');
        if (grid) grid.innerHTML = '';
        if (empty) empty.classList.add('hidden');
        updatePlotsStats([]);
        resetPlotDetailsPanel();
    }, 200);
}


// --- ADD PLOT MODAL CONTROLS ---
function quickAddPlot(areaId, areaName) {
    const modal = document.getElementById('add-plot-modal');
    const container = document.getElementById('add-plot-container');
    const areaNameEl = document.getElementById('add-plot-area-name');
    const areaIdInput = document.getElementById('add-plot-area-id');
    const errorEl = document.getElementById('add-plot-error');
    const form = document.getElementById('addPlotForm');

    if (!modal || !container) return;

    if (areaNameEl) areaNameEl.textContent = `Area: ${areaName}`;
    if (areaIdInput) areaIdInput.value = areaId;
    if (errorEl) errorEl.classList.add('hidden');
    if (form) form.reset();

    modal.classList.remove('hidden');
    modal.classList.add('flex');

    setTimeout(() => {
        container.classList.remove('scale-95', 'opacity-0');
        container.classList.add('scale-100', 'opacity-100');
    }, 10);
}

function closeAddPlotModal() {
    const modal = document.getElementById('add-plot-modal');
    const container = document.getElementById('add-plot-container');
    const errorEl = document.getElementById('add-plot-error');
    const form = document.getElementById('addPlotForm');

    if (!modal || !container) return;

    container.classList.add('scale-95', 'opacity-0');
    if (errorEl) errorEl.classList.add('hidden');

    setTimeout(() => {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        if (form) form.reset();
    }, 200);
}


// Map numeric or string status to label used in UI
function mapStatus(raw) {
    // 0 = Available, 1 = Sold, 2 = Pending
    if (raw === 0 || raw === '0') return 'Available';
    if (raw === 1 || raw === '1') return 'Sold';
    if (raw === 2 || raw === '2') return 'Pending';
    // if already string, just return it
    return raw || 'Available';
}


// --- DATA: AREAS ---
async function fetchAreas() {
    const tbody = document.getElementById('areas-table-body');
    const emptyState = document.getElementById('empty-state');
    const badge = document.getElementById('total-areas-badge');

    if (!tbody || !badge) return;

    try {
        const response = await fetch('../api/get_areas.php');
        if (!response.ok) throw new Error('Failed to load areas');

        const data = await response.json();

        if (!Array.isArray(data) || data.length === 0) {
            tbody.innerHTML = '';
            if (emptyState) emptyState.classList.remove('hidden');
            badge.textContent = 'Total Areas: 0';
            return;
        }

        if (emptyState) emptyState.classList.add('hidden');
        badge.textContent = `Total Areas: ${data.length}`;

        tbody.innerHTML = data.map(area => `
            <tr class="hover:bg-[#f6f9fc] transition-colors group">
                <td class="px-8 py-5 font-bold text-[#3baa15] text-sm">${area.Id}</td>
                <td class="px-8 py-5 font-semibold text-gray-800 text-sm">${area.Name}</td>
                <td class="px-8 py-5 text-gray-500 text-xs max-w-xs truncate">
                    ${area.Description || 'No description provided'}
                </td>
                <td class="px-8 py-5 font-bold text-gray-700 text-sm">
                    ₦${Number(area.BasePricePerPlot || 0).toLocaleString()}
                </td>
                <td class="px-8 py-5">
                    <div class="flex justify-center gap-3">
                        <button onclick="viewPlots(${area.Id}, '${area.Name.replace(/'/g, "\\'")}')"
                                class="w-9 h-9 flex items-center justify-center bg-gray-50 text-gray-400 hover:text-[#3baa15] hover:bg-[rgba(59, 170, 21, 0.10)] rounded-xl transition-all"
                                title="View Plots">
                            <i class="fas fa-eye text-sm"></i>
                        </button>
                        <button onclick="quickAddPlot(${area.Id}, '${area.Name.replace(/'/g, "\\'")}')"
                                class="w-9 h-9 flex items-center justify-center bg-gray-50 text-gray-400 hover:text-green-500 hover:bg-green-50 rounded-xl transition-all"
                                title="Add Plot">
                            <i class="fas fa-plus text-sm"></i>
                        </button>
                        <button onclick="editArea(${area.Id})"
                                class="w-9 h-9 flex items-center justify-center bg-gray-50 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-xl transition-all"
                                title="Edit Area">
                            <i class="fas fa-cog text-sm"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    } catch (err) {
        console.error('Fetch areas error:', err);
        if (tbody) tbody.innerHTML = '';
        if (emptyState) emptyState.classList.remove('hidden');
        if (badge) badge.textContent = 'Total Areas: 0';
    }
}


// --- DATA: PLOTS ---
async function fetchPlotsForArea(areaId) {
    const grid = document.getElementById('plots-grid');
    const emptyState = document.getElementById('plots-empty-state');

    if (!grid) return;

    grid.innerHTML = '';

    try {
        const response = await fetch(`../api/get_plots.php?areaId=${encodeURIComponent(areaId)}`);
        if (!response.ok) throw new Error('Failed to load plots');

        const data = await response.json();

        if (!Array.isArray(data) || data.length === 0) {
            if (emptyState) emptyState.classList.remove('hidden');
            updatePlotsStats([]);
            window.__currentPlots = [];
            return;
        }

        if (emptyState) emptyState.classList.add('hidden');
        updatePlotsStats(data);

        grid.innerHTML = data.map((p, index) => {
            const status = mapStatus(p.Status);

            // tile background color
            let bg = 'bg-slate-500';
            if (status === 'Sold') bg = 'bg-emerald-500';
            else if (status === 'Pending') bg = 'bg-rose-500';

            const price = Number(p.FullPrice || p.ContractPrice || 0).toLocaleString();

            return `
        <button type="button"
                class="text-left rounded-2xl ${bg} text-white shadow-lg cursor-pointer transition transform hover:-translate-y-1 hover:shadow-xl focus:outline-none"
                onclick="selectPlot(${index})">
            <div class="p-4 flex flex-col h-full">
                <div class="inline-flex items-center justify-center px-3 py-1 rounded-lg bg-black/20 text-xs font-semibold mb-3">
                    ${p.Code}
                </div>
                <div class="flex-1 flex flex-col justify-center items-center text-center">
                    <p class="text-sm opacity-80 mb-1">Full Price</p>
                    <p class="text-lg font-bold">₦${price}</p>
                </div>
                <div class="mt-3">
                    <div class="w-full rounded-lg bg-white/90 px-3 py-1.5 text-center text-[11px] font-bold uppercase tracking-widest text-gray-700">
                        ${status}
                    </div>
                </div>
            </div>
        </button>
    `;
        }).join('');

        // store for detail panel
        window.__currentPlots = data;
    } catch (err) {
        console.error('Fetch plots error:', err);
        if (emptyState) emptyState.classList.remove('hidden');
        updatePlotsStats([]);
        window.__currentPlots = [];
    }
}

function updatePlotsStats(plots) {
    const totalEl = document.getElementById('plots-total');
    const availEl = document.getElementById('plots-available');
    const soldEl = document.getElementById('plots-sold');
    const pendEl = document.getElementById('plots-pending');

    const total = plots.length;
    const available = plots.filter(p => mapStatus(p.Status) === 'Available').length;
    const sold = plots.filter(p => mapStatus(p.Status) === 'Sold').length;
    const pending = plots.filter(p => mapStatus(p.Status) === 'Pending').length;

    if (totalEl) totalEl.textContent = `Total: ${total}`;
    if (availEl) availEl.textContent = `Available: ${available}`;
    if (soldEl) soldEl.textContent = `Sold: ${sold}`;
    if (pendEl) pendEl.textContent = `Pending: ${pending}`;
}


// --- PLOT DETAILS PANEL ---
function resetPlotDetailsPanel() {
    const codeEl = document.getElementById('detail-plot-code');
    const areaEl = document.getElementById('detail-area-name');
    const statusPill = document.getElementById('detail-status-pill');
    const areaPriceEl = document.getElementById('detail-area-price');
    const contractPriceEl = document.getElementById('detail-contract-price');
    const buyerEl = document.getElementById('detail-buyer');
    const planTypeEl = document.getElementById('detail-plan-type');
    const planDurationEl = document.getElementById('detail-plan-duration');
    const monthlyEl = document.getElementById('detail-monthly-amount');
    const totalPaidEl = document.getElementById('detail-total-paid');
    const outstandingEl = document.getElementById('detail-outstanding');
    const discountEl = document.getElementById('detail-discount');
    const notesEl = document.getElementById('detail-notes');
    const nextDueEl = document.getElementById('detail-next-due');

    if (codeEl) codeEl.textContent = 'No plot selected';
    if (areaEl) areaEl.textContent = 'Choose a plot on the left to view details.';
    if (statusPill) {
        statusPill.textContent = '-';
        statusPill.className = 'px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest bg-gray-100 text-gray-500';
    }
    if (areaPriceEl) areaPriceEl.textContent = '₦0';
    if (contractPriceEl) contractPriceEl.textContent = '₦0';
    if (buyerEl) buyerEl.textContent = '-';
    if (planTypeEl) planTypeEl.textContent = '-';
    if (planDurationEl) planDurationEl.textContent = '-';
    if (monthlyEl) monthlyEl.textContent = '₦0';
    if (totalPaidEl) totalPaidEl.textContent = '₦0';
    if (outstandingEl) outstandingEl.textContent = '₦0';
    if (nextDueEl) nextDueEl.textContent = '-';
    if (discountEl) {
        discountEl.textContent = 'No';
        discountEl.className = 'font-semibold text-emerald-600';
    }
    if (notesEl) {
        notesEl.textContent = 'Notes about this plot will appear here when you select a plot from the list.';
    }
}

function selectPlot(index) {
    const plots = window.__currentPlots || [];
    const p = plots[index];
    if (!p) return;

    const codeEl = document.getElementById('detail-plot-code');
    const areaEl = document.getElementById('detail-area-name');
    const statusPill = document.getElementById('detail-status-pill');
    const areaPriceEl = document.getElementById('detail-area-price');
    const contractPriceEl = document.getElementById('detail-contract-price');
    const buyerEl = document.getElementById('detail-buyer');
    const planTypeEl = document.getElementById('detail-plan-type');
    const planDurationEl = document.getElementById('detail-plan-duration');
    const monthlyEl = document.getElementById('detail-monthly-amount');
    const totalPaidEl = document.getElementById('detail-total-paid');
    const outstandingEl = document.getElementById('detail-outstanding');
    const discountEl = document.getElementById('detail-discount');
    const notesEl = document.getElementById('detail-notes');
    const nextDueEl = document.getElementById('detail-next-due');

    const status = mapStatus(p.Status);
    let pillClass = 'bg-gray-100 text-gray-500';
    if (status === 'Sold') pillClass = 'bg-emerald-100 text-emerald-700';
    else if (status === 'Pending') pillClass = 'bg-rose-100 text-rose-700';

    if (codeEl) codeEl.textContent = p.Code || 'Unknown plot';
    if (areaEl) areaEl.textContent = p.AreaName ? `Area: ${p.AreaName}` : '';
    if (statusPill) {
        statusPill.textContent = status;
        statusPill.className = 'px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ' + pillClass;
    }

    const nf = v => '₦' + Number(v || 0).toLocaleString();

    if (areaPriceEl) areaPriceEl.textContent = nf(p.FullPrice);          // total plot value
    if (contractPriceEl) contractPriceEl.textContent = nf(p.ContractPrice || p.FullPrice);
    if (buyerEl) buyerEl.textContent = p.BuyerName || '-';
    if (planTypeEl) planTypeEl.textContent = p.PlanType || '-';
    if (planDurationEl) {
        const months = p.PlanDurationMonths;
        planDurationEl.textContent = months ? `${months} months` : '-';
    }
    if (monthlyEl) monthlyEl.textContent = nf(p.MonthlyAmount);
    if (totalPaidEl) totalPaidEl.textContent = nf(p.TotalPaid);
    if (outstandingEl) outstandingEl.textContent = nf(p.OutstandingAmount);

    if (nextDueEl) {
        if (p.NextDue) {
            const d = new Date(p.NextDue);
            const opts = { day: '2-digit', month: 'short', year: 'numeric' };
            nextDueEl.textContent = d.toLocaleDateString(undefined, opts);
        } else {
            nextDueEl.textContent = '-';
        }
    }

    const hasDiscount = p.HasDiscount === 1 || p.HasDiscount === true || p.HasDiscount === '1';

    if (discountEl) {
        if (hasDiscount) {
            if (p.DiscountLabel) {
                discountEl.textContent = p.DiscountLabel;
            } else if (p.DiscountAmount) {
                discountEl.textContent = 'Yes (₦' + Number(p.DiscountAmount).toLocaleString() + ' off)';
            } else {
                discountEl.textContent = 'Yes';
            }
            discountEl.className = 'font-semibold text-emerald-600';
        } else {
            discountEl.textContent = 'No';
            discountEl.className = 'font-semibold text-gray-500';
        }
    }

    if (notesEl) {
        notesEl.textContent = p.Notes && p.Notes.trim().length
            ? p.Notes
            : 'No additional notes recorded for this plot.';
    }
}


// --- FORM HANDLING: PLOTS ---
async function handleAddPlot(e) {
    e.preventDefault();
    const errorEl = document.getElementById('add-plot-error');
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (!submitBtn) return;

    // Role guard: only Director can add plots
    const userJson = localStorage.getItem('user');
    const user = userJson ? JSON.parse(userJson) : null;
    if (!user || user.Role !== 'Director') {
        if (errorEl) {
            errorEl.textContent = 'Only Directors can add plots.';
            errorEl.classList.remove('hidden');
        } else {
            alert('Only Directors can add plots.');
        }
        return;
    }

    const formData = new FormData(e.target);
    const payload = {
        areaId: formData.get('areaId'),
        code: formData.get('code'),
        fullPrice: formData.get('fullPrice'),
        status: formData.get('status'),
        buyerName: formData.get('buyerName'),
        notes: formData.get('notes')
    };

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Saving...';

    try {
        const response = await fetch('../api/add_plot.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const text = await response.text();
        console.log('add_plot.php raw response:', text);

        let result;
        try {
            result = JSON.parse(text);
        } catch {
            if (errorEl) {
                errorEl.textContent = 'Server returned invalid response.';
                errorEl.classList.remove('hidden');
            }
            return;
        }

        if (result.success) {
            closeAddPlotModal();
            if (currentAreaId) {
                fetchPlotsForArea(currentAreaId);
            }
        } else if (errorEl) {
            errorEl.textContent = result.message || 'Failed to save plot.';
            errorEl.classList.remove('hidden');
        }
    } catch (err) {
        console.error('Add plot error:', err);
        if (errorEl) {
            errorEl.textContent = 'Server connection error.';
            errorEl.classList.remove('hidden');
        }
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Save Plot';
    }
}



// --- FORM HANDLING: AREAS ---
async function handleAddArea(e) {
    e.preventDefault();
    const errorMsg = document.getElementById('modal-error');
    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (!submitBtn) return;

    // Role guard: only Director can add areas
    const userJson = localStorage.getItem('user');
    const user = userJson ? JSON.parse(userJson) : null;
    if (!user || user.Role !== 'Director') {
        if (errorMsg) {
            errorMsg.textContent = 'Only Directors can add areas.';
            errorMsg.classList.remove('hidden');
        } else {
            alert('Only Directors can add areas.');
        }
        return;
    }

    const formData = new FormData(e.target);
    const rawBase = formData.get('basePrice');

    console.log('rawBase from form:', rawBase);

    const payload = {
        name: formData.get('name'),
        description: formData.get('description') || '',
        basePrice: rawBase === '' || rawBase === null ? null : rawBase,
        minPrice: formData.get('minPrice') || null,
        maxPrice: formData.get('maxPrice') || null,
        developmentType: formData.get('developmentType') || '',
        category: formData.get('category') || 'Residential',
        projectStatus: formData.get('projectStatus') || 'Ongoing',
        showOnWebsite: formData.get('showOnWebsite') || '1',
        configurations: formData.get('configurations') || '',
        layoutImage: formData.get('layoutImage') || '',
        frontImage: formData.get('frontImage') || '',
        leftImage: formData.get('leftImage') || '',
        rightImage: formData.get('rightImage') || '',
        sideImage: formData.get('sideImage') || '',
        extraImages: []
    };

    console.log('payload to API:', payload);

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Saving...';

    try {
        const response = await fetch('../api/add_area.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const text = await response.text();
        console.log('add_area.php raw response:', text);

        let result;
        try {
            result = JSON.parse(text);
        } catch {
            if (errorMsg) {
                errorMsg.textContent = 'Server returned invalid response.';
                errorMsg.classList.remove('hidden');
            }
            return;
        }

        if (result.success) {
            closeAreaModal();
            fetchAreas();
        } else if (errorMsg) {
            errorMsg.textContent = result.message || 'Failed to save area.';
            errorMsg.classList.remove('hidden');
        }
    } catch (err) {
        console.error('Add area error:', err);
        if (errorMsg) {
            errorMsg.textContent = 'Server connection error.';
            errorMsg.classList.remove('hidden');
        }
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Save Project Area';
    }
}



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

function viewPlots(areaId, areaName) {
    openPlotsModal(areaId, areaName);
}

function editArea(areaId) {
    window.location.href = `manage-area.html?id=${encodeURIComponent(areaId)}`;
}

