/* assets/js/mobile-pos.js */

let productsCache = [];
let categoriesCache = [];
let selectedCategoryId = 'all';
let paymentMethod = 'CASH';
let currentShiftId = null;
let userPrintMethod = 'Browser'; // Default

// Queues management (matches desktop behavior)
let queues = JSON.parse(localStorage.getItem('pos_mobile_queues')) || [
    { id: Date.now(), name: 'Sale 1', cart: [], customer: null }
];
let activeQueueIndex = parseInt(localStorage.getItem('pos_mobile_active_queue')) || 0;
if (activeQueueIndex >= queues.length) activeQueueIndex = 0;

let html5QrCode = null;

document.addEventListener('DOMContentLoaded', async () => {
    // Register Service Worker
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js').then(() => console.log("SW Registered"));
    }


    // Initial load
    await checkAuth();
    await checkShiftStatus();
    await loadCategories();
    await loadProducts();
    
    // Resume state
    renderCart();
    updateCustomerDisplay();

    // Binds
    document.getElementById('productSearch').addEventListener('input', handleSearch);
    document.getElementById('customerSearch').addEventListener('input', handleCustomerSearch);
    document.getElementById('addCustomerForm').addEventListener('submit', handleAddCustomer);
    
    // Register form bindings
    bindShiftForm();
    loadMobileSystemSettings();
    initModalBackdrops();
});

function initModalBackdrops() {
    // Unified Modal Backdrop Click Handler
    const modals = [
        { id: 'customerModal', closeFn: closeCustomerModal },
        { id: 'checkoutModal', closeFn: closeCheckout },
        { id: 'ongoingModal', closeFn: closeOngoingModal },
        { id: 'onlineOrdersModal', closeFn: closeOnlineOrders },
        { id: 'quickOrderModal', closeFn: closeQuickOrder },
        { id: 'calculatorModal', closeFn: closeCalculator },
        { id: 'shiftHistoryModal', closeFn: closeShiftHistory },
        { id: 'closeShiftModal', closeFn: closeCloseShiftModal },
        { id: 'returnItemsModal', closeFn: closeReturnModal },
        { id: 'profileModal', closeFn: closeProfileModal },
        { id: 'moreMenuModal', closeFn: closeMoreMenu },
        { id: 'addCustomerModal', closeFn: closeAddCustomerModal }
    ];

    modals.forEach(m => {
        const el = document.getElementById(m.id);
        if (el) {
            el.addEventListener('click', (e) => {
                if (e.target === el) m.closeFn();
            });
            // Ensure content clicks don't bubble out if not already handled
            const content = el.querySelector('.modal-content');
            if (content) {
                content.addEventListener('click', (e) => e.stopPropagation());
            }
        }
    });
}

async function loadMobileSystemSettings() {
    const res = await fetch('api/settings.php?action=get');
    const data = await res.json();
    if (data.success) {
        const symbol = data.data.company_currency_code || 'TSh';
        const el = document.getElementById('shiftCurrencySymbol');
        if (el) el.innerText = symbol;
    }
}

function saveState() {
    localStorage.setItem('pos_mobile_queues', JSON.stringify(queues));
    localStorage.setItem('pos_mobile_active_queue', activeQueueIndex.toString());
}

async function checkAuth() {
    try {
        const response = await fetch('api/auth.php?action=me');
        const data = await response.json();
        if (!data.success || !data.user) {
            window.location.href = 'login';
            return null;
        }

        // Toggle Admin menu option visibility
        const userRole = (data.user.role || '').toLowerCase();
        userPrintMethod = data.user.printing_method || 'Browser';
        
        const adminOpt = document.getElementById('adminMenuOption');
        if (adminOpt) {
            adminOpt.style.display = (userRole === 'admin' || userRole === 'accounts') ? 'flex' : 'none';
        }

        return data.user;
    } catch (e) {
        console.error("Auth check failed", e);
        return null;
    }
}

async function checkShiftStatus() {
    try {
        const res = await fetch('api/shifts.php?action=current&t=' + new Date().getTime());
        const data = await res.json();
        const overlay = document.getElementById('shiftOverlay');
        
        if (data.success && data.shift) {
            currentShiftId = data.shift.id;
            overlay.style.display = 'none';
        } else {
            currentShiftId = null;
            overlay.style.display = 'flex';
        }
    } catch (e) {
        console.error("Shift check failed");
    }
}

async function loadCategories() {
    try {
        const r = await fetch('api/products.php?action=list_categories');
        const data = await r.json();
        if (data.success) {
            categoriesCache = data.data;
            renderCategories();
        }
    } catch (e) { console.error("Load Categories failed", e); }
}

async function loadProducts() {
    try {
        const r = await fetch('api/products.php?action=list');
        const data = await r.json();
        if (data.success) {
            productsCache = data.data;
            renderProducts();
        }
    } catch (e) { console.error("Load Products failed", e); }
}

function renderCategories() {
    const container = document.getElementById('categoryTabs');
    const existingAll = container.querySelector('[data-id="all"]');
    container.innerHTML = '';
    container.appendChild(existingAll);

    existingAll.onclick = () => filterByCategory('all');

    categoriesCache.forEach(cat => {
        const tab = document.createElement('div');
        tab.className = 'category-tab';
        tab.innerText = cat.name;
        tab.dataset.id = cat.id;
        tab.onclick = () => filterByCategory(cat.id);
        container.appendChild(tab);
    });
}

function filterByCategory(id) {
    selectedCategoryId = id;
    document.querySelectorAll('.category-tab').forEach(t => {
        t.classList.toggle('active', t.dataset.id == id);
    });
    renderProducts();
}

function handleSearch(e) {
    const term = e.target.value.toLowerCase();
    renderProducts(term);
}

function renderProducts(searchTerm = '') {
    const grid = document.getElementById('productsGrid');
    grid.innerHTML = '';

    const filtered = productsCache.filter(p => {
        const matchesCategory = selectedCategoryId === 'all' || p.category_id == selectedCategoryId;
        const matchesSearch = p.name.toLowerCase().includes(searchTerm) || p.sku.toLowerCase().includes(searchTerm);
        return matchesCategory && matchesSearch;
    });

    filtered.forEach(p => {
        const item = document.createElement('li');
        item.className = 'list-group-item product-list-item d-flex align-items-center justify-content-between px-3 py-3';
        item.style.borderLeft = 'none';
        item.style.borderRight = 'none';
        item.style.cursor = 'pointer';
        item.onclick = () => addToCart(p);
        item.innerHTML = `
            <div class="fw-bold d-flex align-items-center" style="font-size: 15px; color: #1a1a1a; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; padding-right: 15px;">
                ${p.name}
                ${p.track_batches == 1 ? '<span class="badge bg-info-subtle text-info ms-2" style="font-size: 0.55rem; padding: 2px 5px; border: 0.5px solid rgba(0,0,0,0.05);">BATCH</span>' : ''}
            </div>
            <div class="fw-bold text-success" style="font-size: 16px;">${formatPrice(p.selling_price)}</div>
        `;
        grid.appendChild(item);
    });
}

function addToCart(product) {
    const q = queues[activeQueueIndex];
    const existing = q.cart.find(item => item.id === product.id);
    if (existing) {
        existing.qty++;
    } else {
        q.cart.push({
            id: product.id,
            name: product.name,
            price: parseFloat(product.selling_price),
            qty: 1
        });
    }
    saveState();
    renderCart();
}

