<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="<?php echo $locale; ?>">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title><?php echo $title; ?> - <?php echo get_option('companyname'); ?></title>
    <link href="<?php echo base_url('assets/css/reset.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/plugins/roboto/roboto.css'); ?>" rel="stylesheet">
    <link href="<?php echo module_dir_url('pos', 'assets/css/pos.css'); ?>" rel="stylesheet">
    <style>
        body { background: #f4f4f4; overflow: hidden; }
        .pos-container { height: 100vh; display: flex; flex-direction: column; }
        .pos-header { background: #2c3e50; color: white; padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; }
        .pos-body { flex: 1; display: flex; overflow: hidden; }
        .pos-left { width: 65%; background: white; padding: 20px; overflow-y: auto; }
        .pos-right { width: 35%; background: #ecf0f1; padding: 20px; overflow-y: auto; border-left: 2px solid #bdc3c7; }
        .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; margin-top: 20px; }
        .product-card { background: white; border: 2px solid #e0e0e0; border-radius: 8px; padding: 15px; text-align: center; cursor: pointer; transition: all 0.3s; }
        .product-card:hover { border-color: #3498db; transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        .product-card h4 { font-size: 14px; margin: 10px 0 5px; color: #2c3e50; }
        .product-card .price { font-size: 18px; font-weight: bold; color: #27ae60; }
        .search-box { width: 100%; padding: 15px; font-size: 16px; border: 2px solid #3498db; border-radius: 8px; margin-bottom: 10px; }
        .cart-table { width: 100%; margin-bottom: 20px; }
        .cart-table th { background: #34495e; color: white; padding: 10px; text-align: left; }
        .cart-table td { padding: 10px; border-bottom: 1px solid #ddd; }
        .cart-item-qty { width: 60px; text-align: center; border: 1px solid #ddd; padding: 5px; }
        .cart-totals { background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; }
        .cart-totals .row { display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 16px; }
        .cart-totals .total-row { font-size: 24px; font-weight: bold; color: #27ae60; padding-top: 10px; border-top: 2px solid #27ae60; }
        .btn-action { width: 100%; padding: 15px; font-size: 18px; margin-bottom: 10px; border: none; border-radius: 8px; cursor: pointer; }
        .btn-checkout { background: #27ae60; color: white; }
        .btn-clear { background: #e74c3c; color: white; }
        .btn-cash-movement { background: #f39c12; color: white; }
        .empty-cart { text-align: center; padding: 50px; color: #95a5a6; }
        .session-info { font-size: 14px; }
        .session-info span { margin-left: 20px; }
    </style>
</head>
<body>
    <div class="pos-container">
        <!-- Header -->
        <div class="pos-header">
            <div>
                <h3 style="margin: 0;"><?php echo _l('pos_screen'); ?></h3>
                <div class="session-info">
                    <span><i class="fa fa-desktop"></i> <?php echo $register->name; ?></span>
                    <span><i class="fa fa-building"></i> <?php echo $register->branch_name; ?></span>
                    <span><i class="fa fa-user"></i> <?php echo get_staff_full_name(get_staff_user_id()); ?></span>
                </div>
            </div>
            <div>
                <button class="btn btn-warning btn-sm" onclick="openCashMovement()">
                    <i class="fa fa-money"></i> <?php echo _l('pos_cash_movement'); ?>
                </button>
                <a href="<?php echo admin_url('pos/close_session/' . $session->id); ?>" class="btn btn-danger btn-sm">
                    <i class="fa fa-lock"></i> <?php echo _l('pos_close_session'); ?>
                </a>
                <a href="<?php echo admin_url('pos/dashboard'); ?>" class="btn btn-default btn-sm">
                    <i class="fa fa-home"></i> <?php echo _l('pos_back'); ?>
                </a>
            </div>
        </div>

        <!-- Body -->
        <div class="pos-body">
            <!-- Left: Products -->
            <div class="pos-left">
                <input type="text" id="search-products" class="search-box" 
                       placeholder="<?php echo _l('pos_search_products'); ?>" 
                       onkeyup="searchProducts(this.value)">
                
                <div class="product-grid" id="products-grid">
                    <!-- Products will be loaded here via JavaScript -->
                </div>
            </div>

            <!-- Right: Cart -->
            <div class="pos-right">
                <h4><?php echo _l('pos_cart'); ?></h4>
                
                <div id="cart-items">
                    <div class="empty-cart">
                        <i class="fa fa-shopping-cart" style="font-size: 60px;"></i>
                        <p><?php echo _l('pos_empty_cart'); ?></p>
                    </div>
                </div>

                <div class="cart-totals" id="cart-totals" style="display: none;">
                    <div class="row">
                        <span><?php echo _l('pos_subtotal'); ?>:</span>
                        <span id="subtotal">0.00</span>
                    </div>
                    <div class="row">
                        <span><?php echo _l('pos_tax'); ?> (<span id="tax-rate">15</span>%):</span>
                        <span id="tax">0.00</span>
                    </div>
                    <div class="row">
                        <span><?php echo _l('pos_discount'); ?>:</span>
                        <span id="discount">0.00</span>
                    </div>
                    <div class="row total-row">
                        <span><?php echo _l('pos_total'); ?>:</span>
                        <span id="total">0.00</span>
                    </div>
                </div>

                <button class="btn-action btn-checkout" onclick="checkout()" style="display: none;" id="btn-checkout">
                    <i class="fa fa-credit-card"></i> <?php echo _l('pos_checkout'); ?>
                </button>
                <button class="btn-action btn-clear" onclick="clearCart()" style="display: none;" id="btn-clear">
                    <i class="fa fa-trash"></i> <?php echo _l('pos_clear_cart'); ?>
                </button>
            </div>
        </div>
    </div>

    <!-- Checkout Modal -->
    <div class="modal fade" id="checkoutModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"><?php echo _l('pos_checkout'); ?></h4>
                </div>
                <div class="modal-body">
                    <h3 class="text-center"><?php echo _l('pos_total'); ?>: <span id="modal-total">0.00</span></h3>
                    <hr>
                    <div class="form-group">
                        <label><?php echo _l('pos_payment_method'); ?></label>
                        <select id="payment-method" class="form-control" onchange="handlePaymentMethod()">
                            <option value="cash"><?php echo _l('pos_cash'); ?></option>
                            <option value="card"><?php echo _l('pos_card'); ?></option>
                            <option value="mixed"><?php echo _l('pos_mixed'); ?></option>
                        </select>
                    </div>
                    <div id="cash-section">
                        <div class="form-group">
                            <label><?php echo _l('pos_paid'); ?></label>
                            <input type="number" step="0.01" id="paid-amount" class="form-control" onkeyup="calculateChange()">
                        </div>
                        <div class="form-group">
                            <label><?php echo _l('pos_change'); ?></label>
                            <input type="text" id="change-amount" class="form-control" readonly>
                        </div>
                    </div>
                    <div id="card-section" style="display:none;">
                        <div class="form-group">
                            <label><?php echo _l('pos_card'); ?> <?php echo _l('pos_total'); ?></label>
                            <input type="number" step="0.01" id="card-amount" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo _l('pos_cancel'); ?></button>
                    <button type="button" class="btn btn-success btn-lg" onclick="completeSale()">
                        <i class="fa fa-check"></i> <?php echo _l('pos_complete_sale'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        var admin_url = '<?php echo admin_url(); ?>';
    </script>
    <script src="<?php echo base_url('assets/plugins/jquery/jquery.min.js'); ?>"></script>
    <script src="<?php echo base_url('assets/plugins/bootstrap/js/bootstrap.min.js'); ?>"></script>
    <script>
        var cart = [];
        var products = [];

        // Load products on page load
        $(document).ready(function() {
            loadProducts('');
        });

        function searchProducts(keyword) {
            if (keyword.length >= 2 || keyword.length === 0) {
                loadProducts(keyword);
            }
        }

        function loadProducts(keyword) {
            var branchId = <?php echo $session->branch_id; ?>;
            var warehouseId = <?php echo isset($register->warehouse_id) ? $register->warehouse_id : 'null'; ?>;
            
            $.get(admin_url + 'pos/search_products?keyword=' + keyword + 
                  '&branch_id=' + branchId + 
                  '&warehouse_id=' + warehouseId, function(data) {
                products = JSON.parse(data);
                displayProducts(products);
            });
        }

        function displayProducts(prods) {
            var html = '';
            prods.forEach(function(product) {
                html += '<div class="product-card" onclick="addToCart(' + product.id + ')">';
                html += '<i class="fa fa-cube" style="font-size: 30px; color: #3498db;"></i>';
                html += '<h4>' + product.description + '</h4>';
                html += '<div class="price">' + parseFloat(product.rate).toFixed(2) + '</div>';
                html += '</div>';
            });
            $('#products-grid').html(html || '<p class="text-center text-muted">لا توجد منتجات</p>');
        }

        function addToCart(productId) {
            var product = products.find(p => p.id == productId);
            if (!product) return;

            var cartItem = cart.find(item => item.id == productId);
            if (cartItem) {
                cartItem.quantity++;
            } else {
                cart.push({
                    id: product.id,
                    name: product.description,
                    price: parseFloat(product.rate),
                    quantity: 1
                });
            }
            updateCart();
        }

        function removeFromCart(productId) {
            cart = cart.filter(item => item.id != productId);
            updateCart();
        }

        function updateQuantity(productId, quantity) {
            var cartItem = cart.find(item => item.id == productId);
            if (cartItem && quantity > 0) {
                cartItem.quantity = parseInt(quantity);
                updateCart();
            }
        }

        function updateCart() {
            if (cart.length === 0) {
                $('#cart-items').html('<div class="empty-cart"><i class="fa fa-shopping-cart" style="font-size: 60px;"></i><p><?php echo _l("pos_empty_cart"); ?></p></div>');
                $('#cart-totals, #btn-checkout, #btn-clear').hide();
                return;
            }

            var html = '<table class="cart-table"><thead><tr><th><?php echo _l("pos_product_name"); ?></th><th><?php echo _l("pos_quantity"); ?></th><th><?php echo _l("pos_price"); ?></th><th><?php echo _l("pos_item_total"); ?></th><th></th></tr></thead><tbody>';
            
            var subtotal = 0;
            cart.forEach(function(item) {
                var itemTotal = item.price * item.quantity;
                subtotal += itemTotal;
                html += '<tr>';
                html += '<td>' + item.name + '</td>';
                html += '<td><input type="number" class="cart-item-qty" value="' + item.quantity + '" min="1" onchange="updateQuantity(' + item.id + ', this.value)"></td>';
                html += '<td>' + item.price.toFixed(2) + '</td>';
                html += '<td>' + itemTotal.toFixed(2) + '</td>';
                html += '<td><button class="btn btn-sm btn-danger" onclick="removeFromCart(' + item.id + ')"><i class="fa fa-trash"></i></button></td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
            $('#cart-items').html(html);

            var taxRate = 15;
            var tax = subtotal * (taxRate / 100);
            var total = subtotal + tax;

            $('#subtotal').text(subtotal.toFixed(2));
            $('#tax').text(tax.toFixed(2));
            $('#total').text(total.toFixed(2));
            $('#cart-totals, #btn-checkout, #btn-clear').show();
        }

        function clearCart() {
            if (confirm('<?php echo _l("pos_confirm_clear_cart"); ?>')) {
                cart = [];
                updateCart();
            }
        }

        function checkout() {
            var total = parseFloat($('#total').text());
            $('#modal-total').text(total.toFixed(2));
            $('#paid-amount').val(total.toFixed(2));
            calculateChange();
            $('#checkoutModal').modal('show');
        }

        function handlePaymentMethod() {
            var method = $('#payment-method').val();
            if (method === 'cash') {
                $('#cash-section').show();
                $('#card-section').hide();
            } else if (method === 'card') {
                $('#cash-section').hide();
                $('#card-section').show();
            } else {
                $('#cash-section').show();
                $('#card-section').show();
            }
        }

        function calculateChange() {
            var total = parseFloat($('#modal-total').text());
            var paid = parseFloat($('#paid-amount').val()) || 0;
            var change = paid - total;
            $('#change-amount').val(change >= 0 ? change.toFixed(2) : '0.00');
        }

        function completeSale() {
            var subtotal = parseFloat($('#subtotal').text());
            var tax = parseFloat($('#tax').text());
            var total = parseFloat($('#total').text());
            var paymentMethod = $('#payment-method').val();
            var paid = parseFloat($('#paid-amount').val()) || 0;
            var cashAmount = paymentMethod === 'cash' ? paid : 0;
            var cardAmount = paymentMethod === 'card' ? $('#card-amount').val() : 0;

            if (paid < total && paymentMethod === 'cash') {
                alert('<?php echo _l("pos_insufficient_payment"); ?>');
                return;
            }

            var warehouseId = <?php echo isset($register->warehouse_id) ? $register->warehouse_id : 'null'; ?>;
            
            var saleData = {
                subtotal: subtotal,
                tax_amount: tax,
                discount_amount: 0,
                total: total,
                payment_method: paymentMethod,
                cash_amount: cashAmount,
                card_amount: cardAmount,
                other_amount: 0,
                paid_amount: paid,
                change_amount: paid - total,
                warehouse_id: warehouseId,
                items: JSON.stringify(cart.map(item => ({
                    product_id: item.id,
                    product_name: item.name,
                    quantity: item.quantity,
                    unit_price: item.price,
                    tax_rate: 15,
                    tax_amount: (item.price * item.quantity * 0.15),
                    discount_rate: 0,
                    discount_amount: 0,
                    subtotal: item.price * item.quantity,
                    total: (item.price * item.quantity) * 1.15
                })))
            };

            $.post(admin_url + 'pos/create_sale', saleData, function(response) {
                var result = JSON.parse(response);
                if (result.success) {
                    // Open receipt in new window
                    window.open(admin_url + 'pos/receipt/' + result.sale_id, '_blank');
                    
                    $('#checkoutModal').modal('hide');
                    cart = [];
                    updateCart();
                } else {
                    alert(result.message || 'حدث خطأ أثناء إتمام العملية');
                }
            });
        }

        function openCashMovement() {
            // Add cash movement functionality
            alert('Cash Movement - To be implemented');
        }
    </script>
</body>
</html>
