let currentUser = null;
let basePrice = 0;
let discountAmount = 0;
let finalPrice = 0;

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

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

    const userRole = currentUser.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();
        }
    });

    if (userRole !== 'Director' && userRole !== 'Staff') {
        alert('Only Directors and Staff can add clients with plot purchase.');
        window.location.href = 'clients.html';
        return;
    }

    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');
            }
        });
    }

    ['surname', 'firstName', 'otherName'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('input', updateFullName);
    });

    loadAreas();

    const areaSelect = document.getElementById('areaSelect');
    const plotSelect = document.getElementById('plotSelect');
    if (areaSelect) areaSelect.addEventListener('change', handleAreaChange);
    if (plotSelect) plotSelect.addEventListener('change', handlePlotChange);

    const applyBtn = document.getElementById('btn-apply-discount');
    if (applyBtn) applyBtn.addEventListener('click', applyDiscount);

    const paymentMode = document.getElementById('paymentMode');
    const installmentMonths = document.getElementById('installmentMonths');
    if (paymentMode) {
        paymentMode.addEventListener('change', () => {
            if (paymentMode.value === 'INSTALLMENT') {
                installmentMonths.disabled = false;
            } else {
                installmentMonths.disabled = true;
                installmentMonths.value = '';
            }
            updateMonthlyAmount();
        });
    }
    if (installmentMonths) {
        installmentMonths.addEventListener('change', updateMonthlyAmount);
    }

    // Set registration date default = today (yyyy-mm-dd)
    const regDateInput = document.getElementById('registrationDate');
    if (regDateInput) {
        const today = new Date();
        const yyyy = today.getFullYear();
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        regDateInput.value = `${yyyy}-${mm}-${dd}`;
    }


    const form = document.getElementById('add-client-form');
    if (form) form.addEventListener('submit', handleSubmit);
});

function updateFullName() {
    const s = (document.getElementById('surname')?.value || '').trim();
    const f = (document.getElementById('firstName')?.value || '').trim();
    const o = (document.getElementById('otherName')?.value || '').trim();
    const parts = [s, f, o].filter(x => x.length);
    const full = parts.join(' ');
    const fullNameEl = document.getElementById('fullName');
    if (fullNameEl) fullNameEl.value = full;
}

async function loadAreas() {
    const sel = document.getElementById('areaSelect');
    if (!sel) return;
    sel.innerHTML = '<option value="">Loading areas...</option>';

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

        if (!Array.isArray(areas) || !areas.length) {
            sel.innerHTML = '<option value="">No areas found</option>';
            return;
        }

        sel.innerHTML = '<option value="">Select area...</option>' +
            areas.map(a => `<option value="${a.Id}">${a.Name}</option>`).join('');
    } catch (err) {
        console.error('loadAreas error:', err);
        sel.innerHTML = '<option value="">Error loading areas</option>';
    }
}

async function handleAreaChange() {
    const areaId = this.value;
    const plotSel = document.getElementById('plotSelect');
    const basePriceEl = document.getElementById('basePrice');
    const discountCodeEl = document.getElementById('discountCode');
    const discountInfoEl = document.getElementById('discountInfo');

    if (plotSel) plotSel.innerHTML = '<option value="">Loading plots...</option>';
    basePrice = 0;
    discountAmount = 0;
    updatePriceFields();

    if (discountCodeEl) discountCodeEl.value = '';
    if (discountInfoEl) {
        discountInfoEl.textContent = '';
        discountInfoEl.className = 'text-xs mt-1';
    }

    if (!areaId) {
        if (plotSel) plotSel.innerHTML = '<option value="">Select area first...</option>';
        if (basePriceEl) basePriceEl.value = '';
        return;
    }

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

        if (!Array.isArray(plots) || !plots.length) {
            if (plotSel) plotSel.innerHTML = '<option value="">No available plots</option>';
            if (basePriceEl) basePriceEl.value = '';
            return;
        }

        if (plotSel) {
            plotSel.innerHTML = '<option value="">Select plot...</option>' +
                plots.map(p =>
                    `<option value="${p.Id}" data-price="${p.FullPrice}">${p.Code}</option>`
                ).join('');
        }
    } catch (err) {
        console.error('handleAreaChange error:', err);
        if (plotSel) plotSel.innerHTML = '<option value="">Error loading plots</option>';
    }
}