function renderCart() {
    const q = queues[activeQueueIndex];
    const container = document.getElementById('cartItems');
    if (!container) return; // Guard
    
    if (!q.cart || q.cart.length === 0) {
        container.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-muted">Cart is empty</td></tr>';
        updateTotal();
        return;
    }

    container.innerHTML = '';
    q.cart.forEach((item, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>
                <span class="item-name-cell">${item.name}</span>
            </td>
            <td>${formatPrice(item.price)}</td>
            <td>
                <div class="qty-control">
                    <div class="btn-qty" onclick="updateQty(${index}, -1)">-</div>
                    <span class="qty-val">${item.qty}</span>
                    <div class="btn-qty" onclick="updateQty(${index}, 1)">+</div>
                </div>
            </td>
            <td class="text-center">
                <i class="fa-solid fa-trash-can btn-delete" onclick="removeItem(${index})"></i>
            </td>
        `;
        container.appendChild(tr);
    });
    updateTotal();
    
    // Auto scroll to bottom of cart
    const cartSection = document.querySelector('.pos-cart-section');
    cartSection.scrollTop = cartSection.scrollHeight;
}

function updateQty(index, delta) {
    const q = queues[activeQueueIndex];
    q.cart[index].qty += delta;
    if (q.cart[index].qty <= 0) {
        q.cart.splice(index, 1);
    }
    saveState();
    renderCart();
}

function removeItem(index) {
    const q = queues[activeQueueIndex];
    q.cart.splice(index, 1);
    saveState();
    renderCart();
}

// Ongoing Sales Management
function openOngoingModal() {
    const modal = document.getElementById('ongoingModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    renderQueues();
}

function closeOngoingModal() {
    const modal = document.getElementById('ongoingModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
    }, 300);
}

function renderQueues() {
    const container = document.getElementById('queuesContainer');
    container.innerHTML = '';

    queues.forEach((q, i) => {
        const isActive = i === activeQueueIndex;
        const total = q.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
        const item = document.createElement('div');
        item.style.background = isActive ? 'rgba(0,100,0,0.05)' : '#f8f9fa';
        item.style.border = isActive ? '2px solid var(--pos-green)' : '1px solid #eee';
        item.style.borderRadius = '15px';
        item.style.padding = '15px';
        item.style.marginBottom = '12px';
        item.style.display = 'flex';
        item.style.justifyContent = 'space-between';
        item.style.alignItems = 'center';
        item.style.cursor = 'pointer';
        item.onclick = () => switchQueue(i);

        item.innerHTML = `
            <div>
                <div style="font-weight:900; color:${isActive ? 'var(--pos-green)' : '#333'}; font-size:16px; margin-bottom:2px;">
                    ${q.customer ? `<i class="fa-solid fa-user-circle me-1 small"></i> ${q.customer.name}` : q.name}
                </div>
                <div style="font-size:12px; color:#64748b; font-weight:700;">
                    ${q.cart.length} Items | Total: ${formatPrice(total)}
                </div>
            </div>
            <div style="display:flex; gap:10px;">
                ${isActive ? '<i class="fa-solid fa-circle-check text-success" style="font-size:20px;"></i>' : ''}
                ${queues.length > 1 ? `<i class="fa-solid fa-circle-xmark text-danger" style="font-size:20px;" onclick="event.stopPropagation(); removeQueue(${i})"></i>` : ''}
            </div>
        `;
        container.appendChild(item);
    });
}

function addNewQueue() {
    const name = `Sale ${queues.length + 1}`;
    queues.push({ id: Date.now(), name: name, cart: [], customer: null });
    activeQueueIndex = queues.length - 1;
    saveState();
    closeOngoingModal();
    renderCart();
    updateCustomerDisplay();
}

function switchQueue(index) {
    activeQueueIndex = index;
    saveState();
    closeOngoingModal();
    renderCart();
    updateCustomerDisplay();
}

function removeQueue(index) {
    if (queues.length <= 1) return;
    queues.splice(index, 1);
    if (activeQueueIndex >= queues.length) activeQueueIndex = queues.length - 1;
    saveState();
    renderQueues();
    renderCart();
    updateCustomerDisplay();
}

// Scanner Management
function startScanner() {
    const view = document.getElementById('scannerView');
    view.style.display = 'flex';
    
    if (!html5QrCode) {
        html5QrCode = new Html5Qrcode("reader", { 
            formatsToSupport: [ 
                Html5QrcodeSupportedFormats.EAN_13, 
                Html5QrcodeSupportedFormats.EAN_8,
                Html5QrcodeSupportedFormats.UPC_A, 
                Html5QrcodeSupportedFormats.UPC_E, 
                Html5QrcodeSupportedFormats.CODE_128,
                Html5QrcodeSupportedFormats.CODE_39
            ],
            verbose: false 
        });
    }
    
    html5QrCode.start(
        { facingMode: "environment" },
        { 
            fps: 30, 
            qrbox: { width: 320, height: 160 },
            aspectRatio: 1.777778, // Pro-wide (16:9) for barcodes
            experimentalFeatures: {
                useBarCodeDetectorIfSupported: true
            }
        },
        onScanSuccess
    ).catch(err => {
        showCustomToast('Camera Access Denied', 'Please allow camera permissions to scan.', 'fa-camera', '#ef4444');
        stopScanner();
    });
}

function stopScanner() {
    const view = document.getElementById('scannerView');
    view.style.display = 'none';
    if (html5QrCode && html5QrCode.isScanning) {
        html5QrCode.stop();
    }
}

function onScanSuccess(decodedText, decodedResult) {
    // Search for product by barcode or SKU
    const product = productsCache.find(p => (p.barcode && p.barcode === decodedText) || (p.sku && p.sku === decodedText));
    if (product) {
        addToCart(product);
        stopScanner();
        showCustomToast('Item Added', product.name, 'fa-cart-plus', '#2ecc71');
    } else {
        // Just show but keep scanning
        console.log("Product not found for: ", decodedText);
    }
}

function openMoreMenu() {
    const modal = document.getElementById('moreMenuModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
}

function closeMoreMenu() {
    const modal = document.getElementById('moreMenuModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
    }, 300);
}

async function logout() {
    if (await showConfirm("Are you sure you want to log out?", "Logout")) {
        const res = await fetch('api/auth.php?action=logout');
        const data = await res.json();
        if (data.success) {
            window.location.href = 'login';
        }
    }
}

// Utility: Custom Mobile Alert/Confirm
function showAlert(message, title = 'Alert', type = 'info') {
    return new Promise(resolve => {
        const modal = document.getElementById('mobileModal');
        const icon = document.getElementById('modalIcon');
        const titleEl = document.getElementById('modalTitle');
        const msgEl = document.getElementById('modalMessage');
        const primaryBtn = document.getElementById('modalPrimaryBtn');
        const secondaryBtn = document.getElementById('modalSecondaryBtn');

        // Set Icon based on type
        icon.innerHTML = type === 'success' ? '✅' : (type === 'error' ? '❌' : 'ℹ️');
        titleEl.innerText = title;
        msgEl.innerText = message;
        
        secondaryBtn.style.display = 'none';
        primaryBtn.innerText = 'OK';
        primaryBtn.onclick = () => {
            modal.classList.remove('show');
            setTimeout(() => { modal.style.display = 'none'; }, 300);
            resolve(true);
        };

        modal.style.display = 'flex';
        setTimeout(() => modal.classList.add('show'), 10);
    });
}

function showConfirm(message, title = 'Confirm') {
    return new Promise(resolve => {
        const modal = document.getElementById('mobileModal');
        const icon = document.getElementById('modalIcon');
        const titleEl = document.getElementById('modalTitle');
        const msgEl = document.getElementById('modalMessage');
        const primaryBtn = document.getElementById('modalPrimaryBtn');
        const secondaryBtn = document.getElementById('modalSecondaryBtn');

        icon.innerHTML = '❓';
        titleEl.innerText = title;
        msgEl.innerText = message;
        
        secondaryBtn.style.display = 'block';
        secondaryBtn.innerText = 'Cancel';
        primaryBtn.innerText = 'Confirm';

        primaryBtn.onclick = () => {
            modal.classList.remove('show');
            setTimeout(() => { modal.style.display = 'none'; }, 300);
            resolve(true);
        };
        secondaryBtn.onclick = () => {
            modal.classList.remove('show');
            setTimeout(() => { modal.style.display = 'none'; }, 300);
            resolve(false);
        };

        modal.style.display = 'flex';
        setTimeout(() => modal.classList.add('show'), 10);
    });
}

async function clearCart() {
    if (await showConfirm("Are you sure you want to clear all items?", "Clear Cart")) {
        queues[activeQueueIndex].cart = [];
        saveState();
        renderCart();
    }
}

function updateTotal() {
    const q = queues[activeQueueIndex];
    if (!q.cart) q.cart = [];
    const total = q.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    document.getElementById('totalAmount').innerText = formatPrice(total);
}

function formatPrice(p) {
    return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    }).format(p);
}

function showOnlineToast() {
    // Remove any existing toast
    const existing = document.getElementById('customToast');
    if (existing) existing.remove();

    const toast = document.createElement('div');
    toast.id = 'customToast';
    toast.innerHTML = `
        <div style="display:flex; align-items:center; gap:12px;">
            <div style="background:rgba(255,255,255,0.15); width:36px; height:36px; border-radius:10px; display:flex; align-items:center; justify-content:center; flex-shrink:0;">
                <i class="fa-solid fa-globe" style="color:#60a5fa; font-size:18px;"></i>
            </div>
            <div>
                <div style="font-weight:800; font-size:14px; color:#fff;">Online Ordering</div>
                <div style="font-size:12px; color:rgba(255,255,255,0.7); font-weight:600;">Coming soon — stay tuned!</div>
            </div>
        </div>
    `;
    Object.assign(toast.style, {
        position: 'fixed',
        top: 'calc(10px + env(safe-area-inset-top, 0px))',
        left: '12px',
        right: '12px',
        padding: '14px 18px',
        background: 'rgba(30, 30, 30, 0.92)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderRadius: '16px',
        zIndex: '9999',
        boxShadow: '0 8px 32px rgba(0,0,0,0.3)',
        border: '1px solid rgba(255,255,255,0.08)',
        transform: 'translateY(-20px)',
        opacity: '0',
        transition: 'all 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
    });
    document.body.appendChild(toast);

    // Animate in
    requestAnimationFrame(() => {
        toast.style.transform = 'translateY(0)';
        toast.style.opacity = '1';
    });

    // Animate out and remove
    setTimeout(() => {
        toast.style.transform = 'translateY(-20px)';
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 350);
    }, 2000);
}

function showCustomToast(title, subtitle, iconClass = 'fa-circle-info', iconColor = '#60a5fa') {
    const existing = document.getElementById('customToast');
    if (existing) existing.remove();

    const toast = document.createElement('div');
    toast.id = 'customToast';
    toast.innerHTML = `
        <div style="display:flex; align-items:center; gap:12px;">
            <div style="background:rgba(255,255,255,0.15); width:36px; height:36px; border-radius:10px; display:flex; align-items:center; justify-content:center; flex-shrink:0;">
                <i class="fa-solid ${iconClass}" style="color:${iconColor}; font-size:18px;"></i>
            </div>
            <div>
                <div style="font-weight:800; font-size:14px; color:#fff;">${title}</div>
                <div style="font-size:12px; color:rgba(255,255,255,0.7); font-weight:600;">${subtitle}</div>
            </div>
        </div>
    `;
    Object.assign(toast.style, {
        position: 'fixed',
        top: 'calc(10px + env(safe-area-inset-top, 0px))',
        left: '12px',
        right: '12px',
        padding: '14px 18px',
        background: 'rgba(30, 30, 30, 0.92)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderRadius: '16px',
        zIndex: '9999',
        boxShadow: '0 8px 32px rgba(0,0,0,0.3)',
        border: '1px solid rgba(255,255,255,0.08)',
        transform: 'translateY(-20px)',
        opacity: '0',
        transition: 'all 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
    });
    document.body.appendChild(toast);

    requestAnimationFrame(() => {
        toast.style.transform = 'translateY(0)';
        toast.style.opacity = '1';
    });

    setTimeout(() => {
        toast.style.transform = 'translateY(-20px)';
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 350);
    }, 2500);
}

// Customer Management
function openCustomerModal() {
    const modal = document.getElementById('customerModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    handleCustomerSearch(); // Initial load
}

function closeCustomerModal() {
    const modal = document.getElementById('customerModal');
    modal.classList.remove('show');
    setTimeout(() => { modal.style.display = 'none'; }, 300);
}

function openAddCustomerModal() {
    const modal = document.getElementById('addCustomerModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
}

function closeAddCustomerModal() {
    const modal = document.getElementById('addCustomerModal');
    modal.classList.remove('show');
    setTimeout(() => { modal.style.display = 'none'; }, 300);
}

async function handleCustomerSearch() {
    const term = document.getElementById('customerSearch').value;
    try {
        const r = await fetch(`api/customers.php?action=list&search=${encodeURIComponent(term)}`);
        const data = await r.json();
        if (data.success) {
            renderCustomerList(data.data);
        }
    } catch (e) { console.error("Customer search failed", e); }
}

function renderCustomerList(customers) {
    const container = document.getElementById('customerList');
    container.innerHTML = '';

    // Walk-in option
    const walkIn = document.createElement('div');
    walkIn.style = 'padding:18px; border-bottom:1px solid #eee; display:flex; align-items:center; cursor:pointer;';
    walkIn.innerHTML = `<i class="fa-solid fa-user-circle me-3" style="font-size:24px; color:#999;"></i> <div><div class="fw-bold">Walk-in Customer</div></div>`;
    walkIn.onclick = () => selectCustomer(null);
    container.appendChild(walkIn);

    customers.forEach(c => {
        const item = document.createElement('div');
        item.style = 'padding:18px 15px; border-bottom:1px solid #f1f3f5; display:flex; align-items:center; justify-content:space-between; cursor:pointer;';
        item.innerHTML = `
            <div style="display:flex; align-items:center;">
                <i class="fa-solid fa-user-circle me-3" style="font-size:26px; color:var(--pos-green);"></i>
                <div class="fw-bold" style="font-size:17px; color:#1a1a1a; letter-spacing:-0.3px;">${c.name}</div>
            </div>
            <div class="fw-bold" style="font-size:14px; color:#666; letter-spacing:0.5px;">${c.mobile || '—'}</div>
        `;
        item.onclick = () => selectCustomer(c);
        container.appendChild(item);
    });
}

function selectCustomer(customer) {
    queues[activeQueueIndex].customer = customer;
    saveState();
    updateCustomerDisplay();
    closeCustomerModal();
}

function updateCustomerDisplay() {
    const q = queues[activeQueueIndex];
    const customer = q.customer;
    const display = document.getElementById('selectedCustomer');
    if (customer) {
        display.innerHTML = `<i class="fa-solid fa-user-circle me-1"></i> ${customer.name}`;
    } else {
        display.innerHTML = `<i class="fa-solid fa-user-circle me-1"></i> Walk-in Customer`;
    }
}


async function handleAddCustomer(e) {
    e.preventDefault();
    const fd = new FormData(e.target);
    try {
        const r = await fetch('api/customers.php?action=add', { method: 'POST', body: fd });
        const data = await r.json();
        if (data.success) {
            showAlert("Customer registered successfully!", "Success", "success");
            selectCustomer({ id: data.id, name: fd.get('name'), mobile: fd.get('mobile') });
            closeAddCustomerModal();
            closeCustomerModal();
        } else {
            showAlert(data.message, "Error", "error");
        }
    } catch (e) {
        showAlert("Failed to register customer", "Error", "error");
    }
}

// Checkout Logic
function openCheckout() {
    const q = queues[activeQueueIndex];
    if (q.cart.length === 0) {
        showCustomToast('Empty Cart', 'Add items before checkout', 'fa-cart-shopping', '#f1c40f');
        return;
    }
    const modal = document.getElementById('checkoutModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    
    const total = q.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    document.getElementById('finalTotal').value = formatPrice(total);

    // Reset fields
    document.getElementById('amountTendered').value = '';
    document.getElementById('changeDue').innerText = '0';
}

function closeCheckout() {
    const modal = document.getElementById('checkoutModal');
    modal.classList.remove('show');
    setTimeout(() => { modal.style.display = 'none'; }, 300);
}

function setPaymentMethod(method) {
    paymentMethod = method;
    document.querySelectorAll('.btn-payment').forEach(btn => {
        btn.classList.toggle('active', btn.getAttribute('data-method') === method);
    });

    if (method !== 'CASH') {
        const totalRaw = document.getElementById('finalTotal').value.replace(/,/g, '');
        document.getElementById('amountTendered').value = parseFloat(totalRaw).toLocaleString();
        calculateChange();
    }
}

async function submitOrder() {
    const q = queues[activeQueueIndex];
    const total = q.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    const amountTendered = parseFloat(document.getElementById('amountTendered').value.replace(/,/g, '')) || total;

    if (!currentShiftId) {
        showAlert("No direct shift active. Please open a shift first.", "Action Required", "warning");
        return;
    }
    
    const orderData = {
        shift_id: currentShiftId,
        items: q.cart.map(i => ({ id: i.id, quantity: i.qty, price: i.price, name: i.name })),
        tax: 0,
        discount: 0,
        total_amount: total,
        amount_paid: amountTendered,
        payment_method: paymentMethod,
        customer_id: q.customer ? q.customer.id : null
    };

    try {
        const r = await fetch('api/sales.php?action=checkout', {
            method: 'POST',
            body: JSON.stringify(orderData)
        });
        const data = await r.json();
        if (data.success) {
            const saleId = data.sale_id;
            
            // Handle printing based on user preference
            if (userPrintMethod === 'Browser') {
                // Fetch full sale data for browser-based (iframe) printing
                const saleRes = await fetch(`api/sales.php?action=receipt&id=${saleId}`);
                const saleData = await saleRes.json();
                if (saleData.success) {
                    await printThermal(saleData.data);
                }
            } else if (userPrintMethod === 'MobilePOS' && data.print_file) {
                // Silent auto-trigger try for Android (RawBT)
                if (/Android/i.test(navigator.userAgent)) {
                    const baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
                    window.location.href = `rawbt:${baseUrl}receipts/${data.print_file}`;
                }
            }
            // If LocalService or MobilePOS, the server already enqueued it in sales.php logic!
            // No need to call printThermal() client-side, which prevents the popup/iPhone dialog.

            // Immediately reset terminal for next sale
            q.cart = [];
            q.customer = null;
            saveState();
            renderCart();
            updateCustomerDisplay();
            closeCheckout();
            
            // Show Success UI
            if (userPrintMethod === 'MobilePOS' && data.print_file) {
                const baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1);
                const fileUrl = `${baseUrl}receipts/${data.print_file}`;
                
                Swal.fire({
                    icon: 'success',
                    title: 'Sale Complete!',
                    html: `
                        <p class="mb-4">Order #<b>${saleId}</b> registered successfully.</p>
                        <hr>
                        <div class="row g-2">
                             <div class="col-12" id="androidPrintBtn" style="display:none">
                                <a href="rawbt:${fileUrl}" class="btn btn-primary btn-lg w-100 py-3 mb-2 fw-bold shadow-sm d-block text-white text-decoration-none">
                                    <i class="fa-solid fa-print me-2"></i>ANDROID (RAWBT)
                                </a>
                             </div>
                             <div class="col-12">
                                <button id="btnSharePrint" class="btn btn-outline-dark btn-lg w-100 py-3 fw-bold shadow-sm d-block text-decoration-none">
                                    <i class="fa-solid fa-share-nodes me-2"></i>IPHONE / SHARE TO APP
                                </button>
                             </div>
                             <div class="col-12 mt-4 text-center">
                                <a href="${fileUrl}" target="_blank" class="small text-muted text-decoration-underline">Manual View (Text)</a>
                             </div>
                             <div class="col-12 mt-3">
                                <button class="btn btn-secondary w-100 py-2 fw-bold" onclick="Swal.close()">DONE / NEW SALE</button>
                             </div>
                        </div>
                    `,
                    showConfirmButton: false,
                    allowOutsideClick: false,
                    position: 'center',
                    backdrop: `rgba(0,0,123,0.4)`,
                    didOpen: () => {
                        const isAndroid = /Android/i.test(navigator.userAgent);
                        if (isAndroid) {
                            document.getElementById('androidPrintBtn').style.display = 'block';
                        }
                        
                        const shareBtn = document.getElementById('btnSharePrint');
                        shareBtn.addEventListener('click', async () => {
                            if (navigator.share && window.isSecureContext) {
                                try {
                                    await navigator.share({
                                        title: `Sale Receipt #${saleId}`,
                                        text: `Receipt for Sale #${saleId}`,
                                        url: fileUrl
                                    });
                                } catch (err) {
                                    // Fallback to direct open if share fails or is cancelled
                                    window.open(fileUrl, '_blank');
                                }
                            } else {
                                window.open(fileUrl, '_blank');
                            }
                        });
                    }
                });
            } else {
                showCustomToast('Sale Complete', `Receipt #${saleId} registered`, 'fa-circle-check', '#27ae60');
            }
        } else {
            showAlert(data.message, "Order Failed", "error");
        }
    } catch (e) {
        showAlert("Server communication error. Please try again.", "Error", "error");
    }
}

