<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 3) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

// Assuming store_id is stored in session or fallback to 1
$store_id = $_SESSION['store_id'] ?? 1;

// Fetch products for search dropdown (limit 100 for performance)
$product_search_stmt = $conn->prepare("SELECT id, product_name, barcode, selling_price, vat_rate FROM products ORDER BY product_name LIMIT 100");
$product_search_stmt->execute();
$products_for_search = $product_search_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$product_search_stmt->close();

// Generate a unique receipt number (you might want to make this more robust)
$receipt_number = 'LDS-' . strtoupper(uniqid());

// Cashier ID
$cashier_id = $_SESSION['user_id'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>POS - Cashier</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body, html {
    margin: 0;
    padding: 0;
    min-height: 100vh;
    width: 100%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: url('../../images/profile.jpg') no-repeat center center fixed;
    background-size: cover;
    color: #eee;
    overflow-x: hidden;
}

/* Reserve space for header (adjust if your header is larger or smaller) */
body {
    padding-top: 70px; /* Reserve 70px space for header */
}

body::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: -1;
}


body::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: -1;
}

.container {
    width: 95%;
    max-width: 1600px;
    margin: 20px auto;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(12px);
    padding: 20px;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(255, 165, 0, 0.3);
    display: flex;
    flex-direction: column;
    min-height: calc(100vh - 40px);
}

h1 {
    text-align: center;
    color: #ffa500;
    margin-bottom: 20px;
}

.input-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 15px;
}

input[type=text], input[type=number], select {
    flex: 1 1 200px;
    padding: 8px 12px;
    border-radius: 8px;
    border: none;
    background: rgba(255,255,255,0.1);
    color: white;
    font-size: 1rem;
    min-width: 150px;
}

button {
    padding: 10px 16px;
    background-color: #ffa500;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    color: black;
    cursor: pointer;
    box-shadow: 0 4px 8px rgba(255,111,0,0.5);
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #cc7a00;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 25px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    overflow-x: auto;
    backdrop-filter: blur(8px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.3);
}

th, td {
    padding: 12px 15px;
    text-align: center;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    color: white;
    word-wrap: break-word;
}

th {
    background: rgba(255, 255, 255, 0.15);
    font-weight: 600;
    color: #ffa500;
}

tbody tr:hover {
    background: rgba(255, 165, 0, 0.1);
}

.totals {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 10px;
    font-weight: 600;
    font-size: 1.1rem;
    color: #ffa500;
}

.payment-section {
    margin-top: 25px;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
    justify-content: space-between;
}

.payment-section select,
.payment-section input[type=number] {
    max-width: 220px;
    background: rgba(255,255,255,0.1);
    border-radius: 8px;
    color: white;
    border: none;
    padding: 8px 12px;
    flex: 1 1 auto;
}

.remove-btn {
    background: #dc3545;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    padding: 6px 10px;
    font-weight: 700;
    box-shadow: 0 4px 8px rgba(220, 53, 69, 0.4);
}

.remove-btn:hover {
    background: #a71d2a;
}

.change-display {
    margin-top: 10px;
    font-size: 1.2rem;
    font-weight: 700;
    color: #ffa500;
    text-align: right;
}

@media (max-width: 900px) {
    .input-group, .payment-section {
        flex-direction: column;
        align-items: stretch;
    }

    .payment-section select,
    .payment-section input[type=number],
    .payment-section button {
        width: 100%;
    }

    table {
        display: block;
        overflow-x: auto;
        white-space: nowrap;
    }

    th, td {
        min-width: 120px;
        padding: 10px;
    }

    .totals {
        flex-direction: column;
        align-items: flex-start;
        font-size: 1rem;
    }

    .change-display {
        text-align: left;
        font-size: 1rem;
    }
}
</style>

