<?php $__env->startSection('content'); ?>
<style>
    .product-card-media {
        height: 180px;
    }

    .product-card-media img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-top-left-radius: 0.5rem;
        border-top-right-radius: 0.5rem;
    }

    @media (min-width: 992px) {
        .product-card-media {
            height: 200px;
        }
    }
    .product-card {
        border: 1px solid #dee2e6;
        border-radius: 0.5rem;
        cursor: pointer;
        transition: transform 0.15s ease, box-shadow 0.15s ease;
    }

    .product-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
</style>

<div class="content">
    <div class="container-fluid py-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">Point of Sale</h1>
                <p class="text-secondary mb-0">Process customer orders, add items to the cart, and complete checkout.</p>
            </div>
            <div class="btn-toolbar gap-2">
                <a href="<?php echo e(url('sales')); ?>" class="btn btn-outline-secondary">
                    <i class="bi bi-clock-history me-2"></i>Recent Orders
                </a>
            </div>
        </div>

        <div class="row g-4">
            <!-- Products List -->
            <div class="col-12 col-lg-8">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-body-tertiary">
                        <h2 class="h5 mb-0">Products</h2>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                          <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <?php
                                    $packSize = $product->packSize;
                                    $packSizeName = $packSize->name ?? 'Pack';
                                    $packBottleQty = $product->pack_bottle_quantity ?? ($packSize->quantity ?? 0);
                                    $availablePacks = $product->available_packs ?? 0;
                                    $availableBottles = $product->current_stock ?? 0;
                                ?>
                                <div class="col-6 col-md-4">
                                    <article class="product-card" 
                                        data-sku="<?php echo e($product->id); ?>" 
                                        data-name="<?php echo e($product->name); ?>" 
                                        data-pack-size-id="<?php echo e($product->pack_size_id); ?>"
                                        data-pack-size-name="<?php echo e($packSizeName); ?>"
                                        data-pack-quantity="<?php echo e($packBottleQty); ?>"
                                        data-bottle-stock="<?php echo e($availableBottles); ?>"
                                        data-image="<?php echo e($product->image ? asset('storage/products/' . $product->image) : asset('img/prod-1.jpg')); ?>"
                                        data-available="<?php echo e($availablePacks > 0 ? 'true' : 'false'); ?>" 
                                        data-stock="<?php echo e($availablePacks); ?>">
                                        
                                        <div class="position-relative product-card-media">
                                            <?php if($availablePacks === 0): ?>
                                                <span class="badge text-bg-danger position-absolute top-0 end-0 m-2">Out of stock</span>
                                            <?php elseif($availablePacks < 5): ?>
                                                <span class="badge text-bg-warning position-absolute top-0 end-0 m-2">
                                                    Low stock (<?php echo e($availablePacks); ?> packs)
                                                </span>
                                            <?php else: ?>
                                                <span class="badge text-bg-success position-absolute top-0 end-0 m-2">
                                                    In stock (<?php echo e($availablePacks); ?> packs)
                                                </span>
                                            <?php endif; ?>
                                            <img src="<?php echo e($product->image ? asset('storage/products/' . $product->image) : asset('img/prod-1.jpg')); ?>" class="card-img-top rounded-top" alt="<?php echo e($product->name); ?>">
                                        </div>

                                        <div class="card-body <?php echo e($availablePacks === 0 ? 'opacity-75' : ''); ?>">
                                            <h6 class="card-title mb-1"><?php echo e($product->name); ?></h6>
                                            <p class="text-secondary small mb-2">
                                                <?php echo e($packSizeName); ?> &middot; <?php echo e($packBottleQty); ?> bottles/pack
                                            </p>
                                            <div class="d-flex justify-content-end">
                                                <small class="text-secondary">
                                                    <?php echo e($availablePacks > 0 ? 'Tap to add pack' : 'Out of stock'); ?>

                                                </small>
                                            </div>
                                        </div>
                                    </article>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <div class="col-12 text-center">
                                    <p class="text-muted fw-semibold">No products found.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Cart -->
                <div class="card shadow-sm">
                    <div class="card-header bg-body-tertiary d-flex justify-content-between align-items-center">
                        <h2 class="h5 mb-0">Current Cart</h2>
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="clearCartButton">
                            <i class="bi bi-trash"></i> Clear
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0 align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th scope="col">Item</th>
                                        <th scope="col" class="text-center" style="width: 140px;">Qty</th>
                                        <th scope="col" class="text-end" style="width: 140px;">Price</th>
                                        <th scope="col" class="text-end" style="width: 140px;">Subtotal</th>
                                        <th scope="col" class="text-end" style="width: 60px;"></th>
                                    </tr>
                                </thead>
                                <tbody id="cartItems"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Order Summary -->
            <div class="col-12 col-lg-4">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-primary text-white">
                        <h2 class="h5 mb-0">Order Summary</h2>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span>Total Packs</span>
                            <span id="summaryItems">0</span>
                        </div>
                        <hr>

                        <div class="row g-3 mb-3">
                            <div class="col-6">
                                <label for="fuelCharges" class="form-label">Fuel Charges</label>
                                <input type="number" id="fuelCharges" class="form-control form-control-sm text-end" step="0.01" placeholder="0.00">
                            </div>
                            <div class="col-6">
                            <label for="otherCharges" class="form-label">Other Charges</label>
                            <input type="number" id="otherCharges" class="form-control form-control-sm text-end" step="0.01" placeholder="0.00">
                            </div>
                        </div>

                        <!-- other Charges Detail Field (Hidden Initially) -->
                       
                        <div class="row g-3 mb-3" id="otherChargesDetailRow" style="display: none;">
                            <div class="col-12">
                            <label for="otherChargesDetail" class="form-label">Other Charges Detail</label>
                            <textarea id="otherChargesDetail" class="form-control form-control-sm" placeholder="Enter detail about other charges"></textarea>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mb-2">
                            <span>Subtotal</span>
                            <span id="summarySubtotal"><?php echo e(env('APP_CURRENCY_SYMBOL')); ?>0.00</span>
                        </div>

                        <hr>

                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="fw-semibold">Total Payable</span>
                            <span class="fs-4 fw-bold text-primary" id="summaryTotal"><?php echo e(env('APP_CURRENCY_SYMBOL')); ?>0.00</span>
                        </div>

                        <div class="row g-3">
                              <div class="col-12">
                                    <label for="orderDate" class="form-label">Order Date</label>
                                <input type="text" id="orderDate" name="sale_date" class="form-control" placeholder="Select date" autocomplete="off">
                             </div>
                        </div>
                    </div>
                    <div class="card-footer bg-body-tertiary d-grid gap-2">
                        <button type="button" class="btn btn-primary btn-lg" id="completeSaleButton">
                            <i class="bi bi-receipt me-2"></i>Complete Sale
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    flatpickr("#orderDate", {
        dateFormat: "d/m/Y",
        defaultDate: new Date(),
        allowInput: true
    });
});

