/**
 * RiMax Business Partner (Supplier) Lifecycle Engine
 */

// Dynamically checks which ID is active to toggle views without hardcoding strings
window.toggleSupplierType = function() {
    const isCompany = document.getElementById('type_Company')?.checked;
    const secCompany = document.getElementById('section_company');
    const secIndividual = document.getElementById('section_individual');
    
    if (isCompany) {
        secCompany.classList.remove('d-none');
        secIndividual.classList.add('d-none');
        document.getElementById('req_company').required = true;
        document.getElementById('req_fname').required = false;
        document.getElementById('req_lname').required = false;
    } else {
        secCompany.classList.add('d-none');
        secIndividual.classList.remove('d-none');
        document.getElementById('req_company').required = false;
        document.getElementById('req_fname').required = true;
        document.getElementById('req_lname').required = true;
    }
};

// Form Delegation Submission
if (!window.supplierFormInit) {
    document.addEventListener('submit', async function (e) {
        if (e.target && e.target.id === 'supplierManagementForm') {
            e.preventDefault();
            const form = e.target;
            const btn = document.getElementById('btnSubmitSupplier');
            const msg = document.getElementById('supplierResponseMessage');
            
            if (!form.checkValidity()) { form.classList.add('was-validated'); return; }

            btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Registering...';
            msg.className = 'alert d-none shadow-sm mb-4 border-0'; 
            
            try {
                const res = await fetch('/rimax/application/dripend/systemSetup/inventory/processAddSupplier.php', { method: 'POST', body: new FormData(form) });
                const json = JSON.parse(await res.text());

                if (json.status === 'success') {
                    msg.classList.add('alert-success', 'bg-success', 'text-white');
                    msg.classList.remove('d-none');
                    msg.innerHTML = `<i class="fa-solid fa-check-circle me-2 fs-5"></i> ${json.message}`;
                    form.reset(); form.classList.remove('was-validated'); window.toggleSupplierType();
                    setTimeout(() => { window.location.href = "?cat=inventory&page=inventory/listSuppliers.php"; }, 1400);
                } else throw new Error(json.message);
            } catch (err) {
                msg.classList.add('alert-danger', 'bg-danger', 'text-white');
                msg.classList.remove('d-none');
                msg.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2 fs-5"></i> <strong>Error:</strong> ${err.message}`;
            } finally {
                btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up me-2"></i> Register Business Partner';
            }
        }
    });
    window.supplierFormInit = true;
}

// Fetch Grid View
setTimeout(() => { if (document.getElementById('suppliers_grid_container')) window.fetchSuppliersGrid(); }, 100);

window.fetchSuppliersGrid = async function() {
    const tbody = document.getElementById('suppliers_grid_container');
    if (!tbody) return;

    try {
        tbody.innerHTML = `<tr><td colspan="7" class="text-center py-5"><div class="spinner-border text-primary" role="status"></div></td></tr>`;
        const res = await fetch('/rimax/application/dripend/systemSetup/inventory/fetchSuppliers.php');
        const payload = await res.json();
        
        if (payload.status !== 'success') throw new Error(payload.message);

        document.getElementById('kpi_total').textContent = payload.kpis.total;
        document.getElementById('kpi_companies').textContent = payload.kpis.companies;
        document.getElementById('kpi_individuals').textContent = payload.kpis.individuals;
        document.getElementById('kpi_active').textContent = payload.kpis.active;

        if (payload.data.length === 0) {
            tbody.innerHTML = `<tr><td colspan="7" class="text-center py-5 text-muted"><i class="fa-solid fa-handshake-slash fs-2 mb-2 d-block"></i>No procurement partners defined.</td></tr>`; return;
        }

        tbody.innerHTML = ''; let count = 1;
        payload.data.forEach(item => {
            const icon = item.type === 'Company' ? '<i class="fa-solid fa-building text-primary me-2"></i>' : '<i class="fa-solid fa-user text-info me-2"></i>';
            const rolesHTML = item.roles.length > 0 ? item.roles.map(r => `<span class="badge bg-light text-secondary border me-1 mb-1">${r}</span>`).join('') : '<span class="text-muted small italic">General Supply</span>';
            const statusBadge = item.is_active === 1 ? '<span class="badge bg-success-subtle text-success border border-success px-3 py-1 rounded-pill">Active</span>' : '<span class="badge bg-danger-subtle text-danger border border-danger px-3 py-1 rounded-pill">Suspended</span>';

            const html = `
                <tr class="bg-white">
                    <td class="fw-bold px-4 text-muted">${count++}</td>
                    <td><div class="fw-bold text-dark">${item.display_name}</div><div class="font-monospace text-muted small mt-1">${item.code || '--'}</div></td>
                    <td class="fw-bold text-secondary">${icon} ${item.type}</td>
                    <td>${rolesHTML}</td>
                    <td><div class="fw-bold text-dark">${item.mobile}</div><div class="text-muted small mt-1"><i class="fa-solid fa-location-dot me-1"></i>${item.city}</div></td>
                    <td class="text-center">${statusBadge}</td>
                    <td class="text-center"><button class="btn btn-sm btn-light border p-2 text-info shadow-sm mx-1" title="View Dossier"><i class="fa-solid fa-folder-open"></i></button><button class="btn btn-sm btn-light border p-2 text-warning shadow-sm mx-1" title="Edit Master"><i class="fa-solid fa-pen"></i></button></td>
                </tr>
            `;
            tbody.insertAdjacentHTML('beforeend', html);
        });
    } catch (err) { tbody.innerHTML = `<tr><td colspan="7" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2"></i><br>${err.message}</td></tr>`; }
};