</head>
<body>
<div class="container">
    <h1>POS - Cashier</h1>

    <form id="pos-form" method="POST" action="process_sale.php" autocomplete="off">
        <input type="hidden" name="sold_by" value="<?= htmlspecialchars($cashier_id) ?>" />
        <input type="hidden" name="receipt_number" value="<?= htmlspecialchars($receipt_number) ?>" />
        <input type="hidden" name="store_id" value="<?= htmlspecialchars($store_id) ?>" />
        
        <!-- Barcode input -->
        <div class="input-group">
            <input type="text" id="barcode-input" placeholder="Scan or enter barcode" autofocus autocomplete="off" />
            <button type="button" id="add-barcode-btn">Add by Barcode</button>
        </div>

        <!-- Manual product search -->
        <div class="input-group">
            <input type="text" id="product-search-input" placeholder="Search product by name or barcode" autocomplete="off" />
            <select id="product-select" size="5" style="display:none;"></select>
            <button type="button" id="add-product-btn">Add Selected Product</button>
        </div>

        <!-- Cart Table -->
        <table id="cart-table" aria-label="Shopping cart">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Unit Price (MWK)</th>
                    <th>Discount (MWK)</th>
                    <th>VAT (MWK)</th>
                    <th>Total (MWK)</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <!-- Items get added here dynamically -->
            </tbody>
        </table>

        <!-- Totals -->
        <div class="totals">
            <div>Subtotal: MWK <span id="subtotal">0.00</span></div>
            <div>Total Discount: MWK <span id="total-discount">0.00</span></div>
            <div>Total VAT: MWK <span id="total-vat">0.00</span></div>
            <div><strong>Grand Total: MWK <span id="grand-total">0.00</span></strong></div>
        </div>

        <!-- Payment Section -->
        <div class="payment-section">
            <label for="payment-method">Payment Method:</label>
            <select id="payment-method" name="payment_method" required>
                <option value="">Select payment method</option>
                <option value="Cash">Cash</option>
                <option value="Card">Card</option>
                <option value="Airtel Money">Airtel Money</option>
                <option value="Mpamba">Mpamba</option>
            </select>

            <label for="amount-paid">Amount Paid (MWK):</label>
            <input type="number" id="amount-paid" name="amount_paid" min="0" step="0.01" value="0" required />

            <button type="submit" id="finalize-sale-btn">Finalize Sale</button>
        </div>

        <div class="change-display" id="change-display">Change: MWK 0.00</div>

        <!-- Items will be dynamically added as hidden inputs -->
    </form>
</div>