async function openShift(e) {
    if (e) e.preventDefault();
    const btn = document.querySelector('#openShiftForm button');
    btn.disabled = true;
    btn.innerText = 'Opening...';

    const fd = new FormData(document.getElementById('openShiftForm'));
    fd.append('terminal_name', 'Mobile Handheld');

    try {
        const res = await fetch('api/shifts.php?action=open', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            await checkShiftStatus();
        } else {
            showAlert(data.message, "Error", "error");
        }
    } catch (e) {
        showAlert("Failed to connect to server", "Error", "error");
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.innerText = 'START SHIFT';
        }
    }
}

// Ensure form is bound once DOM is ready (called from main listener)
function bindShiftForm() {
    const f = document.getElementById('openShiftForm');
    if (f) f.onsubmit = openShift;

    const input = document.getElementById('mobileOpeningBalance');
    const hidden = document.getElementById('mobileOpeningBalanceValue');
    
    if (input) {
        input.addEventListener('input', (e) => {
            let val = e.target.value.replace(/[^0-9]/g, '');
            if (val) {
                hidden.value = val;
                input.value = parseInt(val).toLocaleString('en-US');
            } else {
                hidden.value = '0';
                input.value = '';
            }
        });
    }
}

async function printThermal(sale, customTitle = "SALES RECEIPT") {
    // Load settings first (ensure we have latest TIN, VRN, etc.)
    const sRes = await fetch('api/settings.php?action=get');
    const sData = await sRes.json();
    const settings = sData.success ? sData.data : {};
    const symbol = settings.company_currency_code || '$';

    // Calculate Tax Breakdown
    const taxRate = parseFloat(settings.tax_percent || 0);
    const totalVal = parseFloat(sale.total_amount);
    const taxVal = (totalVal * taxRate) / (100 + taxRate); // Inclusive
    const subtotalVal = totalVal - taxVal;

    const html = `
        <div style="font-family: 'Courier New', Courier, monospace; width: 280px; margin: 0 auto; padding: 10px; font-size: 13px; line-height: 1.3; color: #000;">
            <div style="text-align: center; font-weight: 800; font-size: 18px; margin-bottom: 5px;">${(settings.company_name || 'JUSTSALE').toUpperCase()}</div>
            
            <div style="text-align: center; font-size: 11px;">
                ${settings.company_address ? `<div>${settings.company_address}</div>` : ''}
                ${settings.company_city ? `<div>${settings.company_city}</div>` : ''}
                ${settings.company_phone ? `<div>Tel: ${settings.company_phone}</div>` : ''}
                ${settings.company_email ? `<div>${settings.company_email}</div>` : ''}
                
                <div style="margin-top: 5px; font-weight: bold;">
                    ${settings.company_tin ? `TIN: ${settings.company_tin} ` : ''}
                    ${settings.company_vrn ? `VRN: ${settings.company_vrn}` : ''}
                </div>
            </div>

            <div style="text-align: center; margin: 10px 0; font-weight: 800; border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 5px 0;">
                ${customTitle}
            </div>

            <div style="font-size: 11px; margin-bottom: 10px;">
                ID: #${sale.id}<br>
                Date: ${sale.sale_date}<br>
                Cashier: ${sale.username}
            </div>

            ${sale.customer_name ? `
            <div style="border: 1px solid #000; padding: 5px; margin-bottom: 10px;">
                <div style="font-weight: bold;">CUSTOMER: ${sale.customer_name.toUpperCase()}</div>
                ${sale.customer_tin ? `<div style="font-size: 11px;">TIN: ${sale.customer_tin}</div>` : ''}
            </div>
            ` : ''}

            <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                <thead>
                    <tr style="border-bottom: 1px solid #000;">
                        <th style="text-align: left; padding: 4px 0;">Item</th>
                        <th style="text-align: center;">Qty</th>
                        <th style="text-align: right;">Total</th>
                    </tr>
                </thead>
                <tbody>
                    ${sale.items.map(i => `
                        <tr>
                            <td style="padding: 4px 0; vertical-align: top;">${i.name}</td>
                            <td style="text-align: center; vertical-align: top;">${i.quantity}</td>
                            <td style="text-align: right; vertical-align: top;">${parseFloat(i.subtotal).toFixed(0)}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>

            <div style="border-top: 1px solid #000; margin-top: 10px; padding-top: 8px;">
                ${taxRate > 0 ? `
                    <div style="display: flex; justify-content: space-between; font-size: 11px;">
                        <span>Subtotal (Excl. Tax)</span>
                        <span>${formatPrice(subtotalVal)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 5px;">
                        <span>VAT / Tax (${taxRate}%)</span>
                        <span>${formatPrice(taxVal)}</span>
                    </div>
                ` : ''}
                
                <div style="display: flex; justify-content: space-between; font-weight: 900; font-size: 18px;">
                    <span>TOTAL</span>
                    <span>${symbol} ${formatPrice(totalVal)}</span>
                </div>
            </div>

            <div style="margin-top: 10px; font-size: 11px;">
                Method: ${sale.payment_method}<br>
                Paid: ${symbol} ${formatPrice(sale.amount_paid)}<br>
                Change: ${symbol} ${formatPrice(sale.change_amount)}
            </div>

            <div style="text-align: center; margin-top: 20px; font-size: 11px; font-style: italic;">
                ${settings.receipt_footer ? `<div>${settings.receipt_footer}</div>` : ''}
                Thank you for your visit!
            </div>
            
            <div style="margin-top: 30px; text-align: center;">.</div>
        </div>
    `;

    let printIframe = document.getElementById('silentPrintIframe');
    if (!printIframe) {
        printIframe = document.createElement('iframe');
        printIframe.id = 'silentPrintIframe';
        printIframe.style.display = 'none';
        document.body.appendChild(printIframe);
    }

    const doc = printIframe.contentWindow.document;
    doc.open();
    doc.write(`<html><head><style>@media print { body { margin: 0; } }</style></head><body>${html}</body></html>`);
    doc.close();

    // Trigger print after a short delay to ensure content is ready, 
    // but close enough to the user interaction to be allowed.
    setTimeout(() => {
        printIframe.contentWindow.focus();
        printIframe.contentWindow.print();
    }, 250);
}

// PREMIUM CALCULATOR LOGIC
let calcCurrentVal = '0';
let calcHistoryVal = '';
let calcPendingOp = null;
let calcPrevVal = null;
let calcNextReset = false;

function openCalculator() {
    const modal = document.getElementById('calculatorModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    calcClear();
}

function closeCalculator() {
    const modal = document.getElementById('calculatorModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
    }, 300);
}

function formatCalcNum(str) {
    if (!str || str === 'ERR' || str === '&nbsp;') return str;
    // Check if it's an expression or a single number
    if (str.includes(' ')) {
        // Handle history string like "1,000 + 4,000 = 5,000"
        return str.split(' ').map(part => {
            if (!isNaN(parseFloat(part.replace(/,/g, '')))) {
                const innerParts = part.split('.');
                innerParts[0] = innerParts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                return innerParts.join('.');
            }
            return part;
        }).join(' ');
    }
    // Handle single number
    const parts = str.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join('.');
}

function updateCalcDisplay() {
    document.getElementById('calcMain').innerText = formatCalcNum(calcCurrentVal);
    document.getElementById('calcHistory').innerHTML = formatCalcNum(calcHistoryVal) || '&nbsp;';
}

function calcNum(n) {
    if (calcNextReset) {
        calcCurrentVal = n;
        calcNextReset = false;
        if (!calcPendingOp) calcHistoryVal = ''; // Start fresh if no operator
    } else {
        if (calcCurrentVal === '0' && n !== '.') {
            calcCurrentVal = n;
        } else {
            calcCurrentVal += n;
        }
    }
    updateCalcDisplay();
}

function calcOp(op) {
    if (calcPendingOp && !calcNextReset) {
        calcEqual();
    }
    calcPrevVal = calcCurrentVal;
    calcPendingOp = op;
    calcHistoryVal = `${calcPrevVal} ${op} `;
    calcNextReset = true;
    updateCalcDisplay();
}

function calcPercent() {
    const oldVal = calcCurrentVal;
    calcCurrentVal = (parseFloat(calcCurrentVal) / 100).toString();
    calcHistoryVal = `${oldVal}% = ${calcCurrentVal}`;
    updateCalcDisplay();
}

function calcClear() {
    calcCurrentVal = '0';
    calcHistoryVal = '';
    calcPendingOp = null;
    calcPrevVal = null;
    calcNextReset = false;
    updateCalcDisplay();
}

function calcBackshot() {
    if (calcNextReset) return;
    if (calcCurrentVal.length > 1) {
        calcCurrentVal = calcCurrentVal.slice(0, -1);
    } else {
        calcCurrentVal = '0';
    }
    updateCalcDisplay();
}

function calcEqual() {
    if (!calcPendingOp || !calcPrevVal) return;
    
    const a = parseFloat(calcPrevVal);
    const b = parseFloat(calcCurrentVal);
    let res = 0;
    
    switch(calcPendingOp) {
        case '+': res = a + b; break;
        case '-': res = a - b; break;
        case '*': res = a * b; break;
        case '/': res = b !== 0 ? a / b : 'ERR'; break;
    }
    
    calcHistoryVal = `${a} ${calcPendingOp} ${b} = ${res}`;
    calcCurrentVal = res.toString();
    calcPendingOp = null;
    calcNextReset = true;
    updateCalcDisplay();
}

// ONLINE ORDERS
function openOnlineOrders() {
    const modal = document.getElementById('onlineOrdersModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
}

function closeOnlineOrders() {
    const modal = document.getElementById('onlineOrdersModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
    }, 300);
}

// QUICK ORDER
function openQuickOrder() {
    const modal = document.getElementById('quickOrderModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    document.getElementById('quickOrderForm').reset();
}

function closeQuickOrder() {
    const modal = document.getElementById('quickOrderModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
    }, 300);
}

function addQuickItem(e) {
    e.preventDefault();
    const name = document.getElementById('quickName').value;
    const priceRaw = document.getElementById('quickPrice').value.replace(/,/g, '');
    const price = parseFloat(priceRaw);
    
    if (isNaN(price) || price <= 0) {
        showCustomToast('Invalid Price', 'Please enter a valid amount', 'fa-circle-xmark', '#e74c3c');
        return;
    }

    const q = queues[activeQueueIndex];
    q.cart.push({
        id: 'QUICK-' + Date.now(),
        name: name,
        price: price,
        qty: 1
    });
    
    saveState();
    renderCart();
    closeQuickOrder();
    showCustomToast('Quick Item Added', name, 'fa-cart-plus', '#2ecc71');
}

// Formatting & Calculations
function formatQuickPrice(input) {
    let val = input.value.replace(/,/g, '');
    if (!isNaN(val) && val.length > 0) {
        input.value = parseFloat(val).toLocaleString();
    }
}

function calculateChange() {
    const totalRaw = document.getElementById('finalTotal').value.replace(/,/g, '');
    const tenderedRaw = document.getElementById('amountTendered').value.replace(/,/g, '');
    
    const total = parseFloat(totalRaw) || 0;
    const tendered = parseFloat(tenderedRaw) || 0;

    // Apply formatting to tendered input
    if (tenderedRaw.length > 0) {
        document.getElementById('amountTendered').value = parseFloat(tenderedRaw).toLocaleString();
    }

    const change = tendered - total;
    document.getElementById('changeDue').innerText = change > 0 ? change.toLocaleString() : '0';
    document.getElementById('changeDue').style.color = change >= 0 ? '#2ecc71' : '#e74c3c';
}

async function openShiftHistory() {
    if (!currentShiftId) {
        showCustomToast('No Active Shift', 'Please open a shift first.', 'fa-triangle-exclamation', '#f1c40f');
        return;
    }

    const modal = document.getElementById('shiftHistoryModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    closeMoreMenu();

    try {
        const res = await fetch(`api/sales.php?action=list_shift_sales&shift_id=${currentShiftId}`);
        const data = await res.json();
        if (data.success) {
            renderShiftSales(data.data);
            const opening = parseFloat(data.opening_balance) || 0;
            const cash = parseFloat(data.cash_total) || 0;
            const mobile = parseFloat(data.mobile_total) || 0;
            const card = parseFloat(data.card_total) || 0;

            document.getElementById('shiftOpeningCash').innerText = formatPrice(opening);
            document.getElementById('shiftCashTotal').innerText = formatPrice(cash);
            document.getElementById('shiftMobileTotal').innerText = formatPrice(mobile);
            document.getElementById('shiftCardTotal').innerText = formatPrice(card);
            document.getElementById('shiftGrandTotal').innerText = formatPrice(cash + mobile + card);
        }
    } catch (e) {
        console.error("Failed to load shift sales", e);
    }
}

function closeShiftHistory(reopenOptions = true) {
    const modal = document.getElementById('shiftHistoryModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
        if (reopenOptions) openMoreMenu();
    }, 300);
}

function renderShiftSales(sales) {
    const container = document.getElementById('shiftSalesContainer');
    if (!sales || sales.length === 0) {
        container.innerHTML = '<div class="text-center py-5 text-muted fw-bold">No sales recorded in this shift.</div>';
        return;
    }

    container.innerHTML = '';
    sales.forEach(s => {
        const item = document.createElement('div');
        item.style = 'padding:18px; border-bottom:1px solid #f1f3f5;';
        
        const dateObj = new Date(s.sale_date);
        const timeStr = dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        
        const isPartiallyRefunded = s.total_refunded > 0;
        const hasPendingCN = s.pending_cn_id !== null;

        item.innerHTML = `
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <div class="fw-bold" style="font-size:15px; color:#1a1a1a;">Receipt #${s.id} <span style="font-size:11px; color:#94a3b8; font-weight:600; margin-left:5px;">${timeStr}</span></div>
                    <div style="font-size:12px; color:#64748b; font-weight:700;">${s.customer_name || 'Walk-in Customer'} • ${s.payment_method}</div>
                </div>
                <div class="text-end">
                    <div class="fw-black text-primary" style="font-weight:900; font-size:16px;">${formatPrice(s.total_amount)}</div>
                    ${isPartiallyRefunded ? `<div style="font-size:10px; color:#ef4444; font-weight:700;">Refunded: -${formatPrice(s.total_refunded)}</div>` : ''}
                </div>
            </div>
            <div style="margin-top:12px; display:flex; gap:10px;">
                <button onclick="reprintSale(${s.id})" class="btn" style="flex:1; padding:10px; border-radius:12px; border:2px solid #e2e8f0; background:#f8fafc; font-size:11px; font-weight:800; color:#1e293b; display:flex; align-items:center; justify-content:center; gap:5px;">
                    <i class="fa-solid fa-print"></i> REPRINT
                </button>
                <button onclick="openReturnModal(${s.id})" class="btn" style="flex:1; padding:10px; border-radius:12px; border:1px solid #e2e8f0; background:#fff; font-size:11px; font-weight:800; color:#64748b; display:flex; align-items:center; justify-content:center; gap:5px;" ${(hasPendingCN || s.total_refunded >= s.total_amount) ? 'disabled' : ''}>
                    <i class="fa-solid fa-rotate-left"></i> ${hasPendingCN ? 'PENDING' : 'RETURN'}
                </button>
            </div>
        `;
        container.appendChild(item);
    });
}

async function loadShiftSummary() {
    try {
        const res = await fetch(`api/shifts.php?action=current&t=${new Date().getTime()}`);
        const data = await res.json();
        if (data.success && data.shift) {
            const shift = data.shift;
            document.getElementById('closeOpeningCash').innerText = formatPrice(shift.opening_balance || 0);
            document.getElementById('closeCashSales').innerText = "+ " + formatPrice(shift.total_cash_sales || 0);
            document.getElementById('closeMobileSales').innerText = "+ " + formatPrice(shift.total_mobile_sales || 0);
            document.getElementById('closeCardSales').innerText = "+ " + formatPrice(shift.total_card_sales || 0);
            document.getElementById('closeExpectedCash').innerText = formatPrice(shift.expected_cash || 0);
            
            // Default actual to expected
            const input = document.getElementById('closingBalanceInput');
            input.value = parseFloat(shift.expected_cash || 0).toLocaleString();
        }
    } catch (e) {
        console.error("Failed to load shift details", e);
    }
}

async function openCloseShiftModal() {
    if (!currentShiftId) {
        showCustomToast('No Active Shift', 'Please open a shift first.', 'fa-triangle-exclamation', '#f1c40f');
        return;
    }

    const modal = document.getElementById('closeShiftModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
    closeMoreMenu();
    loadShiftSummary();
}

function closeCloseShiftModal(reopenOptions = true) {
    const modal = document.getElementById('closeShiftModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
        if (reopenOptions) openMoreMenu();
    }, 300);
}

function formatClosingBalance(input) {
    let val = input.value.replace(/[^0-9]/g, '');
    if (val) {
        input.value = parseInt(val).toLocaleString('en-US');
    } else {
        input.value = '';
    }
}

async function submitCloseShift(e) {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    const balanceRaw = document.getElementById('closingBalanceInput').value.replace(/,/g, '');
    const balance = parseFloat(balanceRaw) || 0;

    if (await showConfirm(`End shift with ${formatPrice(balance)} in drawer?`, "End Shift")) {
        btn.disabled = true;
        btn.innerText = 'Closing...';

        try {
            const fd = new FormData();
            fd.append('closing_balance', balance);
            
            const res = await fetch('api/shifts.php?action=close', { method: 'POST', body: fd });
            const data = await res.json();
            
            if (data.success) {
                closeCloseShiftModal(false); // Do not reopen options on success
                await checkShiftStatus();
                showAlert("Register closed successfully. Have a great day!", "Shift Ended", "success");
            } else {
                showAlert(data.message, "Error", "error");
            }
        } catch (e) {
            showAlert("Connection error. Shift not closed.", "Error", "error");
        } finally {
            btn.disabled = false;
            btn.innerText = 'CLOSE REGISTER';
        }
    }
}

// Global variable to hold sale being returned
let currentReturnSale = null;

async function openReturnModal(saleId) {
    try {
        const res = await fetch(`api/sales.php?action=receipt&id=${saleId}`);
        const data = await res.json();
        if (data.success) {
            currentReturnSale = data.data;
            document.getElementById('returnSaleRef').innerText = `Receipt #${saleId}`;
            document.getElementById('refundTotal').innerText = formatPrice(0);
            document.getElementById('returnReason').value = '';
            renderReturnItems(currentReturnSale.items);
            
            const modal = document.getElementById('returnItemsModal');
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
            
            closeShiftHistory(false); // Hide but don't reopen more options
        }
    } catch (e) {
        console.error("Failed to load sale for return", e);
    }
}