function handlePlotChange() {
    const opt = this.selectedOptions[0];
    const priceEl = document.getElementById('basePrice');
    const discCodeEl = document.getElementById('discountCode');
    const discInfoEl = document.getElementById('discountInfo');

    basePrice = 0;
    if (opt && opt.dataset.price) {
        basePrice = Number(opt.dataset.price) || 0;
    }

    if (priceEl) priceEl.value = basePrice ? basePrice.toLocaleString() : '';
    discountAmount = 0;
    updatePriceFields();

    // If there is already a discount code typed, re-apply it for this plot
    const code = (discCodeEl?.value || '').trim().toUpperCase();
    if (code) {
        applyDiscount();
    } else if (discInfoEl) {
        discInfoEl.textContent = '';
        discInfoEl.className = 'text-xs mt-1';
    }
}

function updatePriceFields() {
    finalPrice = Math.max(0, basePrice - discountAmount);
    const discEl = document.getElementById('discountAmount');
    const finalEl = document.getElementById('finalPrice');

    if (discEl) discEl.value = discountAmount ? discountAmount.toLocaleString() : '0';
    if (finalEl) finalEl.value = finalPrice ? finalPrice.toLocaleString() : '0';

    updateMonthlyAmount();
}

function updateMonthlyAmount() {
    const modeEl = document.getElementById('paymentMode');
    const monthsEl = document.getElementById('installmentMonths');
    const monthlyEl = document.getElementById('monthlyAmount');
    if (!modeEl || !monthlyEl) return;

    if (modeEl.value !== 'INSTALLMENT') {
        monthlyEl.value = finalPrice ? finalPrice.toLocaleString() : '0';
        return;
    }

    const months = monthsEl && monthsEl.value ? parseInt(monthsEl.value, 10) : 0;
    if (!months || !finalPrice) {
        monthlyEl.value = '0';
        return;
    }

    const monthly = Math.ceil(finalPrice / months);
    monthlyEl.value = monthly.toLocaleString();
}

async function applyDiscount() {
    const infoEl = document.getElementById('discountInfo');
    const codeEl = document.getElementById('discountCode');

    const plotSelect = document.getElementById('plotSelect');
    if (!plotSelect || !plotSelect.value) {
        if (infoEl) {
            infoEl.textContent = 'Select an area and plot first.';
            infoEl.className = 'text-xs mt-1 text-red-500';
        }
        return;
    }

    if (!basePrice || basePrice <= 0) {
        if (infoEl) {
            infoEl.textContent = 'Select a plot first.';
            infoEl.className = 'text-xs mt-1 text-red-500';
        }
        return;
    }

    const code = (codeEl?.value || '').trim().toUpperCase();
    if (!code) {
        if (infoEl) {
            infoEl.textContent = 'Enter discount code.';
            infoEl.className = 'text-xs mt-1 text-red-500';
        }
        return;
    }

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

        const text = await res.text();
        let data;
        try { data = JSON.parse(text); }
        catch {
            if (infoEl) {
                infoEl.textContent = 'Server returned invalid response.';
                infoEl.className = 'text-xs mt-1 text-red-500';
            }
            return;
        }

        if (!data.success) {
            discountAmount = 0;
            updatePriceFields();
            if (infoEl) {
                infoEl.textContent = data.message || 'Discount code invalid.';
                infoEl.className = 'text-xs mt-1 text-red-500';
            }
            return;
        }

        discountAmount = Number(data.discountAmount || 0);
        updatePriceFields();
        if (infoEl) {
            infoEl.textContent = data.label || 'Discount applied successfully.';
            infoEl.className = 'text-xs mt-1 text-green-600 font-semibold';
        }
    } catch (err) {
        console.error('applyDiscount error:', err);
        if (infoEl) {
            infoEl.textContent = 'Error applying discount.';
            infoEl.className = 'text-xs mt-1 text-red-500';
        }
    }
}