<script>
    // Products list from PHP
    const products = <?= json_encode($products_for_search); ?>;

    // Elements
    const barcodeInput = document.getElementById('barcode-input');
    const addBarcodeBtn = document.getElementById('add-barcode-btn');
    const productSearchInput = document.getElementById('product-search-input');
    const productSelect = document.getElementById('product-select');
    const addProductBtn = document.getElementById('add-product-btn');
    const cartTableBody = document.querySelector('#cart-table tbody');
    const subtotalEl = document.getElementById('subtotal');
    const totalDiscountEl = document.getElementById('total-discount');
    const totalVatEl = document.getElementById('total-vat');
    const grandTotalEl = document.getElementById('grand-total');
    const amountPaidInput = document.getElementById('amount-paid');
    const changeDisplay = document.getElementById('change-display');
    const posForm = document.getElementById('pos-form');

    // Cart array
    let cart = [];

    // Find product by barcode or id
    function findProductByBarcode(barcode) {
        return products.find(p => p.barcode === barcode);
    }

    function findProductById(id) {
        return products.find(p => p.id == id);
    }

    // Add product to cart
    function addProductToCart(product) {
        if (!product) return alert('Product not found');

        // Check if already in cart
        const existing = cart.find(item => item.product.id == product.id);
        if (existing) {
            existing.quantity += 1;
            updateCart();
            return;
        }

        cart.push({
            product: product,
            quantity: 1,
            discount: 0
        });
        updateCart();
    }

    // Update cart table & totals
    function updateCart() {
        cartTableBody.innerHTML = '';

        let subtotal = 0, totalDiscount = 0, totalVat = 0;

        cart.forEach((item, index) => {
            const { product, quantity, discount } = item;
            const unitPrice = parseFloat(product.selling_price);
            const vatRate = parseFloat(product.vat_rate);

            const totalBeforeDiscount = unitPrice * quantity;
            const vatAmount = ((totalBeforeDiscount - discount) * vatRate) / 100;
            const total = totalBeforeDiscount - discount + vatAmount;

            subtotal += totalBeforeDiscount;
            totalDiscount += discount;
            totalVat += vatAmount;

            const tr = document.createElement('tr');

            tr.innerHTML = `
                <td>${product.product_name}</td>
                <td><input type="number" min="1" value="${quantity}" data-index="${index}" class="qty-input" style="width:60px; border-radius:6px; padding:3px;"/></td>
                <td>${unitPrice.toFixed(2)}</td>
                <td><input type="number" min="0" max="${(unitPrice * quantity).toFixed(2)}" step="0.01" value="${discount.toFixed(2)}" data-index="${index}" class="discount-input" style="width:80px; border-radius:6px; padding:3px;"/></td>
                <td>${vatAmount.toFixed(2)}</td>
                <td>${total.toFixed(2)}</td>
                <td><button type="button" class="remove-btn" data-index="${index}">Remove</button></td>
            `;

            cartTableBody.appendChild(tr);
        });

        subtotalEl.textContent = subtotal.toFixed(2);
        totalDiscountEl.textContent = totalDiscount.toFixed(2);
        totalVatEl.textContent = totalVat.toFixed(2);
        grandTotalEl.textContent = (subtotal - totalDiscount + totalVat).toFixed(2);

        updateChange();

        // Update hidden inputs on submit, not here
    }

    // Calculate and update change display
    function updateChange() {
        const grandTotal = parseFloat(grandTotalEl.textContent) || 0;
        const amountPaid = parseFloat(amountPaidInput.value) || 0;
        const change = amountPaid - grandTotal;
        changeDisplay.textContent = `Change: MWK ${change >= 0 ? change.toFixed(2) : '0.00'}`;
    }

    // Handle barcode add
    addBarcodeBtn.addEventListener('click', () => {
        const code = barcodeInput.value.trim();
        if (!code) return alert('Please enter a barcode');

        const product = findProductByBarcode(code);
        if (!product) {
            alert('Product not found for this barcode');
            return;
        }
        addProductToCart(product);
        barcodeInput.value = '';
        barcodeInput.focus();
    });

    // Product search filter and dropdown
    productSearchInput.addEventListener('input', () => {
        const query = productSearchInput.value.trim().toLowerCase();
        if (!query) {
            productSelect.style.display = 'none';
            productSelect.innerHTML = '';
            return;
        }
        const matches = products.filter(p => 
            p.product_name.toLowerCase().includes(query) || 
            (p.barcode && p.barcode.includes(query))
        ).slice(0, 10);

        productSelect.innerHTML = '';
        if (matches.length === 0) {
            productSelect.style.display = 'none';
            return;
        }
        matches.forEach(p => {
            const option = document.createElement('option');
            option.value = p.id;
            option.textContent = `${p.product_name} (${p.barcode || 'No barcode'}) - MWK ${parseFloat(p.selling_price).toFixed(2)}`;
            productSelect.appendChild(option);
        });
        productSelect.style.display = 'block';
        productSelect.selectedIndex = 0;
    });

    // Add product by manual search selection
    addProductBtn.addEventListener('click', () => {
        if (productSelect.style.display === 'none' || productSelect.selectedIndex < 0) {
            alert('Please select a product');
            return;
        }
        const selectedId = productSelect.value;
        const product = findProductById(selectedId);
        if (!product) {
            alert('Selected product not found');
            return;
        }
        addProductToCart(product);
        productSearchInput.value = '';
        productSelect.style.display = 'none';
    });

    // Delegate qty and discount changes
    cartTableBody.addEventListener('input', e => {
        const target = e.target;
        const index = target.dataset.index;
        if (index === undefined) return;

        if (target.classList.contains('qty-input')) {
            const qty = parseInt(target.value);
            if (qty < 1) {
                target.value = cart[index].quantity;
                return alert('Quantity must be at least 1');
            }
            cart[index].quantity = qty;
            updateCart();
        } else if (target.classList.contains('discount-input')) {
            const discountVal = parseFloat(target.value);
            if (isNaN(discountVal) || discountVal < 0) {
                target.value = cart[index].discount.toFixed(2);
                return alert('Discount must be a positive number or zero');
            }
            const maxDiscount = cart[index].product.selling_price * cart[index].quantity;
            if (discountVal > maxDiscount) {
                target.value = cart[index].discount.toFixed(2);
                return alert('Discount cannot exceed total price');
            }
            cart[index].discount = discountVal;
            updateCart();
        }
    });

    // Remove item button
    cartTableBody.addEventListener('click', e => {
        if (e.target.classList.contains('remove-btn')) {
            const index = e.target.dataset.index;
            if (index !== undefined) {
                cart.splice(index, 1);
                updateCart();
            }
        }
    });

    // Update change when amount paid changes
    amountPaidInput.addEventListener('input', updateChange);

    // On form submit, prepare inputs for items array and validate
    posForm.addEventListener('submit', e => {
        if (cart.length === 0) {
            e.preventDefault();
            alert('Add at least one product to the cart before finalizing the sale.');
            return false;
        }
        if (!document.getElementById('payment-method').value) {
            e.preventDefault();
            alert('Please select a payment method.');
            return false;
        }
        const amountPaid = parseFloat(amountPaidInput.value);
        const grandTotal = parseFloat(grandTotalEl.textContent);
        if (isNaN(amountPaid) || amountPaid < grandTotal) {
            e.preventDefault();
            alert(`Amount paid must be at least MWK ${grandTotal.toFixed(2)}.`);
            return false;
        }

        // Remove previous dynamic inputs if any
        const oldInputs = posForm.querySelectorAll('input[name^="items"]');
        oldInputs.forEach(i => i.remove());

        // Add hidden inputs for each item
        cart.forEach((item, index) => {
            const baseName = `items[${index}]`;

            const prodIdInput = document.createElement('input');
            prodIdInput.type = 'hidden';
            prodIdInput.name = `${baseName}[product_id]`;
            prodIdInput.value = item.product.id;
            posForm.appendChild(prodIdInput);

            const qtyInput = document.createElement('input');
            qtyInput.type = 'hidden';
            qtyInput.name = `${baseName}[quantity]`;
            qtyInput.value = item.quantity;
            posForm.appendChild(qtyInput);

            const discountInput = document.createElement('input');
            discountInput.type = 'hidden';
            discountInput.name = `${baseName}[discount]`;
            discountInput.value = item.discount.toFixed(2);
            posForm.appendChild(discountInput);
        });
    });

    // Initial cart update in case products are preloaded
    updateCart();
    