function closeReturnModal() {
    const modal = document.getElementById('returnItemsModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
        openShiftHistory();
    }, 300);
}

function renderReturnItems(items) {
    const container = document.getElementById('returnItemsContainer');
    container.innerHTML = '';
    
    items.forEach(item => {
        const price = parseFloat(item.price) || 0;
        const maxQty = parseInt(item.quantity) - (parseInt(item.already_refunded || 0) + parseInt(item.pending_refund || 0));
        
        if (maxQty <= 0) return;

        const div = document.createElement('div');
        div.style = 'background: #fff; border: 1px solid #e2e8f0; border-radius: 20px; padding: 20px; margin-bottom: 12px;';
        div.innerHTML = `
            <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:15px;">
                <div style="flex:1; padding-right:15px;">
                    <div class="fw-bold" style="font-size:15px; color:#1a1a1a;">${item.name}</div>
                    <div style="font-size:12px; color:#64748b; font-weight:600;">Purchased: ${item.quantity} • Unit: ${formatPrice(price)}</div>
                </div>
                <div class="text-end">
                    <div class="fw-black text-dark" style="font-weight:900;">Max Return: ${maxQty}</div>
                </div>
            </div>
            <div style="display:flex; align-items:center; gap:15px;">
                <div style="flex:1;">
                    <label style="font-size:10px; color:#94a3b8; font-weight:800; display:block; margin-bottom:5px;">QTY TO RETURN</label>
                    <div style="display:flex; align-items:center; background:#f8fafc; border-radius:12px; padding:5px; border:1px solid #e2e8f0;">
                        <button onclick="decrementReturn(${item.id})" class="btn" style="width:36px; height:36px; border-radius:8px; background:white; border:1px solid #e2e8f0; display:flex; align-items:center; justify-content:center; color:#64748b;"><i class="fa-solid fa-minus"></i></button>
                        <input type="number" id="returnQty_${item.id}" value="0" min="0" max="${maxQty}" readonly style="flex:1; background:transparent; border:none; text-align:center; font-weight:900; font-size:16px;">
                        <button onclick="incrementReturn(${item.id}, ${maxQty})" class="btn" style="width:36px; height:36px; border-radius:8px; background:white; border:1px solid #e2e8f0; display:flex; align-items:center; justify-content:center; color:#64748b;"><i class="fa-solid fa-plus"></i></button>
                    </div>
                </div>
                <div style="width:120px;">
                    <label style="font-size:10px; color:#94a3b8; font-weight:800; display:block; margin-bottom:5px;">REFUND VAL</label>
                    <div id="refundVal_${item.id}" style="font-weight:900; font-size:16px; color:#ef4444;">0</div>
                </div>
            </div>
        `;
        container.appendChild(div);
    });
}

