/* assets/js/mobile-admin.js */

let companySettings = { company_currency_code: '$' };
let currentView = 'dashboard';
let userProfile = null;

let productsCache = [];
let usersCache = [];
let purchasesCache = [];
let currentPoItems = [];
let currentPoStatus = 'Pending';
let inventoryBatchSize = 30;
let lastInventoryIndex = 0;
let filteredInventoryCache = [];
let isLoadingMoreInventory = false;

document.addEventListener('DOMContentLoaded', async () => {
    // Auth Check
    const res = await fetch('api/auth.php?action=me');
    const data = await res.json();
    if (!data.success || !data.user) {
        window.location.href = 'login';
        return;
    }
    userProfile = data.user;

    // Reject non-admins
    if (userProfile.role !== 'Admin' && userProfile.role !== 'Accounts') {
        window.location.href = 'mobile-pos';
        return;
    }

    // Update UI headers
    document.getElementById('userInfo').innerText = userProfile.username;

    // Load Settings
    try {
        const sRes = await fetch('api/settings.php?action=get');
        const sData = await sRes.json();
        if (sData.success) {
            companySettings = sData.data;
        }
    } catch (e) { console.error("Could not load settings"); }

    // Init data
    loadKPIs();
    initTrendChart();
    loadInventory();
    loadReports();

    // Bind Search
    document.getElementById('inventorySearch').addEventListener('input', (e) => {
        renderInventory(e.target.value, false);
    });

    // Infinite Scroll for Inventory
    window.addEventListener('scroll', () => {
        if (currentView !== 'inventory' || isLoadingMoreInventory) return;
        
        // Use a threshold (100px from bottom)
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 200) {
            const term = document.getElementById('inventorySearch').value;
            renderInventory(term, true);
        }
    });
});

function switchView(view) {
    // Hide all views
    document.querySelectorAll('.mobile-view').forEach(v => {
        v.style.display = 'none';
    });
    
    // Show selected view
    document.getElementById('view-' + view).style.display = 'block';

    // Update Bottom Nav UI
    document.querySelectorAll('.nav-item').forEach(n => {
        n.classList.remove('active');
    });
    const navBtn = document.getElementById('nav-' + view);
    const bottomNav = document.querySelector('.mobile-bottom-nav');

    if (view === 'manage-purchase' || view === 'supplier-details' || view === 'sale-items' || view === 'edit-product' || view === 'stock-correction' || view === 'categories' || view.startsWith('settings-')) {
        if (bottomNav) bottomNav.style.display = 'none';
    } else {
        if (bottomNav) bottomNav.style.display = 'flex';
    }

    if (navBtn) {
        navBtn.classList.add('active');
    } else if (view === 'settings' || view.startsWith('settings-')) {
        const moreBtn = document.getElementById('nav-more');
        if (moreBtn) moreBtn.classList.add('active');
    }

    currentView = view;

    // Lazy Loads
    if (view === 'users' && !window.usersLoaded) loadUsers();
    if (view === 'suppliers' && !window.suppliersLoaded) loadSuppliers();
    if (view === 'purchases' && !window.purchasesLoaded) loadPurchases();
    if (view === 'categories' && !window.categoriesLoaded) loadCategoriesList();
    if (view === 'settings' || view.startsWith('settings-')) populateSettingsMobile();
}

function formatCurrency(n) {
    if(!n) return "0.00";
    return parseFloat(n).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

async function loadKPIs() {
    try {
        const res = await fetch('api/reports.php?action=dashboard_stats');
        const data = await res.json();
        if (data.success && data.data) {
            const sym = companySettings.company_currency_code || '$';
            const stats = data.data;

            document.getElementById('kpiTodaySales').innerText = `${sym} ${formatCurrency(stats.today_sales)}`;
            document.getElementById('kpiMonthlySales').innerText = `${sym} ${formatCurrency(stats.mtd_sales)}`;
            document.getElementById('kpiLowStock').innerText = stats.low_stock;
            document.getElementById('kpiTotalSKUs').innerText = stats.total_skus;
        }
    } catch(e) { console.error(e); }
}

async function initTrendChart() {
    try {
        const res = await fetch('api/reports.php?action=sales_summary');
        const data = await res.json();
        if (!data.success) return;

        const ctx = document.getElementById('salesTrendChart').getContext('2d');
        const labels = data.data.map(r => r.date).reverse();
        const values = data.data.map(r => r.revenue).reverse();

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Revenue',
                    data: values,
                    backgroundColor: '#4361ee',
                    borderRadius: 4,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { 
                        beginAtZero: true, 
                        grid: { display: false },
                        ticks: { display: false }
                    },
                    x: {
                        grid: { display: false },
                        ticks: { maxTicksLimit: 7 }
                    }
                }
            }
        });
    } catch(e) { console.error(e); }
}

async function loadInventory() {
    try {
        const r = await fetch('api/products.php?action=list');
        const data = await r.json();
        if (data.success) {
            productsCache = data.data;
            renderInventory();
        }
    } catch (e) { console.error(e); }
}

function renderInventory(searchTerm = '', append = false) {
    const list = document.getElementById('inventoryList');
    const sym = companySettings.company_currency_code || '$';
    const term = searchTerm.toLowerCase();

    if (!append) {
        list.innerHTML = '';
        lastInventoryIndex = 0;
        // Pre-filter so we only slice what matches
        filteredInventoryCache = productsCache.filter(p => {
            return p.name.toLowerCase().includes(term) || (p.sku && p.sku.toLowerCase().includes(term));
        });
    }

    if (filteredInventoryCache.length === 0) {
        if (!append) list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No products found</div>';
        return;
    }

    if (lastInventoryIndex >= filteredInventoryCache.length) return;

    isLoadingMoreInventory = true;
    
    // Slice the next batch
    const nextBatch = filteredInventoryCache.slice(lastInventoryIndex, lastInventoryIndex + inventoryBatchSize);
    lastInventoryIndex += inventoryBatchSize;

    nextBatch.forEach(p => {
        const lowStockAlert = p.stock_quantity <= p.alert_quantity ? '<i class="fa-solid fa-triangle-exclamation text-warning ms-2"></i>' : '';
        const item = document.createElement('div');
        item.className = 'mobile-list-item';
        const pStr = btoa(unescape(encodeURIComponent(JSON.stringify(p))));
        item.innerHTML = `
            <div style="flex:1;">
                <div style="font-weight:800; font-size:15px; color:#1a1a1a;">${p.name}</div>
                <div style="font-size:12px; color:#666; font-weight:700; margin-top:2px;">
                    Stock: <span style="color:${p.stock_quantity <= p.alert_quantity ? 'var(--danger)' : 'var(--success)'}">${p.stock_quantity}</span>
                    ${lowStockAlert} | SKU: ${p.sku}
                </div>
            </div>
            <div style="text-align:right; display:flex; flex-direction:column; align-items:flex-end; gap:5px;">
                <div style="font-weight:800; color:var(--primary); font-size:15px;">
                    ${sym}${formatCurrency(p.selling_price)}
                </div>
                <div style="display:flex; gap:10px;">
                    <button onclick="openStockCorrection('${pStr}')" title="Correct Stock" style="background:rgba(255, 159, 64, 0.1); border:none; color:#ff9f40; font-size:14px; padding:2px 8px; border-radius:6px;"><i class="fa-solid fa-boxes-stacked"></i></button>
                    <button onclick="editProductMobile('${pStr}')" style="background:none; border:none; color:var(--primary); font-size:14px; padding:2px;"><i class="fa-solid fa-pen"></i></button>
                    <button onclick="deleteProductMobile(${p.id})" style="background:none; border:none; color:var(--danger); font-size:14px; padding:2px;"><i class="fa-solid fa-trash-can"></i></button>
                </div>
            </div>
        `;
        list.appendChild(item);
    });

    isLoadingMoreInventory = false;
}

