<?php
session_start();
require_once '../assets/db_connect.php';

// Simple POS for testing
if (!isset($_SESSION['user']['shop_id'])) {
    die("Please login first");
}

$shop_id = (int)$_SESSION['user']['shop_id'];
$user_id = (int)$_SESSION['user']['id'];
?>
<!DOCTYPE html>
<html>
<head>
    <title>Simple POS Test</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .product { border: 1px solid #ccc; padding: 10px; margin: 5px; cursor: pointer; }
        .product:hover { background: #f0f0f0; }
        #cart { margin-top: 20px; border: 2px solid #333; padding: 10px; }
        .cart-item { margin: 5px 0; }
    </style>
</head>
<body>
    <h2>Simple POS Test</h2>
    
    <h3>Products:</h3>
    <div id="products">
        <?php
        $stmt = $pdo->prepare("
            SELECT p.id, p.name, p.sku, 
                   COALESCE(SUM(bs.current_qty), 0) as stock
            FROM products p
            LEFT JOIN batch_stock_view bs ON p.id = bs.product_id
            WHERE p.shop_id = ? AND p.is_active = 1
            GROUP BY p.id, p.name, p.sku
            LIMIT 5
        ");
        $stmt->execute([$shop_id]);
        while ($product = $stmt->fetch()) {
            echo "<div class='product' data-id='{$product['id']}' onclick='addToCart({$product['id']}, \"{$product['name']}\")'>
                    {$product['name']} ({$product['sku']}) - Stock: {$product['stock']}
                  </div>";
        }
        ?>
    </div>
    
    <div id="cart">
        <h3>Cart:</h3>
        <div id="cartItems"></div>
        <p>Total: <span id="cartTotal">0.00</span></p>
        <button onclick="checkout()">Checkout</button>
    </div>
    
    <div id="result"></div>
    
    <script>
    let cart = [];
    
    function addToCart(productId, productName) {
        cart.push({
            product_id: productId,
            name: productName,
            price: 100, // Fixed price for testing
            qty: 1
        });
        updateCartDisplay();
    }
    
    function updateCartDisplay() {
        const cartItems = document.getElementById('cartItems');
        const cartTotal = document.getElementById('cartTotal');
        
        let html = '';
        let total = 0;
        
        cart.forEach((item, index) => {
            const itemTotal = item.price * item.qty;
            total += itemTotal;
            html += `<div class="cart-item">
                        ${item.name} - ${item.price} × ${item.qty} = ${itemTotal}
                        <button onclick="removeFromCart(${index})">Remove</button>
                     </div>`;
        });
        
        cartItems.innerHTML = html;
        cartTotal.textContent = total.toFixed(2);
    }
    
    function removeFromCart(index) {
        cart.splice(index, 1);
        updateCartDisplay();
    }
    
    function checkout() {
        if (cart.length === 0) {
            alert('Cart is empty');
            return;
        }
        
        const formData = new FormData();
        formData.append('shop_id', <?= $shop_id ?>);
        formData.append('created_by', <?= $user_id ?>);
        formData.append('payment_method', 'CASH');
        formData.append('paid', document.getElementById('cartTotal').textContent);
        
        cart.forEach((item, index) => {
            formData.append(`items[${index}][product_id]`, item.product_id);
            formData.append(`items[${index}][batch_id]`, 4); // Using batch 4 for testing
            formData.append(`items[${index}][qty]`, item.qty);
            formData.append(`items[${index}][unit_price]`, item.price);
            formData.append(`items[${index}][discount]`, 0);
        });
        
        fetch('save_sale.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('result').innerHTML = 
                `<h3>Result:</h3><pre>${JSON.stringify(data, null, 2)}</pre>`;
            if (data.status === 'success') {
                cart = [];
                updateCartDisplay();
                alert('Sale completed!');
            }
        })
        .catch(error => {
            document.getElementById('result').innerHTML = 
                `<h3>Error:</h3><p>${error}</p>`;
        });
    }
    </script>
</body>
</html>