function incrementReturn(itemId, max) {
    const input = document.getElementById(`returnQty_${itemId}`);
    let val = parseInt(input.value);
    if (val < max) {
        input.value = val + 1;
        updateReturnItemTotal(itemId);
    }
}

function decrementReturn(itemId) {
    const input = document.getElementById(`returnQty_${itemId}`);
    let val = parseInt(input.value);
    if (val > 0) {
        input.value = val - 1;
        updateReturnItemTotal(itemId);
    }
}

function updateReturnItemTotal(itemId) {
    const item = currentReturnSale.items.find(i => i.id == itemId);
    const input = document.getElementById(`returnQty_${itemId}`);
    if (item && input) {
        const qty = parseInt(input.value) || 0;
        const price = parseFloat(item.price) || 0;
        const total = qty * price;
        document.getElementById(`refundVal_${itemId}`).innerText = formatPrice(total);
    }
    calculateReturnGrandTotal();
}

function calculateReturnGrandTotal() {
    let grand = 0;
    currentReturnSale.items.forEach(item => {
        const input = document.getElementById(`returnQty_${item.id}`);
        if (input) {
            const qty = parseInt(input.value) || 0;
            const price = parseFloat(item.price) || 0;
            grand += qty * price;
        }
    });
    document.getElementById('refundTotal').innerText = formatPrice(grand);
}