async function handleSubmit(e) {
    e.preventDefault();
    const errEl = document.getElementById('form-error');
    const btn = document.getElementById('btn-save');
    if (errEl) errEl.textContent = '';

    const surname = document.getElementById('surname').value.trim();
    const firstName = document.getElementById('firstName').value.trim();
    const fullName = document.getElementById('fullName').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const areaId = document.getElementById('areaSelect').value;
    const plotId = document.getElementById('plotSelect').value;
    const paymentMode = document.getElementById('paymentMode').value;
    const monthsVal = document.getElementById('installmentMonths').value;
    const registrationDate = document.getElementById('registrationDate').value;

    if (!surname || !firstName || !phone || !areaId || !plotId) {
        if (errEl) errEl.textContent = 'Surname, First Name, Phone, Area and Plot are required.';
        return;
    }

    if (!finalPrice || finalPrice <= 0) {
        if (errEl) errEl.textContent = 'Final price must be greater than zero.';
        return;
    }

    if (!registrationDate) {
        if (errEl) errEl.textContent = 'Please select registration date.';
        return;
    }


    let planMonths = null;
    let monthlyAmount = finalPrice;
    if (paymentMode === 'INSTALLMENT') {
        if (!monthsVal) {
            if (errEl) errEl.textContent = 'Select installment duration.';
            return;
        }
        planMonths = parseInt(monthsVal, 10);
        monthlyAmount = Math.ceil(finalPrice / planMonths);
    }

    const payload = {
        client: {
            surname,
            firstName,
            otherName: document.getElementById('otherName').value.trim(),
            fullName,
            gender: document.getElementById('gender').value || null,
            dateOfBirth: document.getElementById('dob').value || null,
            maritalStatus: document.getElementById('maritalStatus').value || null,
            nationality: document.getElementById('nationality').value || null,
            stateOfOrigin: document.getElementById('stateOfOrigin').value || null,
            lga: document.getElementById('lga').value || null,
            address: document.getElementById('address').value || null,
            phone,
            altPhone: document.getElementById('altPhone').value || null,
            email: document.getElementById('email').value || null,
            nokName: document.getElementById('nokName').value || null,
            nokRelationship: document.getElementById('nokRelationship').value || null,
            nokPhone: document.getElementById('nokPhone').value || null,
            nokAddress: document.getElementById('nokAddress').value || null,
            createdAt: registrationDate || null
        },
        contract: {
            areaId: parseInt(areaId, 10),
            plotId: parseInt(plotId, 10),
            originalPrice: basePrice,
            discountCode: document.getElementById('discountCode').value.trim().toUpperCase() || null,
            discountAmount: discountAmount,
            finalPrice: finalPrice,
            planType: paymentMode === 'FULL' ? 'Full Payment' : 'Installment Plan',
            planMonths: planMonths,
            monthlyAmount: monthlyAmount,
            createdAt: registrationDate || null
        }
    };

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

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

        const text = await res.text();
        let data;
        try { data = JSON.parse(text); }
        catch {
            if (errEl) errEl.textContent = 'Server returned invalid response.';
            return;
        }

        if (!data.success) {
            if (errEl) errEl.textContent = data.message || 'Failed to save client and plot.';
            return;
        }

        alert(`Client and plot saved successfully.\nClient ID: ${data.clientCode}\nContract ID: ${data.contractCode}`);
        window.location.href = 'clients.html';
    } catch (err) {
        console.error('add_client_with_plot error:', err);
        if (errEl) errEl.textContent = 'Server connection error.';
    } finally {
        btn.disabled = false;
        btn.innerHTML = '✓ Save Client &amp; Plot';
    }
}

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