async function loadReports() {
    try {
        const res = await fetch('api/reports.php?action=sales_summary');
        const data = await res.json();
        if (data.success) {
            const list = document.getElementById('salesList');
            list.innerHTML = '';
            const sym = companySettings.company_currency_code || '$';

            data.data.forEach(row => {
                const item = document.createElement('div');
                item.className = 'mobile-list-item';
                item.onclick = () => openSaleItems(row.date);
                item.innerHTML = `
                    <div style="display:flex; align-items:center; gap:15px;">
                        <div style="background:rgba(67, 97, 238, 0.1); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; color:var(--primary); font-size:12px; font-weight:800;">
                            ${row.date.split('-')[2]}
                        </div>
                        <div>
                            <div style="font-weight:800; font-size:14px;">${row.date}</div>
                            <div style="font-size:12px; color:#666; font-weight:700;">${row.total_sales} Transactions</div>
                        </div>
                    </div>
                    <div style="font-weight:800; color:var(--success); font-size:16px;">
                        ${sym}${formatCurrency(row.revenue)}
                    </div>
                `;
                list.appendChild(item);
            });
        }
    } catch (e) { console.error(e); }
}

async function openSaleItems(date) {
    switchView('sale-items');
    const subtitle = document.getElementById('saleItemsSubtitle');
    if (subtitle) subtitle.innerText = "Items sold on " + date;
    const list = document.getElementById('saleItemsList');
    list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">Loading items...</div>';
    const sym = companySettings.company_currency_code || '$';

    try {
        const res = await fetch(`api/reports.php?action=sale_items&date=${date}`);
        const data = await res.json();
        if (data.success) {
            list.innerHTML = '';
            if (data.data.length === 0) {
                list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No items found for this date.</div>';
                return;
            }

            data.data.forEach(item => {
                const tr = document.createElement('div');
                tr.className = 'mobile-list-item';
                const lineTotal = parseFloat(item.quantity) * parseFloat(item.price);
                tr.innerHTML = `
                    <div style="flex:1;">
                        <div style="font-weight:800; font-size:14px; color:#1a1a1a;">${item.product_name}</div>
                        <div style="font-size:12px; color:#666; font-weight:700; margin-top:2px;">
                            Qty: <span style="color:var(--primary)">${item.quantity}</span> | REC-${item.sale_id} (${item.payment_method})
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-weight:800; color:#1a1a1a; font-size:14px;">${sym}${formatCurrency(lineTotal)}</div>
                        <div style="font-size:11px; color:#999;">${sym}${formatCurrency(item.price)} each</div>
                    </div>
                `;
                list.appendChild(tr);
            });
        }
    } catch (e) {
        console.error(e);
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold text-danger">Error loading items</div>';
    }
}

