<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('pos_access');

$pdo = getDB();
$customers = $pdo->query("SELECT * FROM customers WHERE status=1 ORDER BY name")->fetchAll();
$categories = $pdo->query("SELECT * FROM categories WHERE status=1 ORDER BY category_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-shopping-cart me-2"></i>Point of Sale</h4>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="pos-container">
            <!-- Left: Products -->
            <div class="pos-products">
                <div class="card">
                    <div class="card-body">
                        <div class="pos-search mb-3">
                            <i class="fas fa-search"></i>
                            <input type="text" class="form-control" id="productSearch" placeholder="Search by name, barcode, SKU, or IMEI..." onkeyup="searchProduct(this.value)">
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <select class="form-select" id="categoryFilter" onchange="filterByCategory()">
                                    <option value="">All Categories</option>
                                    <?php foreach ($categories as $c): ?>
                                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['category_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <select class="form-select" id="typeFilter" onchange="filterByCategory()">
                                    <option value="">All Types</option>
                                    <option value="phone">Phones</option>
                                    <option value="accessory">Accessories</option>
                                    <option value="spare_part">Spare Parts</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <button class="btn btn-secondary w-100" onclick="loadAllProducts()"><i class="fas fa-sync me-1"></i>Reload</button>
                            </div>
                        </div>
                        <div id="productLoader" class="text-center py-4" style="display:none;">
                            <div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>
                            <p class="text-muted mt-2">Loading products...</p>
                        </div>
                        <div id="productError" class="alert alert-danger" style="display:none;"></div>
                        <div class="product-grid" id="productGrid">
                            <div class="empty-state col-12"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading products...</p></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right: Cart -->
            <div class="pos-cart">
                <div class="card">
                    <div class="card-header d-flex justify-content-between">
                        <span><i class="fas fa-shopping-basket me-1"></i>Cart (<span id="cartCount">0</span>)</span>
                        <div>
                            <button class="btn btn-sm btn-warning" onclick="holdSale()"><i class="fas fa-pause"></i></button>
                            <button class="btn btn-sm btn-danger" id="clearCart"><i class="fas fa-trash"></i></button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="cart-items" id="cartItems">
                            <p class="text-muted text-center">Cart is empty</p>
                        </div>

                        <div class="cart-summary mt-3">
                            <div class="d-flex justify-content-between"><span>Subtotal:</span><strong id="cartSubtotal">0.00</strong></div>
                            <hr>
                            <div class="row mb-2">
                                <div class="col-6">
                                    <label class="form-label small">Customer *</label>
                                    <select class="form-select form-select-sm" id="saleCustomer">
                                        <option value="">Walk-in Customer</option>
                                        <?php foreach ($customers as $c): ?>
                                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?> (<?= htmlspecialchars($c['phone']) ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <button class="btn btn-sm btn-outline-primary mt-4" data-bs-toggle="modal" data-bs-target="#quickCustomerModal"><i class="fas fa-plus"></i> Quick Add</button>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-6">
                                    <label class="form-label small">Discount</label>
                                    <div class="input-group input-group-sm">
                                        <select class="form-select form-select-sm" id="discountType" style="max-width:70px;">
                                            <option value="Percentage">%</option>
                                            <option value="Fixed">Rs.</option>
                                        </select>
                                        <input type="number" class="form-control form-control-sm" id="discountValue" value="0" min="0" oninput="updatePosTotals()">
                                    </div>
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Tax</label>
                                    <div class="input-group input-group-sm">
                                        <select class="form-select form-select-sm" id="taxType" style="max-width:70px;">
                                            <option value="Percentage">%</option>
                                            <option value="Fixed">Rs.</option>
                                        </select>
                                        <input type="number" class="form-control form-control-sm" id="taxValue" value="0" min="0" oninput="updatePosTotals()">
                                    </div>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-6">
                                    <label class="form-label small">Payment Method</label>
                                    <select class="form-select form-select-sm" id="salePaymentMethod">
                                        <option value="Cash">Cash</option>
                                        <option value="Card">Card</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Online Payment">Online Payment</option>
                                        <option value="Partial">Partial</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label small">Paid Amount</label>
                                    <input type="number" step="0.01" class="form-control form-control-sm" id="salePaidAmount" value="0" oninput="updatePosTotals()">
                                </div>
                            </div>
                            <hr>
                            <div class="d-flex justify-content-between"><span>Discount:</span><span id="posDiscount">0.00</span></div>
                            <div class="d-flex justify-content-between"><span>Tax:</span><span id="posTax">0.00</span></div>
                            <div class="d-flex justify-content-between fs-5 fw-bold"><span>Total:</span><span id="posTotal">0.00</span></div>
                            <div class="d-flex justify-content-between text-danger"><span>Balance:</span><span id="posBalance">0.00</span></div>
                            <hr>
                            <div class="d-grid gap-2">
                                <button class="btn btn-success" onclick="saveSale()"><i class="fas fa-save me-1"></i>Save Invoice</button>
                                <button class="btn btn-primary" onclick="saveAndPrint()"><i class="fas fa-print me-1"></i>Save & Print</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- IMEI Selection Modal -->
<div class="modal fade" id="imeiModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Select IMEI - <span id="selectProductName"></span></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" id="selectProductId">
                <input type="hidden" id="selectSellingPrice">
                <div id="imeiList" class="mb-3"></div>
                <div class="mb-3">
                    <label class="form-label">Price</label>
                    <input type="number" step="0.01" class="form-control" id="imeiPrice" value="0">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="confirmImeiSelect">Add to Cart</button>
            </div>
        </div>
    </div>
</div>

<!-- Quick Customer Modal -->
<div class="modal fade" id="quickCustomerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="quickCustomerForm">
                <div class="modal-header"><h5 class="modal-title">Quick Add Customer</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Name *</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone *</label>
                        <input type="text" name="phone" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Customer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="<?= BASE_URL ?>assets/js/pos.js"></script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