async function submitReturnRequest() {
    const returnItems = [];
    currentReturnSale.items.forEach(item => {
        const input = document.getElementById(`returnQty_${item.id}`);
        if (input && parseInt(input.value) > 0) {
            returnItems.push({
                sale_item_id: item.id,
                product_id: item.product_id,
                quantity: parseInt(input.value),
                refund_amount: parseInt(input.value) * parseFloat(item.price || 0)
            });
        }
    });

    if (returnItems.length === 0) {
        showAlert("Please select at least one item to return.", "Warning", "warning");
        return;
    }

    const reason = document.getElementById('returnReason').value;
    if (!reason.trim()) {
        showAlert("Please provide a reason for the return.", "Reason Required", "warning");
        return;
    }

    if (await showConfirm(`Request refund of ${document.getElementById('refundTotal').innerText} for this sale?`, "Confirm Return")) {
        try {
            const data = {
                sale_id: currentReturnSale.id,
                items: returnItems,
                reason: reason,
                shift_id: currentShiftId
            };
            
            const res = await fetch('api/credit_notes.php?action=request', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();
            
            if (result.success) {
                closeReturnModal();
                showAlert(result.message, "Success", "success");
            } else {
                showAlert(result.message, "Error", "error");
            }
        } catch (e) {
            console.error("Failed to submit credit note", e);
            showAlert("Connection error.", "Error", "error");
        }
    }
}

async function printDraftBill() {
    const q = queues[activeQueueIndex];
    if (!q.cart || q.cart.length === 0) return;

    const authRes = await fetch('api/auth.php?action=me');
    const authData = await authRes.json();
    const username = authData.success ? authData.user.username : 'Staff';

    const draftSale = {
        id: 'DRAFT',
        sale_date: new Date().toLocaleString(),
        username: username,
        customer_name: q.customer ? q.customer.name : 'Walk-in Customer',
        customer_tin: q.customer ? q.customer.tin : null,
        total_amount: q.cart.reduce((sum, i) => sum + (i.price * i.qty), 0),
        amount_paid: 0,
        change_amount: 0,
        payment_method: 'PENDING',
        items: q.cart.map(i => ({
            name: i.name,
            quantity: i.qty,
            subtotal: i.price * i.qty
        }))
    };

    await printThermal(draftSale, "PROFORMA BILL");
}

async function reprintSale(saleId) {
    try {
        const res = await fetch(`api/sales.php?action=receipt&id=${saleId}`);
        const data = await res.json();
        if (data.success) {
            await printThermal(data.data, "DUPLICATE RECEIPT");
            showCustomToast('Printing Copy', `Receipt #${saleId}`, 'fa-print', '#6366f1');
        } else {
            showAlert(data.message, "Error", "error");
        }
    } catch (e) {
        console.error("Failed to reprint sale", e);
        showAlert("Connection error.", "Error", "error");
    }
}

async function openProfileModal() {
    closeMoreMenu();
    const res = await fetch('api/auth.php?action=me');
    const data = await res.json();
    if (data.success) {
        document.getElementById('profileFullName').value = data.user.fullname || 'Unknown';
    }
    
    // Reset passwords
    document.getElementById('currentPass').value = '';
    document.getElementById('newPass').value = '';
    document.getElementById('confirmPass').value = '';

    const modal = document.getElementById('profileModal');
    modal.style.display = 'flex';
    setTimeout(() => modal.classList.add('show'), 10);
}

function closeProfileModal(reopenOptions = true) {
    const modal = document.getElementById('profileModal');
    modal.classList.remove('show');
    setTimeout(() => { 
        modal.style.display = 'none'; 
        if (reopenOptions) openMoreMenu();
    }, 300);
}

function clearInlineError(id) {
    const el = document.getElementById(id);
    if (el) el.innerText = '';
}

function togglePassVisibility(id, btn) {
    const input = document.getElementById(id);
    const icon = btn.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.replace('fa-eye', 'fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.replace('fa-eye-slash', 'fa-eye');
    }
}

async function updateProfilePassword() {
    const current = document.getElementById('currentPass').value;
    const newP = document.getElementById('newPass').value;
    const confirm = document.getElementById('confirmPass').value;

    // Reset errors
    ['currentPass', 'newPass', 'confirmPass', 'recalc'].forEach(id => {
        const el = document.getElementById('error_' + id);
        if (el) el.innerText = '';
    });

    let hasError = false;

    if (!current) {
        document.getElementById('error_currentPass').innerText = 'Please enter your current password';
        hasError = true;
    }

    if (!newP) {
        document.getElementById('error_newPass').innerText = 'Please enter a new password';
        hasError = true;
    } else if (newP.length < 4) {
        document.getElementById('error_newPass').innerText = 'Password must be at least 4 characters';
        hasError = true;
    }

    if (!confirm) {
        document.getElementById('error_confirmPass').innerText = 'Please confirm your new password';
        hasError = true;
    } else if (newP !== confirm) {
        document.getElementById('error_confirmPass').innerText = 'Passwords do not match';
        hasError = true;
    }

    if (hasError) return;

    const btn = document.querySelector('#profileModal button[onclick="updateProfilePassword()"]');
    btn.disabled = true;
    btn.innerText = 'UPDATING...';

    try {
        const fd = new FormData();
        fd.append('current_password', current);
        fd.append('new_password', newP);

        const res = await fetch('api/auth.php?action=change_password', {
            method: 'POST',
            body: fd
        });
        const data = await res.json();

        if (data.success) {
            showAlert(data.message, "Success", "success");
            closeProfileModal();
        } else {
            // Show the server error under current password if it relates to password mismatch
            if (data.message.toLowerCase().includes('current password')) {
                document.getElementById('error_currentPass').innerText = data.message;
            } else {
                showAlert(data.message, "Error", "error");
            }
        }
    } catch (e) {
        console.error("Password update failed", e);
        showAlert("Connection error.", "Error", "error");
    } finally {
        btn.disabled = false;
        btn.innerText = 'COMPLETE UPDATE';
    }
}
