{% extends 'core/base.html' %}
{% load static %}

{% block title %}POS Terminal - SwiftPOS{% endblock %}

{% block topbar_title %}
POS Terminal
{% endblock %}

{% block content %}

<!-- Receipt Action Modal -->
<!-- <div class="modal fade" id="receiptActionModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="border-radius: 14px;">
      <div class="modal-header">
        <h5 class="modal-title">Order Completed</h5>
      </div>

      <div class="modal-body text-center">
        <p class="text-muted mb-3">Choose how you want to finish this order.</p>

        <button onclick="printReceipt()" class="btn btn-primary w-100 mb-2">
            <i class="fas fa-print"></i> Print Receipt
        </button>

        <button onclick="shareReceipt()" class="btn btn-success w-100">
            <i class="fab fa-whatsapp"></i> Share via WhatsApp
        </button>
      </div>
    </div>
  </div>
</div> -->

<div class="container-fluid px-0">
        <div id="offline-banner" class="alert alert-warning rounded-0 mb-0 d-none">
        <i class="fas fa-wifi-slash me-2"></i>
        You are currently offline. Orders will be saved and synced automatically when you’re back online.
    </div>

    <!-- Toast Messages -->
    <div class="swiftpos-toast-container">
        {% if messages %}
            {% for message in messages %}
                <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}">
                    <div class="toast-icon">
                        {% if message.tags == 'success' %}
                            <i class="fas fa-check-circle"></i>
                        {% elif message.tags == 'error' or message.tags == 'danger' %}
                            <i class="fas fa-exclamation-circle"></i>
                        {% elif message.tags == 'warning' %}
                            <i class="fas fa-exclamation-triangle"></i>
                        {% else %}
                            <i class="fas fa-info-circle"></i>
                        {% endif %}
                    </div>
                    <div class="toast-text">
                        {{ message }}
                    </div>
                </div>
            {% endfor %}
        {% endif %}
    </div>

    <!-- Order + cashier overview -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card border-0" style="background: radial-gradient(circle at top left, rgba(79,70,229,.18), transparent 55%), radial-gradient(circle at bottom right, rgba(34,197,94,.14), transparent 45%), var(--sp-surface);">
                <div class="card-body d-flex flex-wrap justify-content-between align-items-center gap-3">
                    <div>
                        <div class="small text-muted mb-1">Active order</div>
                        <h5 class="mb-1">
                            <i class="fas fa-receipt me-2"></i>
                            {{ order.order_number }}
                        </h5>
                        <div class="small text-muted">
                            Cashier: {{ user_name }}
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 align-items-center">
                        <span class="badge rounded-pill bg-light text-muted border">
                            <i class="fas fa-box-open me-1"></i>
                            <span id="itemCount">{{ order_items|length }}</span> item{{ order_items|length|pluralize }}
                        </span>
                        <span class="badge rounded-pill bg-success-subtle text-success border border-success-subtle">
                            Total: <span class="ms-1 fw-semibold">{{ currency_symbol }}<span id="headerTotal">{{ final_total|floatformat:2 }}</span></span>
                        </span>
                        <a href="{% url 'sales:daily_dashboard' %}" class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2">
                            <i class="fas fa-chart-line"></i> Today’s summary
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main POS layout -->
    <div class="row g-3">
        <!-- LEFT: Products / search / quantity -->
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                            <i class="fas fa-boxes-stacked"></i> Product Selection
                        </h6>
                        <div class="d-flex align-items-center gap-2">
                            <span class="small text-muted">
                                Choose product & quantity, then add to cart
                            </span>
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary"
                                    id="refresh-products-btn">
                                <i class="fas fa-rotate-right me-1"></i> Refresh
                            </button>
                        </div>
                    </div>

                <div class="card-body">
                    <!-- Product select (now filled from IndexedDB via JS) -->
                    <form id="productForm" class="mb-3" onsubmit="return false;">
                        <div class="mb-3">
                            <label for="product-dropdown" class="form-label fw-semibold small">
                                Product
                            </label>
                            <select
                                class="form-select"
                                id="product-dropdown"
                                required>
                                <option value="">Search or choose product…</option>
                            </select>

                            <!-- Barcode Scanner (QuaggaJS) -->
                            {% if barcode_scanner_enabled %}
                                <div class="mt-2 d-flex align-items-center gap-2">
                                    <button type="button"
                                            class="btn btn-outline-secondary btn-sm d-inline-flex align-items-center gap-2"
                                            id="openScannerBtn">
                                        <i class="fas fa-barcode"></i>
                                        Scan barcode
                                    </button>
                                    <span id="scanStatus" class="small text-muted"></span>
                                </div>

                                <div id="scannerContainer"
                                     class="border rounded mt-2"
                                     style="display:none; padding:6px; width: 280px; height: 280px; position: relative;">
                                    <div class="small text-muted mb-1">
                                        Align the barcode inside the box:
                                    </div>
                                    <!-- Small camera frame -->
                                    <video id="barcodeVideo"
                                           style="width: 100%; height: 100%; object-fit: cover; background: #000;"
                                           playsinline></video>
                                    <div class="text-end mt-2">
                                        <button type="button"
                                                class="btn btn-sm btn-light"
                                                id="closeScannerBtn">
                                            Close scanner
                                        </button>
                                    </div>
                                </div>
                            {% else %}
                                <div class="mt-2 small text-muted">
                                    Barcode scanning is not available on your current plan.
                                </div>
                            {% endif %}

                            <div class="form-text small text-muted">
                                Use SKU or name to quickly find items.
                            </div>
                        </div>

                        <!-- Quantity + quick add -->
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="quantity-input" class="form-label fw-semibold small">
                                    Quantity
                                </label>
                                <input
                                    type="number"
                                    class="form-control"
                                    id="quantity-input"
                                    min="1"
                                    value="1"
                                    placeholder="Enter quantity">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold small">
                                    Quick add
                                </label>
                                <div class="d-flex gap-2 flex-wrap">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(1)">+1</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(5)">+5</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(10)">+10</button>
                                </div>
                            </div>
                        </div>

                        <!-- Selected product info + add to cart -->
                        <div class="mt-4 p-3 rounded-3" style="background:var(--sp-surface-muted);">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                <div>
                                    <div class="small text-muted mb-1">Selected product</div>
                                    <div class="small">
                                        Price: {{ currency_symbol }}<span id="selectedProductPrice">0.00</span> ·
                                        Stock: <span id="selectedProductStock">0</span>
                                    </div>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="button" class="btn btn-primary d-flex align-items-center gap-2" id="add-item-btn">
                                        <i class="fas fa-cart-plus"></i>
                                        Add to cart
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- RIGHT: Cart / totals / payment -->
        <div class="col-lg-4">
            <div class="position-sticky" style="top: 80px;">
                <!-- Cart items -->
                <div class="card mb-3">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                            <i class="fas fa-shopping-basket"></i> Current Cart
                        </h6>
                        <span class="badge bg-light text-muted border small">
                            <span id="cartItemCount">{{ order_items|length }}</span> item{{ order_items|length|pluralize }}
                        </span>
                    </div>
                    <div class="card-body" style="max-height: calc(100vh - 320px); overflow-y: auto;" id="orderItemsContainer">
                        <table class="table table-sm mb-0">
                            <tbody id="cart-items-body">
                                <!-- Filled by JS from IndexedDB -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Totals -->
                <div class="card mb-3">
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="small text-muted">Subtotal</span>
                            <span class="small">{{ currency_symbol }}<span id="cart-subtotal">{{ subtotal|floatformat:2 }}</span></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="small text-muted">Tax (0.0%)</span>
                            <span class="small">{{ currency_symbol }}{{ tax_amount|floatformat:2 }}</span>
                        </div>
                        <hr class="my-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="fw-semibold">Total</span>
                            <span class="price text-success">{{ currency_symbol }}<span id="cart-grand-total">{{ final_total|floatformat:2 }}</span></span>
                        </div>
                    </div>
                </div>

                <!-- Payment -->
                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                            <i class="fas fa-wallet"></i> Payment
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="post" id="pos-form">
                            {% csrf_token %}
                            <input type="hidden" name="cart_payload" id="cart-payload-field">

                           <div class="mb-3">
                                <label class="form-label small fw-semibold">Payment method</label>
                                <select class="form-select" name="payment_method" required>
                                    <option value="pos">POS / Card</option>
                                    <option value="transfer">Bank Transfer</option>
                                    <option value="cash">Cash</option>
                                    <option value="mobile_money">Mobile Money</option>
                                    <option value="credit">Credit (No immediate payment)</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label small fw-semibold">Payment status</label>
                                <select class="form-select" name="payment_status" id="payment-status-select">
                                    <option value="full" selected>Paid in full</option>
                                    <option value="partial">Partial payment</option>
                                    <option value="credit">Credit / Customer owing</option>
                                </select>
                                <div class="form-text">
                                    Choose "Credit" when the customer will pay later (bashi / loan).
                                </div>
                            </div>

                            <div class="mb-3" id="amount-paid-group">
                                <label class="form-label small fw-semibold">Amount paid now</label>
                                <input
                                    type="number"
                                    step="0.01"
                                    min="0"
                                    name="amount_paid"
                                    class="form-control"
                                    placeholder="Amount customer is paying now">
                                <div class="form-text">
                                    Leave empty for full payment. For credit, set what they pay now (0 for full loan).
                                </div>
                            </div>


                            <div class="mb-3">
                                <label class="form-label small fw-semibold">Reference (optional)</label>
                                <input
                                    type="text"
                                    name="reference_number"
                                    class="form-control"
                                    placeholder="Transaction reference">
                            </div>

                            <div class="mb-3">
                                <label class="form-label small fw-semibold">Customer <span class="text-muted fw-normal">(optional)</span></label>
                                <!-- Search box -->
                                <div class="position-relative">
                                    <input type="text" id="pos-cust-search" class="form-control" placeholder="🔍 Search customer…" autocomplete="off">
                                    <div id="pos-cust-dropdown" class="list-group position-absolute w-100 shadow-sm" style="z-index:9999;max-height:220px;overflow-y:auto;display:none;top:100%;">
                                        <button type="button" class="list-group-item list-group-item-action" data-name="" data-phone="">
                                            <span class="fw-semibold">Walk-in (no customer)</span>
                                        </button>
                                        {% for c in customers %}
                                        <button type="button" class="list-group-item list-group-item-action"
                                                data-name="{{ c.name|escapejs }}"
                                                data-phone="{{ c.phone|default:''|escapejs }}">
                                            <span class="fw-semibold">{{ c.name }}</span>
                                            {% if c.phone %}<span class="text-muted small ms-2">{{ c.phone }}</span>{% endif %}
                                        </button>
                                        {% endfor %}
                                    </div>
                                </div>
                                <!-- Hidden actual fields sent with form -->
                                <input type="hidden" name="customer_name" id="pos-cust-name-val">
                                <input type="hidden" name="customer_phone" id="pos-cust-phone-val">
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary d-flex justify-content-center align-items-center gap-2">
                                    <i class="fas fa-check-circle"></i>
                                    Complete order
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Clear order (now JS-driven, not POST) -->
                <div class="card">
                    <div class="card-body">
                        <button type="button" class="btn btn-outline-danger w-100 d-flex justify-content-center align-items-center gap-2" id="clear-cart-btn">
                            <i class="fas fa-trash"></i>
                            Clear order
                        </button>
                    </div>
                </div>

            </div> <!-- /position-sticky -->
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
    <!-- QuaggaJS barcode library -->
    <script src="{% static 'js/quagga.min.js' %}"></script>

    <!-- Offline product + cart + order sync -->
    <script src="{% static 'js/product-cache.js' %}"></script>
    <script src="{% static 'js/pos-cart.js' %}"></script>
    <script src="{% static 'js/order-sync.js' %}"></script>

    <script>
    // Barcode scanner logic (same as before, but using #product-dropdown)
    document.addEventListener('DOMContentLoaded', function () {
        const scannerEnabled = {{ barcode_scanner_enabled|yesno:"true,false" }};
        if (!scannerEnabled) {
            console.log("DEBUG POS: Barcode scanner disabled by plan");
            return;
        }

        const productSelect = document.getElementById('product-dropdown');
        const openBtn = document.getElementById('openScannerBtn');
        const closeBtn = document.getElementById('closeScannerBtn');
        const scannerContainer = document.getElementById('scannerContainer');
        const scanStatus = document.getElementById('scanStatus');
        const videoElem = document.getElementById('barcodeVideo');

        let scanning = false;

        function selectProductByBarcode(barcode) {
            if (!productSelect) return false;
            const value = barcode.trim();
            console.log("DEBUG POS: Decoded barcode =", value);

            const opts = productSelect.options;
            for (let i = 0; i < opts.length; i++) {
                const opt = opts[i];
                if (opt.dataset && opt.dataset.barcode && opt.dataset.barcode === value) {
                    productSelect.value = opt.value;
                    productSelect.dispatchEvent(new Event('change'));
                    scanStatus.textContent = "Scanned: " + value;
                    scanStatus.classList.remove('text-danger');
                    scanStatus.classList.add('text-success');
                    return true;
                }
            }
            scanStatus.textContent = "No product found with barcode " + value;
            scanStatus.classList.remove('text-success');
            scanStatus.classList.add('text-danger');
            return false;
        }

        function startScanner() {
            if (scanning) return;

            scannerContainer.style.display = 'block';
            scanStatus.textContent = "Align barcode with camera…";
            scanStatus.classList.remove('text-danger', 'text-success');

            Quagga.init({
                inputStream: {
                    name: "Live",
                    type: "LiveStream",
                    target: document.querySelector('#scannerContainer'),
                    constraints: {
                        width: { min: 640, ideal: 640, max: 1280 },
                        height: { min: 480, ideal: 480, max: 720 },
                        aspectRatio: { ideal: 1 },
                        facingMode: "environment"
                    },
                },
                decoder: {
                    readers: ["code_128_reader"]
                }
            }, function (err) {
                if (err) {
                    console.error("DEBUG POS: Quagga initialization error:", err);
                    scanStatus.textContent = "Error initializing scanner.";
                    scanStatus.classList.add('text-danger');
                    scannerContainer.style.display = 'none';
                    return;
                }
                console.log("DEBUG POS: Quagga initialized successfully.");
                Quagga.start();
                scanning = true;
            });

            Quagga.onDetected(function (result) {
                const barcode = result.codeResult.code;
                console.log("DEBUG POS: Barcode detected:", barcode);
                const found = selectProductByBarcode(barcode);
                if (found) {
                    stopScanner();
                }
            });
        }

        function stopScanner() {
            if (!scanning) return;
            Quagga.stop();
            scanning = false;
            scannerContainer.style.display = 'none';
            console.log("DEBUG POS: Scanner stopped");
        }

        if (openBtn) {
            openBtn.addEventListener('click', function () {
                if (scanning) {
                    stopScanner();
                } else {
                    startScanner();
                }
            });
        }

        if (closeBtn) {
            closeBtn.addEventListener('click', function () {
                stopScanner();
            });
        }

        window.addEventListener('beforeunload', function () {
            stopScanner();
        });
    });
    </script>

    <!-- Existing POS JS: Select2, selected product info, quickAdd -->
    <script>
    document.addEventListener('DOMContentLoaded', async function () {
        const productSelect = document.getElementById('product-dropdown');
        const priceSpan = document.getElementById('selectedProductPrice');
        const stockSpan = document.getElementById('selectedProductStock');
        const statusEl = document.getElementById('product-loading-status');
        const refreshBtn = document.getElementById('refresh-products-btn');

                // ---- Payment status -> show/hide Amount Paid ----
        const paymentStatusSelect = document.getElementById("payment-status-select");
        const amountPaidGroup = document.getElementById("amount-paid-group");

        function updateAmountPaidVisibility() {
            if (!paymentStatusSelect || !amountPaidGroup) return;
            const val = paymentStatusSelect.value;
            if (val === "full") {
                amountPaidGroup.classList.add("d-none");
            } else {
                amountPaidGroup.classList.remove("d-none");
            }
        }

        if (paymentStatusSelect && amountPaidGroup) {
            paymentStatusSelect.addEventListener("change", updateAmountPaidVisibility);
            updateAmountPaidVisibility();
        }

    
        async function populateProducts(options) {
            if (!productSelect || !window.swiftposLoadProducts) return;
    
            const forceRefresh = options && options.forceRefresh;
            if (statusEl) {
                statusEl.textContent = forceRefresh ? "Refreshing products…" : "Loading products…";
            }
    
            try {
                let products;
                if (forceRefresh && window.swiftposRefreshProducts) {
                    products = await window.swiftposRefreshProducts();
                } else {
                    products = await window.swiftposLoadProducts();
                }
    
                productSelect.innerHTML = '<option value="">Search or choose product…</option>';
    
                (products || []).forEach((p) => {
                    if (Number(p.stock_quantity) <= 0) return; // safety

                    const opt = document.createElement('option');
                    opt.value = p.id;

                    // Build label: show wholesale price if configured
                    let label = `${p.name} (${p.id}) - {{ currency_symbol }}${p.price}`;
                    if (p.wholesale_price && Number(p.wholesale_min_quantity) > 0) {
                        label += ` / Wholesale: {{ currency_symbol }}${p.wholesale_price} (≥ ${p.wholesale_min_quantity})`;
                    }
                    label += ` | Stock: ${p.stock_quantity}`;
                    opt.textContent = label;

                    opt.dataset.name = p.name;
                    opt.dataset.price = p.price;
                    opt.dataset.stock = p.stock_quantity;
                    opt.dataset.barcode = p.barcode || "";

                    // NEW: store wholesale info
                    opt.dataset.wholesalePrice = p.wholesale_price || "";
                    opt.dataset.wholesaleMinQty = p.wholesale_min_quantity || "";

                    productSelect.appendChild(opt);
                });

    
                if (statusEl) {
                    statusEl.textContent = navigator.onLine ? "Products up to date." : "Offline — using cached products.";
                }
    
                updateSelectedInfo();
            } catch (err) {
                console.error("SwiftPOS: error loading products", err);
                if (statusEl) {
                    statusEl.textContent = "Error loading products. Using cached data if available.";
                }
            }
        }
    
        function updateSelectedInfo() {
            if (!productSelect || !priceSpan || !stockSpan) return;
            const opt = productSelect.options[productSelect.selectedIndex];
            if (opt && opt.value) {
                priceSpan.textContent = opt.dataset.price || '0.00';
                stockSpan.textContent = opt.dataset.stock || '0';
            } else {
                priceSpan.textContent = '0.00';
                stockSpan.textContent = '0';
            }
        }
    
        // Initialize Select2 if available
        if (window.jQuery && jQuery.fn.select2) {
            $('#product-dropdown').select2({
                placeholder: "Search or choose product…",
                allowClear: true,
                width: '100%',
                dropdownAutoWidth: true
            });
        }
    
        if (productSelect) {
            productSelect.addEventListener('change', updateSelectedInfo);
        }
    
        // Initial load
        populateProducts({ forceRefresh: false });
    
        // Refresh button
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function () {
                populateProducts({ forceRefresh: true });
            });
        }
    
        // Auto-refresh when back online
        window.addEventListener('online', () => {
            populateProducts({ forceRefresh: true });
        });
    
        // Offline banner
        function updateOfflineBanner() {
            const banner = document.getElementById('offline-banner');
            if (!banner) return;
            if (navigator.onLine) {
                banner.classList.add('d-none');
            } else {
                banner.classList.remove('d-none');
            }
        }
    
        window.addEventListener('online', updateOfflineBanner);
        window.addEventListener('offline', updateOfflineBanner);
        updateOfflineBanner();
    
        const container = document.getElementById('orderItemsContainer');
        if (container) {
            container.scrollTop = container.scrollHeight;
        }
    });
    
    function quickAdd(qty) {
        const quantityInput = document.getElementById('quantity-input');
        if (!quantityInput) return;
        quantityInput.value = qty;
        const addBtn = document.getElementById('add-item-btn');
        if (addBtn) addBtn.click();
    }
    </script>


<script>
(function() {
    const search = document.getElementById('pos-cust-search');
    const drop   = document.getElementById('pos-cust-dropdown');
    const nameV  = document.getElementById('pos-cust-name-val');
    const phoneV = document.getElementById('pos-cust-phone-val');
    if (!search) return;
    const allBtns = Array.from(drop.querySelectorAll('button[data-name]'));
    search.addEventListener('input', function() {
        const q = this.value.toLowerCase();
        allBtns.forEach(b => b.style.display = b.textContent.toLowerCase().includes(q) ? '' : 'none');
        drop.style.display = '';
    });
    search.addEventListener('focus', () => drop.style.display = '');
    allBtns.forEach(btn => btn.addEventListener('click', function() {
        nameV.value  = this.dataset.name;
        phoneV.value = this.dataset.phone;
        search.value = this.dataset.name || '';
        drop.style.display = 'none';
    }));
    document.addEventListener('click', e => {
        if (!search.contains(e.target) && !drop.contains(e.target)) drop.style.display = 'none';
    });
})();
</script>
{% endblock %}