// static/js/pos-cart.js

// Uses the same IndexedDB as product-cache.js
// Requires window.swiftposOpenDB to be defined (from product-cache.js)

let cartDB = null;

// ---------- DB HELPERS ----------

async function getDB() {
    if (cartDB) return cartDB;
    if (!window.swiftposOpenDB) {
        throw new Error("swiftposOpenDB is not defined. Make sure product-cache.js is loaded first.");
    }
    cartDB = await window.swiftposOpenDB();
    return cartDB;
}

async function loadCartFromDB() {
    const db = await getDB();

    return new Promise((resolve) => {
        const txItems = db.transaction("cart_items", "readonly");
        const storeItems = txItems.objectStore("cart_items");
        const itemsReq = storeItems.getAll();

        itemsReq.onsuccess = () => {
            const items = itemsReq.result || [];

            const txTotals = db.transaction("cart_totals", "readonly");
            const storeTotals = txTotals.objectStore("cart_totals");
            const totalsReq = storeTotals.get("current");

            totalsReq.onsuccess = () => {
                const totals = totalsReq.result || {
                    id: "current",
                    subtotal: 0,
                    discount: 0,
                    tax: 0,
                    grandTotal: 0
                };
                resolve({ items, totals });
            };
        };
    });
}

async function saveCartToDB(items, totals) {
    const db = await getDB();

    return new Promise((resolve) => {
        const tx = db.transaction(["cart_items", "cart_totals"], "readwrite");
        const storeItems = tx.objectStore("cart_items");
        const storeTotals = tx.objectStore("cart_totals");

        // Clear existing items
        const clearReq = storeItems.clear();
        clearReq.onsuccess = () => {
            items.forEach((item) => storeItems.put(item));
            storeTotals.put(totals);

            tx.oncomplete = () => resolve();
        };
    });
}

// ---------- CART LOGIC ----------

function recalcTotals(items) {
    let subtotal = 0;
    items.forEach((item) => {
        subtotal += item.price * item.quantity;
    });

    const discount = 0; // placeholder if you later add discount
    const tax = 0;      // placeholder if you later add tax
    const grandTotal = subtotal - discount + tax;

    return {
        id: "current",
        subtotal,
        discount,
        tax,
        grandTotal
    };
}

function renderCartUI(items, totals) {
    const tbody = document.getElementById("cart-items-body");
    const subtotalEl = document.getElementById("cart-subtotal");
    const grandTotalEl = document.getElementById("cart-grand-total");
    const cartPayloadField = document.getElementById("cart-payload-field");

    if (!tbody) return;

    tbody.innerHTML = "";

    items.forEach((item) => {
        const tr = document.createElement("tr");

        tr.innerHTML = `
            <td>${item.name}</td>
            <td>${item.quantity}</td>
            <td>${(window.swiftposCurrencySymbol || '')}${item.price.toFixed(2)}</td>
            <td>${(window.swiftposCurrencySymbol || '')}${(item.price * item.quantity).toFixed(2)}</td>
            <td>
                <button type="button"
                        class="btn btn-sm btn-danger"
                        data-remove-product-id="${item.productId}">
                    Remove
                </button>
            </td>
        `;

        tbody.appendChild(tr);
    });

    if (subtotalEl) {
        subtotalEl.textContent = totals.subtotal.toFixed(2);
    }
    if (grandTotalEl) {
        grandTotalEl.textContent = totals.grandTotal.toFixed(2);
    }

    // Save snapshot in hidden field for Phase 4 submit
    if (cartPayloadField) {
        cartPayloadField.value = JSON.stringify({
            items,
            totals
        });
    }
}

async function addItemToCartFromUI() {
    const dropdown = document.getElementById("product-dropdown");
    const qtyInput = document.getElementById("quantity-input");

    if (!dropdown || !qtyInput) return;

    const productId = parseInt(dropdown.value);
    if (!productId) return;

    const selectedOption = dropdown.options[dropdown.selectedIndex];
    const name = selectedOption.dataset.name || selectedOption.textContent;

    const basePrice = parseFloat(selectedOption.dataset.price || "0");
    const wholesalePrice = parseFloat(selectedOption.dataset.wholesalePrice || "0");
    const wholesaleMinQty = parseInt(selectedOption.dataset.wholesaleMinQty || "0");
    const quantity = parseInt(qtyInput.value || "1");

    if (!name || !basePrice || quantity <= 0) return;

    // Decide which unit price to use
    let price = basePrice;
    if (
        wholesalePrice &&
        !Number.isNaN(wholesalePrice) &&
        wholesaleMinQty &&
        !Number.isNaN(wholesaleMinQty) &&
        quantity >= wholesaleMinQty
    ) {
        price = wholesalePrice;
    }


    const { items } = await loadCartFromDB();

    // If product already in cart, increase quantity
    const existing = items.find((i) => i.productId === productId);
    if (existing) {
        existing.quantity += quantity;
    } else {
        items.push({
            id: productId,     // key in IndexedDB
            productId,
            name,
            price,
            quantity
        });
    }

    const totals = recalcTotals(items);
    await saveCartToDB(items, totals);
    renderCartUI(items, totals);
}

async function removeItemFromCart(productId) {
    const pid = parseInt(productId);
    const { items } = await loadCartFromDB();

    const newItems = items.filter((i) => i.productId !== pid);
    const totals = recalcTotals(newItems);

    await saveCartToDB(newItems, totals);
    renderCartUI(newItems, totals);
}

async function clearCart() {
    const db = await getDB();

    const items = [];
    const totals = recalcTotals(items);

    await saveCartToDB(items, totals);

    renderCartUI(items, totals);
}

// ---------- INIT / EVENT BINDING ----------

async function initCart() {
    const cartTableBody = document.getElementById("cart-items-body");
    if (!cartTableBody) {
        // Not on POS page
        return;
    }

    // 1. Load existing cart (if any) from DB and render
    const { items, totals } = await loadCartFromDB();
    renderCartUI(items, totals);

    // 2. Set up "Add to Cart" button
    const addBtn = document.getElementById("add-item-btn");
    if (addBtn) {
        addBtn.addEventListener("click", () => {
            addItemToCartFromUI();
        });
    }

    // 3. Handle remove buttons (event delegation)
    cartTableBody.addEventListener("click", (event) => {
        const btn = event.target.closest("button[data-remove-product-id]");
        if (!btn) return;
        const productId = btn.getAttribute("data-remove-product-id");
        if (productId) {
            removeItemFromCart(productId);
        }
    });

    // 4. Optional "Clear Cart" button
    const clearBtn = document.getElementById("clear-cart-btn");
    if (clearBtn) {
        clearBtn.addEventListener("click", () => {
            clearCart();
        });
    }
}

// Expose a small API for later (Phase 4)
window.swiftposCart = {
    init: initCart,
    loadCartFromDB,
    clearCart
};

document.addEventListener("DOMContentLoaded", () => {
    initCart();
});