document.addEventListener('DOMContentLoaded', () => {
    const appCurrency = "<?php echo e(env('APP_CURRENCY_SYMBOL')); ?>"; // from .env

    const formatCurrency = (value) => {
        const num = parseFloat(value) || 0;
        return appCurrency + num.toFixed(2);
    };

    const productCards = document.querySelectorAll('.product-card');
    const cartItemsBody = document.querySelector('#cartItems');
    const clearCartButton = document.querySelector('#clearCartButton');
    const summaryItems = document.querySelector('#summaryItems');
    const summarySubtotal = document.querySelector('#summarySubtotal');
    const summaryTotal = document.querySelector('#summaryTotal');
    const fuelChargesInput = document.querySelector('#fuelCharges');
    const otherChargesInput = document.querySelector('#otherCharges');
    const otherChargesDetailRow = document.querySelector('#otherChargesDetailRow');
    const completeSaleButton = document.querySelector('#completeSaleButton');

    const cart = {};

    // Show/Hide other Charges Detail
    otherChargesInput.addEventListener('input', () => {
        const value = parseFloat(otherChargesInput.value) || 0;
        if (value > 0) {
            otherChargesDetailRow.style.display = 'block';
        } else {
            otherChargesDetailRow.style.display = 'none';
            document.querySelector('#otherChargesDetail').value = '';
        }
    });

    const updateSummary = () => {
        const hasItems = Object.keys(cart).length > 0;
        let totalItems = 0;
        let subtotalItems = 0;

        Object.values(cart).forEach(item => {
            totalItems += item.quantity;
            subtotalItems += item.quantity * (item.price || 0);
        });

        const fuelCharges = parseFloat(fuelChargesInput.value) || 0;
        const otherCharges = parseFloat(otherChargesInput.value) || 0;

        // ⚡ Subtract fuel and other charges from total payable
        const totalPayable = subtotalItems - (fuelCharges + otherCharges);

        summaryItems.textContent = totalItems;
        summarySubtotal.textContent = formatCurrency(subtotalItems);
        summaryTotal.textContent = formatCurrency(totalPayable);

        clearCartButton.disabled = !hasItems;
        completeSaleButton.disabled = !hasItems;
    };


    const renderCart = () => {
        cartItemsBody.innerHTML = '';

        if (Object.keys(cart).length === 0) {
            cartItemsBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center text-secondary py-4">
                <i class="bi bi-info-circle me-2"></i>No product is selected.
            </td>
        </tr>
    `;
            updateSummary();
            return;
        }

        Object.values(cart).forEach(item => {
            const row = document.createElement('tr');
            row.dataset.sku = item.sku;
            row.innerHTML = `
                <td>
                    <div class="d-flex align-items-center gap-2">
                        <div>
                            <p class="mb-0 fw-semibold">${item.name}</p>
                            <small class="text-secondary">${item.packSizeName ?? 'Pack'} • ${item.packSizeQuantity ?? 0} bottles/pack</small>
                        </div>
                    </div>
                </td>
                <td class="text-center">
                    <div class="input-group input-group-sm">
                        <button class="btn btn-outline-secondary btn-decrease" type="button">-</button>
                        <input type="number" class="form-control quantity-input text-center" value="${item.quantity}" min="1">
                        <button class="btn btn-outline-secondary btn-increase" type="button">+</button>
                    </div>
                </td>
                <td class="text-end">
                    <input type="number" class="form-control form-control-sm price-input text-end" value="${item.price ? item.price.toFixed(2) : ''}" step="0.01" min="0" placeholder="0.00">
                </td>
                <td class="text-end fw-semibold item-subtotal">${formatCurrency(item.quantity * (item.price || 0))}</td>
                <td class="text-end">
                    <button class="btn btn-sm btn-outline-danger btn-remove-item"><i class="bi bi-x"></i></button>
                </td>
            `;
            cartItemsBody.appendChild(row);
        });

        updateSummary();
    };

    const handleProductAdd = (card) => {
        if (card.dataset.available === 'false') {
            alert(`"${card.dataset.name}" is out of stock!`);
            return;
        }

        const sku = card.dataset.sku;
        const name = card.dataset.name;
        const price = 0;
        const maxStock = parseInt(card.dataset.stock) || 0;
        const packSizeId = card.dataset.packSizeId || null;
        const packSizeName = card.dataset.packSizeName || 'Pack';
        const packSizeQuantity = parseInt(card.dataset.packQuantity) || 0;

        if (cart[sku]) {
            if (cart[sku].quantity + 1 > maxStock) {
                alert(`Only ${maxStock} pack(s) available in stock for "${name}"`);
                return;
            }
            cart[sku].quantity += 1;
        } else {
            if (!packSizeQuantity) {
                alert(`Pack size is not configured for "${name}".`);
                return;
            }
            if (maxStock < 1) {
                alert(`"${name}" is out of stock!`);
                return;
            }
            cart[sku] = {
                sku,
                name,
                price,
                quantity: 1,
                packSizeId,
                packSizeName,
                packSizeQuantity,
            };
        }

        renderCart();
    };

    productCards.forEach(card => {
        card.addEventListener('click', () => handleProductAdd(card));
    });

    cartItemsBody.addEventListener('click', (e) => {
        const row = e.target.closest('tr');
        if (!row) return;
        const sku = row.dataset.sku;
        const maxStock = parseInt(document.querySelector(`.product-card[data-sku="${sku}"]`).dataset.stock) || 0;

        if (e.target.closest('.btn-increase')) {
            if (cart[sku].quantity + 1 > maxStock) {
                alert(`Only ${maxStock} pack(s) available in stock for "${cart[sku].name}"`);
                return;
            }
            cart[sku].quantity += 1;
            renderCart();
        }

        if (e.target.closest('.btn-decrease')) {
            if (cart[sku].quantity > 1) {
                cart[sku].quantity -= 1;
                renderCart();
            }
        }

        if (e.target.closest('.btn-remove-item')) {
            delete cart[sku];
            renderCart();
        }
    });

    // Quantity input change
    cartItemsBody.addEventListener('input', (e) => {
        const row = e.target.closest('tr');
        if (!row) return;
        const sku = row.dataset.sku;

        if (e.target.classList.contains('quantity-input')) {
            let qty = parseInt(e.target.value) || 1;
            const maxStock = parseInt(document.querySelector(`.product-card[data-sku="${sku}"]`).dataset.stock) || 0;
            if (qty > maxStock) qty = maxStock;
            cart[sku].quantity = qty;
        }

        if (e.target.classList.contains('price-input')) {
            const price = parseFloat(e.target.value);
            cart[sku].price = isNaN(price) ? 0 : price;
            const subtotalCell = row.querySelector('.item-subtotal');
            if (subtotalCell) {
                subtotalCell.textContent = formatCurrency(cart[sku].quantity * (cart[sku].price || 0));
            }
            updateSummary();
            return;
        }

        renderCart();
    });

    // Charges input change
    [fuelChargesInput, otherChargesInput].forEach(input => {
        input.addEventListener('input', updateSummary);
    });

    clearCartButton.addEventListener('click', () => {
        for (let key in cart) delete cart[key];
        fuelChargesInput.value = '';
        otherChargesInput.value = '';
        document.querySelector('#otherChargesDetail').value = '';
        otherChargesDetailRow.style.display = 'none';
        renderCart();
    });

    renderCart();

    // ---- Complete Sale ----
    completeSaleButton.addEventListener('click', async () => {
        if (Object.keys(cart).length === 0) {
            alert('Cart is empty!');
            return;
        }
        const itemsWithoutPrice = Object.values(cart).filter(item => !item.price || item.price <= 0);
        if (itemsWithoutPrice.length > 0) {
            const names = itemsWithoutPrice.map(item => `"${item.name}"`).join(', ');
            alert(`Please enter a price for: ${names}.`);
            return;
        }
        const orderDateInput = document.querySelector('#orderDate');

        if (!orderDateInput.value) {
            if (orderDateInput._flatpickr) {
                orderDateInput._flatpickr.open();
            }
            alert('Please select a sale date before completing the sale.');
            return;
        }
        const otherCharges = parseFloat(otherChargesInput.value) || 0;
        const otherChargesDetail = document.querySelector('#otherChargesDetail').value.trim();
        if (otherCharges > 0 && otherChargesDetailRow.style.display !== 'none' && otherChargesDetail === '') {
            alert('Please fill in the Other Charges Detail before completing the sale.');
            document.querySelector('#otherChargesDetail').focus();
            return;
        }

        const confirmSale = confirm("Are you sure you want to complete this sale?");
        if (!confirmSale) return;

        const saleData = {
            _token: document.querySelector('meta[name="csrf-token"]').content,
            items: Object.values(cart).map(item => ({
                sku: item.sku,
                name: item.name,
                quantity: item.quantity,
                price: item.price,
                pack_size_id: item.packSizeId,
                pack_size_name: item.packSizeName,
                pack_size_quantity: item.packSizeQuantity,
                bottle_quantity: item.quantity * item.packSizeQuantity,
            })),
            fuel_charges: parseFloat(fuelChargesInput.value) || 0,
            other_charges: parseFloat(otherChargesInput.value) || 0,
            other_charges_detail: otherChargesDetailRow.style.display !== 'none' ? otherChargesDetail : '',

            total_amount: parseFloat(summaryTotal.textContent.replace(/[^0-9.-]+/g, "")) || 0,
            sale_date: document.querySelector('#orderDate').value
        };

        try {
            const response = await fetch("/store-pos", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": saleData._token
                },
                body: JSON.stringify(saleData)
            });

            const result = await response.json();

            if (result.status === "success") {
                alert("Sale completed successfully!");
                for (let key in cart) delete cart[key];
                fuelChargesInput.value = '';
                otherChargesInput.value = '';
                document.querySelector('#otherChargesDetail').value = '';
                otherChargesDetailRow.style.display = 'none';
                renderCart();
                window.location.reload();
            } else {
                alert("Error: " + result.message);
            }

        } catch (error) {
            console.error("Error completing sale:", error);
            alert("An error occurred while completing the sale.");
        }
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH F:\www\waterPOS\resources\views\POS\create.blade.php ENDPATH**/ ?>