</script>
<script>
    posForm.addEventListener('submit', e => {
        e.preventDefault(); // Prevent default form submission

        if (cart.length === 0) {
            alert('Add at least one product to the cart before finalizing the sale.');
            return false;
        }
        if (!document.getElementById('payment-method').value) {
            alert('Please select a payment method.');
            return false;
        }
        const amountPaid = parseFloat(amountPaidInput.value);
        const grandTotal = parseFloat(grandTotalEl.textContent);
        if (isNaN(amountPaid) || amountPaid < grandTotal) {
            alert(`Amount paid must be at least MWK ${grandTotal.toFixed(2)}.`);
            return false;
        }

        const formData = new FormData(posForm);

        // Add cart items as JSON
        const items = cart.map(item => ({
            product_id: item.product.id,
            quantity: item.quantity,
            discount: item.discount
        }));

        const data = {
            items: items,
            payment_method: formData.get('payment_method'),
            store_id: formData.get('store_id'),
            receipt_number: formData.get('receipt_number'),
            customer_name: '', // optional
            amount_paid: parseFloat(formData.get('amount_paid'))
        };

        fetch('process_sale.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('Sale successful!');

                const receiptWindow = window.open('receipt_view.php?sale_id=' + result.sale_id, '_blank');

                setTimeout(() => {
                    if (receiptWindow) {
                        receiptWindow.print();
                    }
                }, 1500);  // Wait 1.5 seconds before triggering print

                // Optional: Reset everything after successful sale
                location.reload();
            } else {
                alert('Error: ' + result.message);
            }
        })
        .catch(err => {
            console.error(err);
            alert('An unexpected error occurred.');
        });
    });
</script>

</body>
</html>
