let discounts = [];
let editingId = null;

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

    // HARD GUARD: only Director can access this page
    if (user.Role !== 'Director') {
        alert('You are not allowed to access User Management.');
        window.location.href = 'dashboard.html';
        return;
    }

    // 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();

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

    // Form buttons
    const btnGenerateCode = document.getElementById('BtnGenerateCode');
    if (btnGenerateCode) btnGenerateCode.addEventListener('click', generateCode);

    const cmbType = document.getElementById('CmbDiscountType');
    if (cmbType) cmbType.addEventListener('change', onTypeChange);

    const btnClear = document.getElementById('BtnClearForm');
    if (btnClear) btnClear.addEventListener('click', clearForm);

    const btnSave = document.getElementById('BtnSaveDiscount');
    if (btnSave) btnSave.addEventListener('click', saveDiscount);

    loadDiscounts();
});

function generateCode() {
    const input = document.getElementById('TxtDiscountCode');
    if (!input) return;
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
        code += chars[Math.floor(Math.random() * chars.length)];
    }
    input.value = code;
}

function onTypeChange() {
    const cmb = document.getElementById('CmbDiscountType');
    const lbl = document.getElementById('LblValue');
    if (!cmb || !lbl) return;
    if (cmb.value === 'PERCENTAGE') {
        lbl.textContent = 'Percentage (%) *';
    } else {
        lbl.textContent = 'Amount (₦) *';
    }
}

function clearForm() {
    editingId = null;

    document.getElementById('TxtDiscountName').value = '';
    document.getElementById('TxtDiscountCode').value = '';
    document.getElementById('CmbDiscountType').value = 'PERCENTAGE';
    document.getElementById('TxtDiscountValue').value = '';
    document.getElementById('DpStartDate').value = '';
    document.getElementById('DpEndDate').value = '';
    document.getElementById('TxtMaxUses').value = '';
    document.getElementById('ChkIsActive').checked = true;
    onTypeChange();
}

async function loadDiscounts() {
    try {
        const res = await fetch('../api/discounts.php?action=list');
        const data = await res.json();

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

        discounts = Array.isArray(data.discounts) ? data.discounts : [];
        renderDiscounts();
    } catch (err) {
        console.error('Failed to load discounts', err);
    }
}

function renderDiscounts() {
    const tbody = document.getElementById('DiscountsTableBody');
    const countEl = document.getElementById('TxtDiscountCount');
    if (!tbody) return;

    if (!discounts.length) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="py-6 text-center text-gray-400 text-sm">
                    No discounts defined yet
                </td>
            </tr>`;
        if (countEl) countEl.textContent = '0';
        return;
    }

    if (countEl) countEl.textContent = String(discounts.length);

    const formatDate = d => d ? d : '';

    tbody.innerHTML = discounts.map(d => {
        const typeBadge = d.Type === 'PERCENTAGE'
            ? 'bg-[var(--brand-blue-soft)] text-[var(--brand-blue)]'
            : 'bg-green-50 text-green-700';

        const typeText = d.Type === 'PERCENTAGE' ? 'Percentage' : 'Fixed Amount';
        const valueText = d.Type === 'PERCENTAGE'
            ? `${Number(d.Value || 0)}%`
            : '₦' + Number(d.Value || 0).toLocaleString();

        const statusBadge = d.IsActive ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-600';
        const statusText = d.IsActive ? 'Active' : 'Inactive';

        return `
            <tr class="hover:bg-[#f6f9fc] cursor-pointer transition-colors"
                onclick="editDiscount(${d.Id})">
                <td class="px-4 py-3 font-mono font-bold text-[#3baa15]">${d.Code}</td>
                <td class="px-4 py-3 font-semibold text-gray-800">${d.Name}</td>
                <td class="px-4 py-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-[11px] font-semibold ${typeBadge}">
                        ${typeText}
                    </span>
                </td>
                <td class="px-4 py-3 font-bold text-[13px] text-[#8b4513]">
                    ${valueText}
                </td>
                <td class="px-4 py-3 text-[11px] text-gray-500">${formatDate(d.StartDateFormatted)}</td>
                <td class="px-4 py-3 text-[11px] text-gray-500">${formatDate(d.EndDateFormatted)}</td>
                <td class="px-4 py-3 text-center">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-[11px] font-semibold ${statusBadge}">
                        ${statusText}
                    </span>
                </td>
            </tr>
        `;
    }).join('');
}

function editDiscount(id) {
    const d = discounts.find(x => x.Id === id);
    if (!d) return;

    editingId = d.Id;

    document.getElementById('TxtDiscountName').value = d.Name || '';
    document.getElementById('TxtDiscountCode').value = d.Code || '';
    document.getElementById('CmbDiscountType').value = d.Type || 'PERCENTAGE';
    document.getElementById('TxtDiscountValue').value = d.Value || '';
    document.getElementById('DpStartDate').value = d.StartDate || '';
    document.getElementById('DpEndDate').value = d.EndDate || '';
    document.getElementById('TxtMaxUses').value = d.MaxUses || '';
    document.getElementById('ChkIsActive').checked = !!Number(d.IsActive);

    onTypeChange();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

async function saveDiscount() {
    const name = document.getElementById('TxtDiscountName').value.trim();
    const code = document.getElementById('TxtDiscountCode').value.trim();
    const type = document.getElementById('CmbDiscountType').value;
    const value = document.getElementById('TxtDiscountValue').value.trim();
    const startDate = document.getElementById('DpStartDate').value || null;
    const endDate = document.getElementById('DpEndDate').value || null;
    const maxUsesRaw = document.getElementById('TxtMaxUses').value.trim();
    const isActive = document.getElementById('ChkIsActive').checked ? 1 : 0;

    if (!name || !code || !value) {
        alert('Please fill in Discount Name, Discount Code and Value.');
        return;
    }

    const maxUses = maxUsesRaw === '' ? null : parseInt(maxUsesRaw, 10);

    const payload = {
        id: editingId,
        name,
        code,
        type,
        value,
        startDate,
        endDate,
        maxUses,
        isActive
    };

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

        if (!res.ok || data.error) {
            console.error('Save discount failed:', data);
            alert(data.error || 'Failed to save discount.');
            return;
        }

        clearForm();
        await loadDiscounts();
    } catch (err) {
        console.error('Save discount exception:', err);
        alert('An error occurred while saving discount.');
    }
}

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