async function loadUsers() {
    window.usersLoaded = true;
    try {
        const res = await fetch('api/users.php?action=list');
        const data = await res.json();
        if (data.success && data.data) {
            usersCache = data.data;
            renderUsers();
        } else {
            document.getElementById('usersList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Failed to load users</div>';
        }
    } catch(e) {
        document.getElementById('usersList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Error loading users</div>';
    }
}

function renderUsers(searchTerm = '') {
    const list = document.getElementById('usersList');
    list.innerHTML = '';
    const term = searchTerm.toLowerCase();

    if (!usersCache || usersCache.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No users listed</div>';
        return;
    }

    const filtered = usersCache.filter(u => {
        return (u.fullname && u.fullname.toLowerCase().includes(term)) || 
               (u.username && u.username.toLowerCase().includes(term)) ||
               (u.role && u.role.toLowerCase().includes(term));
    });

    if (filtered.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No match found</div>';
        return;
    }

    filtered.forEach(u => {
        const userStr = btoa(unescape(encodeURIComponent(JSON.stringify(u))));
        list.innerHTML += `
        <div class="mobile-list-item">
            <div style="display:flex; align-items:center; gap:15px;">
                <div style="background:rgba(67, 97, 238, 0.1); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; color:var(--primary); font-size:16px; font-weight:800;">
                    <i class="fa-solid fa-user"></i>
                </div>
                <div>
                    <div style="font-weight:800; font-size:15px; color:#1a1a1a;">${u.fullname || u.username}</div>
                    <div style="font-size:12px; color:#666; font-weight:700;">Role: ${u.role}</div>
                </div>
            </div>
            <div style="display:flex; gap:12px;">
                <button onclick="editUserMobile('${userStr}')" style="background:none; border:none; color:var(--primary); font-size:17px; padding:5px;"><i class="fa-solid fa-pen-to-square"></i></button>
                <button onclick="deleteUserMobile(${u.id})" style="background:none; border:none; color:var(--danger); font-size:17px; padding:5px;"><i class="fa-solid fa-trash-can"></i></button>
            </div>
        </div>`;
    });
}

function openAddUserModal() {
    document.getElementById('m_userModalTitle').innerText = 'New User';
    document.getElementById('addUserFormMobile').reset();
    document.getElementById('mu_id').value = '';
    document.getElementById('mu_password').required = true;
    document.getElementById('mu_pass_hint').style.display = 'none';
    
    document.querySelector('.mobile-bottom-nav').style.display = 'none';
    
    const m = document.getElementById('addUserModal');
    m.style.display = 'flex';
    setTimeout(() => m.classList.add('modal-visible'), 10);
}

function closeAddUserModal() {
    const m = document.getElementById('addUserModal');
    m.classList.remove('modal-visible');
    setTimeout(() => { 
        m.style.display = 'none'; 
        document.querySelector('.mobile-bottom-nav').style.display = 'flex';
    }, 300);
}

function editUserMobile(userStr) {
    const u = JSON.parse(decodeURIComponent(escape(atob(userStr))));
    document.getElementById('m_userModalTitle').innerText = 'Edit User';
    document.getElementById('mu_id').value = u.id;
    document.getElementById('mu_fullname').value = u.fullname || '';
    document.getElementById('mu_username').value = u.username || '';
    document.getElementById('mu_role').value = u.role || 'Cashier';
    document.getElementById('mu_mobile').value = u.mobile || '';
    
    document.getElementById('mu_password').value = ''; 
    document.getElementById('mu_password').required = false; 
    document.getElementById('mu_pass_hint').style.display = 'block';

    document.querySelector('.mobile-bottom-nav').style.display = 'none';

    const m = document.getElementById('addUserModal');
    m.style.display = 'flex';
    setTimeout(() => m.classList.add('modal-visible'), 10);
}

async function saveUserMobile(e) {
    e.preventDefault();
    const btn = document.getElementById('btnSaveUserMobile');
    const og = btn.innerHTML;
    btn.innerHTML = 'SAVING...';
    btn.disabled = true;

    const fd = new FormData(e.target);
    const id = document.getElementById('mu_id').value;
    const action = id ? 'update' : 'create';

    try {
        const res = await fetch('api/users.php?action=' + action, { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Success', text:data.message, timer:1500, showConfirmButton:false});
            closeAddUserModal();
            loadUsers();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.innerHTML = og;
        btn.disabled = false;
    }
}

async function deleteUserMobile(id) {
    const res = await Swal.fire({
        title: 'Delete User?',
        text: 'This user will be permanently deactivated.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete!'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/users.php?action=delete', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Deleted', text:data.message, timer:1500, showConfirmButton:false});
                loadUsers();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) { console.error(e); }
    }
}

// Bind Form globally since it's at the end of the body
if (document.getElementById('addUserFormMobile')) {
    document.getElementById('addUserFormMobile').addEventListener('submit', saveUserMobile);
}
if (document.getElementById('userSearch')) {
    document.getElementById('userSearch').addEventListener('input', (e) => renderUsers(e.target.value));
}

if (document.getElementById('supplierSearch')) {
    document.getElementById('supplierSearch').addEventListener('input', (e) => {
        if(typeof renderSuppliers === 'function') renderSuppliers(e.target.value);
    });
}
if (document.getElementById('poSearch')) {
    document.getElementById('poSearch').addEventListener('input', (e) => {
        if(typeof renderPurchases === 'function') renderPurchases(e.target.value);
    });
}
if (document.getElementById('mpo_itemSearch')) {
    document.getElementById('mpo_itemSearch').addEventListener('input', (e) => handlePoItemSearch(e.target.value));
}
if (document.getElementById('addSupplierFormMobile')) {
    document.getElementById('addSupplierFormMobile').addEventListener('submit', saveSupplierMobile);
}

async function loadSuppliers() {
    window.suppliersLoaded = true;
    try {
        const res = await fetch('api/suppliers.php?action=list');
        const data = await res.json();
        if (data.success && data.data) {
            window.suppliersCache = data.data;
            renderSuppliers();
        } else {
            document.getElementById('suppliersList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Failed to load suppliers</div>';
        }
    } catch(e) {
        document.getElementById('suppliersList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Error loading suppliers</div>';
    }
}

function renderSuppliers(searchTerm = '') {
    const list = document.getElementById('suppliersList');
    list.innerHTML = '';
    const term = searchTerm.toLowerCase();

    if (!window.suppliersCache || window.suppliersCache.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No suppliers listed</div>';
        return;
    }

    const filtered = window.suppliersCache.filter(s => {
        return (s.name && s.name.toLowerCase().includes(term)) || 
               (s.contact_person && s.contact_person.toLowerCase().includes(term)) ||
               (s.phone && s.phone.toLowerCase().includes(term));
    });

    if (filtered.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No match found</div>';
        return;
    }

    filtered.forEach(s => {
        const sStr = btoa(unescape(encodeURIComponent(JSON.stringify(s))));
        list.innerHTML += `
        <div class="mobile-list-item">
            <div style="display:flex; align-items:center; gap:15px; flex:1;" onclick="viewSupplierMobile(${s.id})">
                <div style="background:rgba(56, 176, 0, 0.1); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; color:var(--success); font-size:16px; font-weight:800;">
                    <i class="fa-solid fa-handshake"></i>
                </div>
                <div>
                    <div style="font-weight:800; font-size:15px; color:#1a1a1a;">${s.name}</div>
                    <div style="font-size:12px; color:#666; font-weight:700;">${s.contact_person || s.phone || 'No Contact Info'}</div>
                </div>
            </div>
            <div style="display:flex; gap:12px;">
                <button onclick="editSupplierMobile('${sStr}')" style="background:none; border:none; color:var(--primary); font-size:17px; padding:5px;"><i class="fa-solid fa-pen-to-square"></i></button>
                <button onclick="deleteSupplierMobile(${s.id})" style="background:none; border:none; color:var(--danger); font-size:17px; padding:5px;"><i class="fa-solid fa-trash-can"></i></button>
            </div>
        </div>`;
    });
}

function openAddSupplierModal() {
    document.getElementById('m_supplierModalTitle').innerText = 'New Supplier';
    document.getElementById('addSupplierFormMobile').reset();
    document.getElementById('ms_id').value = '';
    
    document.querySelector('.mobile-bottom-nav').style.display = 'none';
    
    const m = document.getElementById('addSupplierModal');
    m.style.display = 'flex';
    setTimeout(() => m.classList.add('modal-visible'), 10);
}

function closeAddSupplierModal() {
    const m = document.getElementById('addSupplierModal');
    m.classList.remove('modal-visible');
    setTimeout(() => { 
        m.style.display = 'none'; 
        document.querySelector('.mobile-bottom-nav').style.display = 'flex';
    }, 300);
}

function editSupplierMobile(sStr) {
    const s = JSON.parse(decodeURIComponent(escape(atob(sStr))));
    document.getElementById('m_supplierModalTitle').innerText = 'Edit Supplier';
    document.getElementById('ms_id').value = s.id;
    document.getElementById('ms_name').value = s.name || '';
    document.getElementById('ms_contact').value = s.contact_person || '';
    document.getElementById('ms_phone').value = s.phone || '';
    document.getElementById('ms_email').value = s.email || '';
    document.getElementById('ms_tin').value = s.tin || '';
    document.getElementById('ms_address').value = s.address || '';
    
    document.querySelector('.mobile-bottom-nav').style.display = 'none';
    
    const m = document.getElementById('addSupplierModal');
    m.style.display = 'flex';
    setTimeout(() => m.classList.add('modal-visible'), 10);
}

async function saveSupplierMobile(e) {
    e.preventDefault();
    const btn = document.getElementById('btnSaveSupplierMobile');
    const og = btn.innerHTML;
    btn.innerHTML = 'SAVING...';
    btn.disabled = true;

    const fd = new FormData(e.target);
    const id = document.getElementById('ms_id').value;
    const action = id ? 'update' : 'create';

    try {
        const res = await fetch('api/suppliers.php?action=' + action, { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Success', text:data.message, timer:1500, showConfirmButton:false});
            closeAddSupplierModal();
            loadSuppliers();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.innerHTML = og;
        btn.disabled = false;
    }
}

async function deleteSupplierMobile(id) {
    const res = await Swal.fire({
        title: 'Delete Supplier?',
        text: 'This will permanently remove the supplier record.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete!'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/suppliers.php?action=delete', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Deleted', text:data.message, timer:1500, showConfirmButton:false});
                loadSuppliers();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) {}
    }
}

async function viewSupplierMobile(id) {
    switchView('supplier-details');
    
    document.getElementById('vs_name').innerText = 'Loading...';
    document.getElementById('vs_id_badge').innerText = '...';
    document.getElementById('vs_history_list').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Loading...</div>';

    try {
        const res = await fetch(`api/suppliers.php?action=details&id=${id}`);
        const data = await res.json();
        if (data.success) {
            const s = data.data;
            document.getElementById('vs_name').innerText = s.name;
            document.getElementById('vs_id_badge').innerText = `ID: SUP-${s.id.toString().padStart(4, '0')}`;
            
            document.getElementById('vs_person').innerText = s.contact_person || 'N/A';
            document.getElementById('vs_phone').innerText = s.phone || 'N/A';
            document.getElementById('vs_email').innerText = s.email || 'N/A';
            document.getElementById('vs_tin').innerText = s.tin || 'N/A';
            document.getElementById('vs_address').innerText = s.address || 'N/A';

            let totalSpend = 0;
            const history = s.purchases || [];
            
            if (history.length > 0) {
                totalSpend = history.reduce((sum, p) => sum + parseFloat(p.total_amount), 0);
            }

            const sym = companySettings.company_currency_code || '$';
            document.getElementById('vs_spend').innerText = `${sym}${formatCurrency(totalSpend)}`;
            document.getElementById('vs_po_count').innerText = `${history.length} Purchase Orders`;

            const hList = document.getElementById('vs_history_list');
            hList.innerHTML = '';
            
            if (history.length === 0) {
                hList.innerHTML = '<div class="text-center py-3 text-muted fw-bold">No purchase history</div>';
            } else {
                history.forEach(p => {
                    const statusColor = p.status === 'Received' ? 'var(--success)' : 'var(--warning)';
                    hList.innerHTML += `
                    <div onclick="editPurchaseMobile(${p.id})" style="background:white; padding:15px; border-radius:15px; margin-bottom:10px; display:flex; justify-content:space-between; align-items:center; box-shadow:0 2px 10px rgba(0,0,0,0.02); border:1px solid #f8f9fa;">
                        <div>
                            <div style="font-weight:800; font-size:14px;">PO #${p.id}</div>
                            <div style="font-size:12px; color:#666; font-weight:700;">${p.purchase_date} | <span style="${statusColor === 'var(--success)' ? 'color:var(--success)' : (statusColor === 'var(--warning)' ? 'color:var(--warning)' : 'color:var(--danger)')}">${p.status}</span></div>
                        </div>
                        <div style="font-weight:900; color:var(--primary); font-size:15px;">
                            ${sym}${formatCurrency(p.total_amount)}
                        </div>
                    </div>`;
                });
            }
        }
    } catch (e) {
        switchView('suppliers');
        Swal.fire('Error', 'Could not load details', 'error');
    }
}



async function loadPurchases() {
    window.purchasesLoaded = true;
    try {
        const res = await fetch('api/purchases.php?action=list');
        const data = await res.json();
        if (data.success && data.data) {
            purchasesCache = data.data;
            renderPurchases();
        } else {
            document.getElementById('purchasesList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Failed to load purchases</div>';
        }
    } catch(e) {
        document.getElementById('purchasesList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Error loading purchases</div>';
    }
}

function renderPurchases(searchTerm = '') {
    const list = document.getElementById('purchasesList');
    list.innerHTML = '';
    const sym = companySettings.company_currency_code || '$';
    const term = searchTerm.toLowerCase();

    if (!purchasesCache || purchasesCache.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No purchase orders found</div>';
        return;
    }

    const filtered = purchasesCache.filter(p => {
        return p.id.toString().includes(term) || 
               (p.supplier_name && p.supplier_name.toLowerCase().includes(term)) ||
               (p.status && p.status.toLowerCase().includes(term));
    });

    if (filtered.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No match found</div>';
        return;
    }

    filtered.forEach(p => {
        const statusColor = p.status === 'Received' ? 'var(--success)' : (p.status === 'Cancelled' ? 'var(--danger)' : 'var(--warning)');
        const canEdit = p.status === 'Pending' || p.status === 'Partial';
        const canCancel = p.status !== 'Cancelled' && p.status !== 'Received';
        const canRestore = p.status === 'Cancelled';
        
        list.innerHTML += `
        <div class="mobile-list-item" style="flex-direction:column; align-items:stretch; gap:10px;" onclick="if(event.target.tagName !== 'BUTTON' && event.target.parentElement.tagName !== 'BUTTON') { editPurchaseMobile(${p.id}) }">
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <div style="display:flex; align-items:center; gap:12px;">
                    <div style="background:rgba(244, 162, 97, 0.1); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; color:var(--warning); font-size:16px;">
                        <i class="fa-solid fa-file-invoice-dollar"></i>
                    </div>
                    <div>
                        <div style="font-weight:800; font-size:15px; color:#1a1a1a;">PO #${p.id}</div>
                        <div style="font-size:12px; color:#666; font-weight:700;">${p.supplier_name || 'System'} | ${p.purchase_date}</div>
                    </div>
                </div>
                <div style="text-align:right;">
                    <div style="font-weight:800; color:var(--primary); font-size:16px;">${sym}${formatCurrency(p.total_amount)}</div>
                    <div style="font-size:11px; font-weight:800; color:${statusColor}">${p.status.toUpperCase()}</div>
                </div>
            </div>
            <div style="display:flex; gap:10px; border-top:1px solid #f8f9fa; pt-10px; padding-top:10px;">
                <button onclick="editPurchaseMobile(${p.id})" class="btn btn-sm" style="flex:1; background:rgba(67, 97, 238, 0.05); color:var(--primary); font-weight:700; border-radius:10px; padding:8px;"><i class="fa-solid fa-${canEdit ? 'pen-to-square' : 'eye'} me-1"></i>${canEdit ? 'Manage' : 'Preview'}</button>
                ${canCancel ? `<button onclick="cancelPurchaseMobile(${p.id})" class="btn btn-sm" style="flex:1; background:rgba(230, 57, 70, 0.05); color:var(--danger); font-weight:700; border-radius:10px; padding:8px;"><i class="fa-solid fa-ban me-1"></i>Cancel</button>` : ''}
                ${canRestore ? `<button onclick="restorePurchaseMobile(${p.id})" class="btn btn-sm" style="flex:1; background:rgba(56, 176, 0, 0.05); color:var(--success); font-weight:700; border-radius:10px; padding:8px;"><i class="fa-solid fa-rotate-left me-1"></i>Restore</button>` : ''}
                ${p.status === 'Pending' ? `<button onclick="deletePurchaseMobile(${p.id})" class="btn btn-sm" style="background:rgba(0,0,0,0.05); color:#666; font-weight:700; border-radius:10px; padding:8px; width:40px;"><i class="fa-solid fa-trash-can"></i></button>` : ''}
            </div>
        </div>`;
    });
}

async function openAddPurchaseModal() {
    if (!window.suppliersLoaded) await loadSuppliers();
    
    document.getElementById('m_poModalTitle').innerText = 'New Purchase Order';
    document.getElementById('mpo_id').value = '';
    currentPoItems = [];
    currentPoStatus = 'Pending';
    
    // Populate Suppliers
    const supplierSelect = $('#mpo_supplier');
    supplierSelect.html('<option value="">-- Choose Supplier --</option>');
    if (window.suppliersCache) {
        window.suppliersCache.forEach(s => {
            supplierSelect.append(`<option value="${s.id}">${s.name}</option>`);
        });
    }
    supplierSelect.val('').trigger('change');
    
    renderPoItems();
    switchView('manage-purchase');
    
    // Initialize Select2 on visible element
    if (supplierSelect.data('select2')) supplierSelect.select2('destroy');
    supplierSelect.select2({ 
        width: '100%', 
        placeholder: '-- Choose Supplier --',
        dropdownParent: $('#view-manage-purchase')
    });
    supplierSelect.prop('disabled', false);

    document.getElementById('mpo_itemSearch').parentElement.parentElement.style.display = 'block';
    document.getElementById('btnSavePurchaseMobile').style.display = 'block';
    
    renderPoItems();
    switchView('manage-purchase');
}

function closeAddPurchaseModal() {
    switchView('purchases');
}

async function editPurchaseMobile(id) {
    if (!window.suppliersLoaded) await loadSuppliers();
    try {
        const res = await fetch(`api/purchases.php?action=details&id=${id}`);
        const data = await res.json();
        if (data.success) {
            const po = data.data;
            document.getElementById('m_poModalTitle').innerText = `${po.status === 'Pending' || po.status === 'Partial' ? 'Edit' : 'View'} PO #${po.id}`;
            document.getElementById('mpo_id').value = po.id;
            currentPoStatus = po.status;
            
            // Populate Suppliers & Set Value
            const supplierSelect = $('#mpo_supplier');
            supplierSelect.html('<option value="">-- Choose Supplier --</option>');
            if (window.suppliersCache) {
                window.suppliersCache.forEach(s => {
                    supplierSelect.append(`<option value="${s.id}">${s.name}</option>`);
                });
            }
            currentPoItems = po.items.map(item => ({
                product_id: item.product_id,
                name: item.product_name,
                quantity: parseFloat(item.quantity),
                cost_price: parseFloat(item.cost_price)
            }));
            
            renderPoItems();
            switchView('manage-purchase');

            // Initialize/Refresh Select2 on visible element
            if (supplierSelect.data('select2')) supplierSelect.select2('destroy');
            supplierSelect.select2({ 
                width: '100%', 
                placeholder: '-- Choose Supplier --',
                dropdownParent: $('#view-manage-purchase')
            });
            supplierSelect.val(po.supplier_id).trigger('change');
            
            const isReadOnly = (po.status !== 'Pending' && po.status !== 'Partial');
            supplierSelect.prop('disabled', isReadOnly);

            document.getElementById('mpo_itemSearch').parentElement.parentElement.style.display = (isReadOnly ? 'none' : 'block');
            document.getElementById('btnSavePurchaseMobile').style.display = (isReadOnly ? 'none' : 'block');
        }
    } catch(e) {
        Swal.fire('Error', 'Failed to load PO details', 'error');
    }
}

function handlePoItemSearch(q) {
    const results = document.getElementById('mpo_searchResults');
    if (!q || q.length < 1) {
        results.style.display = 'none';
        return;
    }
    
    const term = q.toLowerCase();
    const filtered = productsCache.filter(p => p.name.toLowerCase().includes(term) || (p.sku && p.sku.toLowerCase().includes(term))).slice(0, 10);
    
    if (filtered.length === 0) {
        results.innerHTML = '<div style="padding:15px; text-align:center; color:#999; font-weight:700;">No items found</div>';
    } else {
        results.innerHTML = filtered.map(p => `
            <div onclick="addPoItem(${p.id}, '${p.name.replace(/'/g, "\\'")}', ${p.cost_price})" style="padding:12px 15px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <div style="font-weight:800; font-size:14px;">${p.name}</div>
                    <div style="font-size:11px; color:#666;">SKU: ${p.sku || 'N/A'}</div>
                </div>
                <div style="font-weight:800; color:var(--primary); font-size:13px;">${companySettings.company_currency_code}${formatCurrency(p.cost_price)}</div>
            </div>
        `).join('');
    }
    results.style.display = 'block';
}

function addPoItem(id, name, cost) {
    const existing = currentPoItems.find(i => i.product_id == id);
    if (existing) {
        existing.quantity += 1;
    } else {
        currentPoItems.push({ product_id: id, name: name, quantity: 1, cost_price: cost });
    }
    
    document.getElementById('mpo_itemSearch').value = '';
    document.getElementById('mpo_searchResults').style.display = 'none';
    renderPoItems();
}

function removePoItem(index) {
    currentPoItems.splice(index, 1);
    renderPoItems();
}

function updatePoItemVal(index, key, val) {
    currentPoItems[index][key] = parseFloat(val) || 0;
    updatePoTotalDisplay();
}

function renderPoItems() {
    const list = document.getElementById('mpo_itemsList');
    list.innerHTML = '';
    const isReadOnly = (currentPoStatus !== 'Pending' && currentPoStatus !== 'Partial');
    
    if (currentPoItems.length === 0) {
        list.innerHTML = `<div style="background:#f8f9fa; border:2px dashed #ddd; border-radius:15px; padding:30px; text-align:center; color:#999; font-weight:700;">${isReadOnly ? 'No items in this order' : 'No items added yet.'}</div>`;
    } else {
        currentPoItems.forEach((item, idx) => {
            list.innerHTML += `
            <div style="background:white; border:1px solid #eee; border-radius:15px; padding:15px; margin-bottom:12px; position:relative;">
                ${isReadOnly ? '' : `<button onclick="removePoItem(${idx})" style="position:absolute; top:10px; right:10px; background:none; border:none; color:var(--danger); font-size:16px;"><i class="fa-solid fa-circle-xmark"></i></button>`}
                <div style="font-weight:800; font-size:14px; ${isReadOnly ? '' : 'margin-bottom:10px; padding-right:25px;'}">${item.name}</div>
                <div style="display:flex; gap:10px; align-items:flex-end; ${isReadOnly ? 'margin-top:10px;' : ''}">
                    <div style="flex:1;">
                        <label style="font-size:10px; font-weight:800; color:#999; display:block; margin-bottom:3px;">QTY</label>
                        <input type="number" ${isReadOnly ? 'readonly disabled' : ''} value="${item.quantity}" oninput="updatePoItemVal(${idx}, 'quantity', this.value)" style="width:100%; padding:8px; border-radius:8px; border:1px solid #ddd; font-weight:800; font-size:14px; background:${isReadOnly ? '#f8fafc' : 'white'};">
                    </div>
                    <div style="flex:1.5;">
                        <label style="font-size:10px; font-weight:800; color:#999; display:block; margin-bottom:3px;">UNIT COST (${companySettings.company_currency_code})</label>
                        <input type="number" step="0.01" ${isReadOnly ? 'readonly disabled' : ''} value="${item.cost_price}" oninput="updatePoItemVal(${idx}, 'cost_price', this.value)" style="width:100%; padding:8px; border-radius:8px; border:1px solid #ddd; font-weight:800; font-size:14px; background:${isReadOnly ? '#f8fafc' : 'white'};">
                    </div>
                    <div style="flex:1; text-align:right;">
                        <label style="font-size:10px; font-weight:800; color:#999; display:block; margin-bottom:3px;">SUBTOTAL</label>
                        <div style="font-weight:900; font-size:14px; color:var(--primary);">${companySettings.company_currency_code}${formatCurrency(item.quantity * item.cost_price)}</div>
                    </div>
                </div>
            </div>`;
        });
    }
    updatePoTotalDisplay();
}

function updatePoTotalDisplay() {
    const total = currentPoItems.reduce((sum, i) => sum + (i.quantity * i.cost_price), 0);
    document.getElementById('mpo_total').innerText = `${companySettings.company_currency_code} ${formatCurrency(total)}`;
}

async function savePurchaseMobile() {
    const supplier_id = $('#mpo_supplier').val();
    if (!supplier_id) {
        Swal.fire('Error', 'Please select a supplier', 'warning');
        return;
    }
    if (currentPoItems.length === 0) {
        Swal.fire('Error', 'Please add at least one item', 'warning');
        return;
    }
    
    const btn = document.getElementById('btnSavePurchaseMobile');
    const og = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = 'SAVING...';
    
    const id = document.getElementById('mpo_id').value;
    const action = id ? 'update' : 'create';
    const total = currentPoItems.reduce((sum, i) => sum + (i.quantity * i.cost_price), 0);
    
    const payload = {
        id: id,
        supplier_id: supplier_id,
        total_amount: total,
        items: currentPoItems
    };
    
    try {
        const res = await fetch('api/purchases.php?action=' + action, {
            method: 'POST',
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Success', text:data.message, timer:1500, showConfirmButton:false});
            switchView('purchases');
            loadPurchases();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch(e) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = og;
    }
}

async function deletePurchaseMobile(id) {
    const res = await Swal.fire({
        title: 'Delete Purchase Order?',
        text: 'This will permanently remove the record and all items.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete!'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/purchases.php?action=delete', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Deleted', text:data.message, timer:1500, showConfirmButton:false});
                loadPurchases();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) {}
    }
}

async function cancelPurchaseMobile(id) {
    const res = await Swal.fire({
        title: 'Cancel Purchase Order?',
        text: 'This will reverse any stock impacts and mark the order as Cancelled.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e63946',
        confirmButtonText: 'Yes, Cancel Order'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/purchases.php?action=reverse', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Cancelled', text:data.message, timer:1500, showConfirmButton:false});
                loadPurchases();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) {}
    }
}

async function restorePurchaseMobile(id) {
    const res = await Swal.fire({
        title: 'Restore Purchase Order?',
        text: 'This will re-add stock for any previously received items and mark the order as Pending/Partial.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: 'var(--success)',
        confirmButtonText: 'Yes, Restore Order'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/purchases.php?action=uncancel', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Restored', text:data.message, timer:1500, showConfirmButton:false});
                loadPurchases();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) {}
    }
}

function populateSettings() {
    document.getElementById('setCompanyName').innerText = companySettings.company_name || 'Not Set';
    document.getElementById('setEmail').innerText = companySettings.company_email || 'Not Set';
    document.getElementById('setPhone').innerText = companySettings.company_phone || 'Not Set';
    document.getElementById('setAddress').innerText = [companySettings.company_address, companySettings.company_city].filter(Boolean).join(' ') || 'Not Set';
}

async function logout() {
    const res = await Swal.fire({
        title: 'Sign Out?',
        text: 'Are you sure you want to exit the backoffice?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e63946',
        confirmButtonText: 'Yes, Sign Out'
    });

    if (res.isConfirmed) {
        await fetch('api/auth.php?action=logout');
        window.location.href = 'login';
    }
}

// --- SETTINGS LOGIC ---
function openSettingsGroup(group) {
    switchView('settings-' + group);
}

function previewLogoMobile(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('logoPreviewMobile').src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

async function populateSettingsMobile() {
    // Already loaded in DOMContentLoaded, but let's refresh just in case
    try {
        const res = await fetch('api/settings.php?action=get');
        const data = await res.json();
        if (data.success && data.data) {
            const s = data.data;
            companySettings = s;
            
            // General
            document.getElementById('set_comp_name').value = s.company_name || '';
            document.getElementById('set_comp_tin').value = s.company_tin || '';
            document.getElementById('set_comp_vrn').value = s.company_vrn || '';
            document.getElementById('set_comp_phone').value = s.company_phone || '';
            document.getElementById('set_comp_email').value = s.company_email || '';
            document.getElementById('set_comp_web').value = s.company_website || '';
            document.getElementById('set_comp_addr').value = s.company_address || '';
            document.getElementById('set_comp_city').value = s.company_city || '';
            document.getElementById('set_comp_country').value = s.company_country || '';
            document.getElementById('set_comp_curr_code').value = s.company_currency_code || 'USD';
            document.getElementById('set_comp_curr_name').value = s.company_currency_name || 'Dollar';
            if (s.company_logo) document.getElementById('logoPreviewMobile').src = s.company_logo;

            // SMTP
            document.getElementById('set_smtp_host').value = s.smtp_host || '';
            document.getElementById('set_smtp_port').value = s.smtp_port || '587';
            document.getElementById('set_smtp_user').value = s.smtp_user || '';
            document.getElementById('set_smtp_pass').value = s.smtp_pass || '';
            document.getElementById('set_smtp_enc').value = s.smtp_encryption || 'tls';
            document.getElementById('set_smtp_from').value = s.smtp_from_email || '';
            document.getElementById('set_smtp_name').value = s.smtp_from_name || '';

            // Inventory
            document.getElementById('set_inv_sku').value = s.sku_template || 'PROD-{MMYYYY}-00000';
            document.getElementById('set_inv_next').value = s.sku_next_number || '1';
            document.getElementById('set_inv_pos_edit').checked = s.pos_allow_price_edit == '1';

            // Receipt
            document.getElementById('set_rec_head').value = s.receipt_header || '';
            document.getElementById('set_rec_foot').value = s.receipt_footer || '';
            document.getElementById('set_rec_tax').value = s.tax_percent || '0';
            document.getElementById('set_rec_logo').value = s.receipt_show_logo || 'yes';
            document.getElementById('set_rec_cust_pos').value = s.receipt_customer_pos || 'top';
            document.getElementById('set_rec_cust_tin').value = s.receipt_show_tin || 'yes';

            // Update View Version
            document.getElementById('curr-ver-mob').innerText = s.system_version || '3.0.0';
        }
    } catch (e) {
        console.error("Error populating settings", e);
    }
}

async function saveSettingsMobile() {
    const btn = event.target;
    const og = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = 'SAVING...';

    const fd = new FormData(document.getElementById('settingsFormMobile'));
    // Handle checkbox
    if (!document.getElementById('set_inv_pos_edit').checked) {
        fd.set('pos_allow_price_edit', '0');
    } else {
        fd.set('pos_allow_price_edit', '1');
    }

    try {
        const res = await fetch('api/settings.php?action=update', {
            method: 'POST',
            body: fd
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire({ title: 'Success', text: 'Settings updated successfully', icon: 'success', toast: true, position: 'top-end', timer: 3000, showConfirmButton: false });
            populateSettingsMobile();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (e) {
        Swal.fire('Error', 'Failed to save settings', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = og;
    }
}

async function testSmtpMobile() {
    const btn = document.getElementById('btnTestSmtpMobile');
    const og = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = 'TESTING...';

    try {
        const fd = new FormData(document.getElementById('settingsFormMobile'));
        const res = await fetch('api/settings.php?action=test_smtp', {
            method: 'POST',
            body: fd
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire('Success', data.message, 'success');
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch(e) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = og;
    }
}

async function checkUpdatesMobile() {
    const btn = document.getElementById('btn-check-updates-mob');
    const og = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = 'CHECKING...';

    try {
        const res = await fetch('api/updater.php?action=check');
        const data = await res.json();
        const statusText = document.getElementById('upd-status-mob');
        const detailsDiv = document.getElementById('upd-details-mob');

        if (data.update_available) {
            statusText.innerHTML = `<span class="text-danger">A new update (${data.latest_version}) is available!</span>`;
            document.getElementById('new-ver-mob').innerText = data.latest_version;
            document.getElementById('new-changelog-mob').innerHTML = data.changelog;
            detailsDiv.style.display = 'block';
            window.latestUpdateInfo = data;
        } else {
            statusText.innerHTML = `<span class="text-success">System is up to date!</span>`;
            detailsDiv.style.display = 'none';
        }
    } catch(e) {
        Swal.fire('Error', 'Update server unavailable', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = og;
    }
}

async function startUpdateMobile() {
    if (!window.latestUpdateInfo) return;

    const confirm = await Swal.fire({
        title: 'Start Update?',
        text: 'System files will be replaced. Ensure you have a backup.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update'
    });

    if (!confirm.isConfirmed) return;

    const btn = document.getElementById('btn-start-update-mob');
    btn.disabled = true;
    btn.innerHTML = 'DOWNLOADING...';

    try {
        const fd = new FormData();
        fd.append('url', window.latestUpdateInfo.download_url);
        fd.append('version', window.latestUpdateInfo.latest_version);

        const dlRes = await fetch('api/updater.php?action=download', { method: 'POST', body: fd });
        const dlData = await dlRes.json();
        if(!dlData.success) throw new Error(dlData.message);

        btn.innerHTML = 'APPLYING...';
        const applyFd = new FormData();
        applyFd.append('zip_path', dlData.zip_path);

        const applyRes = await fetch('api/updater.php?action=apply', { method: 'POST', body: applyFd });
        const applyData = await applyRes.json();
        
        if (applyData.success) {
            await Swal.fire('Update Success', applyData.message, 'success');
            window.location.href = 'finish_update.php';
        } else {
            throw new Error(applyData.message);
        }
    } catch(e) {
        Swal.fire('Failed', e.message, 'error');
        btn.disabled = false;
        btn.innerHTML = 'INSTALL UPDATE NOW';
    }
}

function generateBackupMobile() {
    const btn = document.getElementById('btn-generate-backup-mob');
    const og = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = 'EXPORTING...';

    window.location.href = 'api/backups.php?action=download';
    
    setTimeout(() => {
        btn.innerHTML = og;
        btn.disabled = false;
    }, 3000);
}

// PRODUCT CRUD MOBILE
async function resetProductForm() {
    document.getElementById('m_productPageTitle').innerText = 'New Product';
    document.getElementById('addProductFormMobile').reset();
    document.getElementById('mp_id').value = '';
    await loadProductFormDependencies();
}

async function loadProductFormDependencies() {
    try {
        const [catRes, unitRes] = await Promise.all([
            fetch('api/products.php?action=list_categories'),
            fetch('api/products.php?action=list_units')
        ]);
        
        const cats = await catRes.json();
        const units = await unitRes.json();
        
        const catSelect = document.getElementById('mp_category');
        const unitSelect = document.getElementById('mp_unit');
        
        catSelect.innerHTML = '<option value="">No Category</option>';
        if (cats.success) {
            cats.data.forEach(c => {
                catSelect.innerHTML += `<option value="${c.id}">${c.name}</option>`;
            });
        }
        
        unitSelect.innerHTML = '<option value="">No Unit</option>';
        if (units.success) {
            units.data.forEach(u => {
                unitSelect.innerHTML += `<option value="${u.id}">${u.name}</option>`;
            });
        }
    } catch (e) { console.error("Error loading dependencies", e); }
}

async function editProductMobile(pStr) {
    const p = JSON.parse(decodeURIComponent(escape(atob(pStr))));
    
    switchView('edit-product');
    document.getElementById('m_productPageTitle').innerText = 'Edit Product';
    await loadProductFormDependencies();
    
    document.getElementById('mp_id').value = p.id;
    document.getElementById('mp_name').value = p.name || '';
    
    // Apply formatting to prices on load
    document.getElementById('mp_cost').value = p.cost_price ? parseFloat(p.cost_price).toLocaleString() : '';
    document.getElementById('mp_selling').value = p.selling_price ? parseFloat(p.selling_price).toLocaleString() : '';
    
    document.getElementById('mp_barcode').value = p.barcode || '';
    document.getElementById('mp_sku').value = p.sku || '';
    document.getElementById('mp_category').value = p.category_id || '';

    document.getElementById('mp_unit').value = p.unit_id || '';
    document.getElementById('mp_min_stock').value = p.min_stock_level || 5;
    document.getElementById('mp_track_batches').checked = p.track_batches == 1;
}


async function saveProductMobile(e) {
    if (e) e.preventDefault();
    const btn = document.getElementById('btnSaveProductMobile');
    const og = btn.innerHTML;
    btn.innerHTML = 'SAVING...';
    btn.disabled = true;


    const fd = new FormData(document.getElementById('addProductFormMobile'));
    fd.set('track_batches', document.getElementById('mp_track_batches').checked ? '1' : '0');
    const id = document.getElementById('mp_id').value;

    const action = id ? 'update' : 'create';

    try {
        const res = await fetch('api/products.php?action=' + action, { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Success', text:data.message, timer:1500, showConfirmButton:false});
            switchView('inventory');
            loadInventory();
            loadKPIs();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.innerHTML = og;
        btn.disabled = false;
    }
}

async function deleteProductMobile(id) {
    const res = await Swal.fire({
        title: 'Delete Product?',
        text: 'This will permanently remove the item from inventory.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete!'
    });
    
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/products.php?action=delete', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Deleted', text:data.message, timer:1500, showConfirmButton:false});
                loadInventory();
                loadKPIs();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) { console.error(e); }
    }
}

function startMobileScanner() {
    Swal.fire({
        title: 'Barcode Scanner',
        html: '<div id="mobile-reader" style="width:100%; min-height:250px;"></div>',
        showCancelButton: true,
        cancelButtonText: 'Cancel',
        didOpen: () => {
            const scanner = new Html5QrcodeScanner("mobile-reader", { fps: 10, qrbox: 250 });
            scanner.render((decodedText) => {
                document.getElementById('mp_barcode').value = decodedText;
                scanner.clear();
                Swal.close();
            }, (error) => { /* ignore errors */ });
        },
        willClose: () => {
            // Cleanup would go here if needed
        }
    });
}

// Bind Product Form
if (document.getElementById('addProductFormMobile')) {
    document.getElementById('addProductFormMobile').addEventListener('submit', saveProductMobile);
}

// STOCK CORRECTION MOBILE
function openStockCorrection(pStr) {
    const p = JSON.parse(decodeURIComponent(escape(atob(pStr))));
    switchView('stock-correction');
    
    document.getElementById('sc_id').value = p.id;
    document.getElementById('sc_prod_name').innerText = p.name;
    document.getElementById('sc_current_qty').innerText = p.stock_quantity;
    document.getElementById('sc_qty').value = '';
    document.getElementById('sc_reason').value = '';
    

    // Reset radio to "In"
    document.getElementById('sc_type_add').checked = true;

    // Batch details for tracked products
    const batchFields = document.getElementById('sc_batch_fields');
    if (p.track_batches == 1) {
        batchFields.style.display = 'block';
        document.getElementById('sc_batch_number').required = true;
        document.getElementById('sc_expiry_date').required = true;
    } else {
        batchFields.style.display = 'none';
        document.getElementById('sc_batch_number').required = false;
        document.getElementById('sc_expiry_date').required = false;
    }
}


async function saveStockCorrection(e) {
    if (e) e.preventDefault();
    const btn = document.getElementById('btnSaveStockCorrection');
    const og = btn.innerHTML;
    btn.innerHTML = 'SAVING...';
    btn.disabled = true;

    const fd = new FormData(document.getElementById('stockCorrectionFormMobile'));

    try {
        const res = await fetch('api/inventory.php?action=adjust_stock', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Correction Applied', text:data.message, timer:1500, showConfirmButton:false});
            switchView('inventory');
            loadInventory();
            loadKPIs();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        Swal.fire('Error', 'Connection failed', 'error');
    } finally {
        btn.innerHTML = og;
        btn.disabled = false;
    }
}

if (document.getElementById('stockCorrectionFormMobile')) {
    document.getElementById('stockCorrectionFormMobile').addEventListener('submit', saveStockCorrection);
}

function formatPriceInput(input) {
    let value = input.value.replace(/,/g, '');
    if (!isNaN(value) && value !== '') {
        input.value = parseFloat(value).toLocaleString();
    } else {
        input.value = '';
    }
}

// CATEGORY MANAGEMENT MOBILE
async function loadCategoriesList() {
    window.categoriesLoaded = true;
    try {
        const res = await fetch('api/products.php?action=list_categories');
        const data = await res.json();
        if (data.success && data.data) {
            window.categoriesCache = data.data;
            renderCategoriesList();
        } else {
            document.getElementById('categoriesList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Failed to load categories</div>';
        }
    } catch(e) {
        document.getElementById('categoriesList').innerHTML = '<div class="text-center py-5 text-muted fw-bold">Error loading categories</div>';
    }
}

function renderCategoriesList() {
    const list = document.getElementById('categoriesList');
    list.innerHTML = '';
    
    if (!window.categoriesCache || window.categoriesCache.length === 0) {
        list.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No categories found</div>';
        return;
    }

    window.categoriesCache.forEach(c => {
        const catStr = btoa(unescape(encodeURIComponent(JSON.stringify(c))));
        const item = document.createElement('div');
        item.className = 'mobile-list-item';
        item.innerHTML = `
            <div style="display:flex; align-items:center; gap:15px; flex:1;">
                <div style="background:rgba(255, 159, 64, 0.1); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; color:#ff9f40; font-size:16px; font-weight:800;">
                    <i class="fa-solid fa-tag"></i>
                </div>
                <div>
                    <div style="font-weight:800; font-size:15px; color:#1a1a1a;">${c.name}</div>
                </div>
            </div>
            <div style="display:flex; gap:12px;">
                <button onclick="openCategoryModal('${catStr}')" style="background:none; border:none; color:var(--primary); font-size:17px; padding:5px;"><i class="fa-solid fa-pen-to-square"></i></button>
                <button onclick="deleteCategoryMobile(${c.id})" style="background:none; border:none; color:var(--danger); font-size:17px; padding:5px;"><i class="fa-solid fa-trash-can"></i></button>
            </div>
        `;
        list.appendChild(item);
    });
}

function openCategoryModal(catStr = '') {
    const m = document.getElementById('categoryModal');
    const form = document.getElementById('categoryFormMobile');
    form.reset();
    
    if (catStr) {
        const c = JSON.parse(decodeURIComponent(escape(atob(catStr))));
        document.getElementById('catModalTitle').innerText = 'Edit Category';
        document.getElementById('cat_id').value = c.id;
        document.getElementById('cat_name').value = c.name;
    } else {
        document.getElementById('catModalTitle').innerText = 'New Category';
        document.getElementById('cat_id').value = '';
    }

    m.style.visibility = 'visible';
    m.style.display = 'flex';
}

function closeCategoryModal() {
    const m = document.getElementById('categoryModal');
    m.style.visibility = 'hidden';
    m.style.display = 'none';
}

async function saveCategoryMobile(e) {
    if (e) e.preventDefault();
    const id = document.getElementById('cat_id').value;
    const name = document.getElementById('cat_name').value;
    
    if (!name) return;

    const fd = new FormData();
    if (id) fd.append('id', id);
    fd.append('name', name);

    const action = id ? 'update_category' : 'create_category';

    try {
        const res = await fetch('api/products.php?action=' + action, { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            Swal.fire({icon:'success', title:'Success', text:data.message, timer:1500, showConfirmButton:false});
            closeCategoryModal();
            loadCategoriesList();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (err) {
        Swal.fire('Error', 'Connection failed', 'error');
    }
}

async function deleteCategoryMobile(id) {
    const res = await Swal.fire({
        title: 'Delete Category?',
        text: 'Products in this category will become uncategorized.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete!'
    });
    if (res.isConfirmed) {
        const fd = new FormData();
        fd.append('id', id);
        try {
            const req = await fetch('api/products.php?action=delete_category', { method: 'POST', body: fd });
            const data = await req.json();
            if (data.success) {
                Swal.fire({icon:'success', title:'Deleted', text:data.message, timer:1500, showConfirmButton:false});
                loadCategoriesList();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(e) {}
    }
}

if (document.getElementById('categoryFormMobile')) {
    document.getElementById('categoryFormMobile').addEventListener('submit', saveCategoryMobile);
}





