<?php
// modules/sales/pos.php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';

if ($shop_id == 0 || $user_id == 0) {
    die("Shop session missing.");
}

// Get shop info
$shop_stmt = $pdo->prepare("SELECT * FROM shops WHERE id = ?");
$shop_stmt->execute([$shop_id]);
$shop = $shop_stmt->fetch(PDO::FETCH_ASSOC);

// Get recent customers
$customers_stmt = $pdo->prepare("SELECT * FROM customers WHERE shop_id = ? ORDER BY created_at DESC LIMIT 10");
$customers_stmt->execute([$shop_id]);
$recent_customers = $customers_stmt->fetchAll(PDO::FETCH_ASSOC);

// Generate invoice number
$invoice_no = "SHOP{$shop_id}-" . date('Ymd-His') . "-" . rand(100, 999);
?>
<style>
/* POS System Styles */
.main-content-wrapper {
    padding: 20px;
    min-height: calc(100vh - 80px);
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.pos-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    height: 85vh;
}

@media (max-width: 1200px) {
    .pos-container {
        grid-template-columns: 1fr;
        height: auto;
    }
}

.pos-left {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.pos-right {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: transform 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

.card-header {
    border-radius: 12px 12px 0 0 !important;
    background: linear-gradient(135deg, #007bff, #6610f2);
    color: white;
    font-weight: 600;
}

.card-header.bg-success {
    background: linear-gradient(135deg, #28a745, #20c997);
}

.card-header.bg-info {
    background: linear-gradient(135deg, #17a2b8, #007bff);
}

.product-search {
    position: relative;
}

.product-search .search-icon {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #6c757d;
}

.product-search input {
    padding-left: 45px;
    border-radius: 8px;
}

.scrollable {
    overflow-y: auto;
    overflow-x: hidden;
}

.product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
    padding: 5px;
}

.product-item {
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    overflow: hidden;
}

.product-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    border-color: #007bff;
}

.product-item.active {
    border-color: #28a745;
    background: #f8fff9;
}

.product-name {
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 4px;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-sku {
    font-size: 11px;
    color: #6c757d;
    background: #f8f9fa;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
}

.product-price {
    font-weight: bold;
    color: #28a745;
    margin-top: 8px;
    font-size: 15px;
}

.product-stock {
    position: absolute;
    top: 8px;
    right: 8px;
    font-size: 11px;
    background: #e9ecef;
    padding: 2px 6px;
    border-radius: 4px;
    color: #495057;
}

.product-stock.low {
    background: #ffeaa7;
    color: #d63031;
}

.product-stock.out {
    background: #ff6b6b;
    color: white;
}

.cart-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: white;
    border-bottom: 1px solid #e0e0e0;
    border-radius: 12px 12px 0 0;
}

.cart-body {
    flex: 1;
    overflow-y: auto;
    background: white;
}

.cart-footer {
    background: white;
    border-top: 1px solid #e0e0e0;
    padding: 20px;
    border-radius: 0 0 12px 12px;
}

.cart-table {
    width: 100%;
    border-collapse: collapse;
}

.cart-table th {
    background: #f8f9fa;
    padding: 12px 15px;
    font-weight: 600;
    color: #495057;
    border-bottom: 2px solid #dee2e6;
    font-size: 14px;
    text-align: left;
}

.cart-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e9ecef;
    vertical-align: middle;
}

.cart-table tr:hover {
    background: #f8f9fa;
}

.cart-table .product-cell {
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.cart-table .qty-cell {
    width: 120px;
}

.cart-table .price-cell {
    width: 100px;
}

.cart-table .total-cell {
    width: 100px;
    font-weight: bold;
}

.cart-table .action-cell {
    width: 80px;
}

.qty-control {
    display: flex;
    align-items: center;
    gap: 8px;
}

.qty-btn {
    width: 28px;
    height: 28px;
    border-radius: 4px;
    border: 1px solid #dee2e6;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
}

.qty-btn:hover {
    background: #f8f9fa;
    border-color: #adb5bd;
}

.qty-input {
    width: 50px;
    text-align: center;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 4px;
    font-size: 14px;
}

.delete-btn {
    width: 28px;
    height: 28px;
    border-radius: 4px;
    border: none;
    background: #ff6b6b;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
}

.delete-btn:hover {
    background: #ff5252;
    transform: scale(1.1);
}

.totals-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.totals-table tr {
    border-bottom: 1px solid #e9ecef;
}

.totals-table td {
    padding: 8px 0;
}

.totals-table .label {
    color: #6c757d;
}

.totals-table .value {
    text-align: right;
    font-weight: 600;
}

.totals-table .total-row td {
    padding: 12px 0;
    border-top: 2px solid #dee2e6;
    font-size: 18px;
}

.customer-section {
    position: relative;
}

.customer-selector {
    position: relative;
}

.customer-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    z-index: 1000;
    display: none;
    max-height: 300px;
    overflow-y: auto;
}

.customer-item {
    padding: 10px 15px;
    cursor: pointer;
    border-bottom: 1px solid #e9ecef;
    transition: background 0.2s;
}

.customer-item:hover {
    background: #f8f9fa;
}

.customer-item:last-child {
    border-bottom: none;
}

.customer-name {
    font-weight: 600;
    color: #333;
    margin-bottom: 2px;
}

.customer-phone {
    font-size: 12px;
    color: #6c757d;
}

.action-buttons {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-top: 20px;
}

.btn-pos {
    padding: 12px;
    border-radius: 8px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.btn-pos:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.btn-pos.btn-success {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;
}

.btn-pos.btn-success:hover {
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.btn-pos.btn-danger {
    background: linear-gradient(135deg, #dc3545, #e83e8c);
    color: white;
}

.btn-pos.btn-danger:hover {
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
}

.btn-pos.btn-warning {
    background: linear-gradient(135deg, #ffc107, #fd7e14);
    color: #212529;
}

.btn-pos.btn-warning:hover {
    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
}

.btn-pos.btn-info {
    background: linear-gradient(135deg, #17a2b8, #007bff);
    color: white;
}

.btn-pos.btn-info:hover {
    box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
}

.btn-pos:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none !important;
    box-shadow: none !important;
}

/* Modal Styles */
.modal-xl {
    max-width: 95%;
}

.modal-body {
    max-height: 70vh;
    overflow-y: auto;
}

/* Batch Selection */
.batch-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 10px;
    margin-top: 15px;
}

.batch-item {
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    background: white;
}

.batch-item:hover {
    border-color: #007bff;
    transform: translateY(-2px);
}

.batch-item.selected {
    border-color: #28a745;
    background: #f8fff9;
}

.batch-info {
    margin-bottom: 5px;
}

.batch-no {
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.batch-stock {
    font-size: 12px;
    color: #6c757d;
    margin: 3px 0;
}

.batch-stock.low {
    color: #ff6b6b;
}

.batch-price {
    font-weight: bold;
    color: #28a745;
    font-size: 14px;
}

.batch-expiry {
    font-size: 11px;
    color: #adb5bd;
    margin-top: 3px;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 10px;
    }
    
    .pos-container {
        gap: 15px;
    }
    
    .product-grid {
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    }
    
    .cart-table th,
    .cart-table td {
        padding: 8px 10px;
        font-size: 13px;
    }
    
    .action-buttons {
        grid-template-columns: 1fr;
    }
    
    .modal-xl {
        max-width: 100%;
        margin: 10px;
    }
}

/* Loading States */
.loading {
    position: relative;
    opacity: 0.7;
    pointer-events: none;
}

.loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* Receipt Preview */
.receipt-preview {
    font-family: 'Courier New', monospace;
    background: white;
    padding: 20px;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    max-width: 400px;
    margin: 0 auto;
}

.receipt-header {
    text-align: center;
    border-bottom: 2px dashed #dee2e6;
    padding-bottom: 15px;
    margin-bottom: 15px;
}

.receipt-header h4 {
    margin: 0;
    font-weight: bold;
    color: #333;
}

.receipt-header p {
    margin: 5px 0;
    font-size: 12px;
    color: #666;
}

.receipt-items {
    margin-bottom: 15px;
}

.receipt-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
}

.receipt-item .qty {
    flex: 0 0 30px;
    text-align: center;
}

.receipt-item .name {
    flex: 1;
    padding: 0 10px;
}

.receipt-item .price {
    flex: 0 0 80px;
    text-align: right;
}

.receipt-totals {
    border-top: 2px dashed #dee2e6;
    padding-top: 15px;
    margin-top: 15px;
}

.receipt-total-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
}

.receipt-total-row.total {
    font-weight: bold;
    font-size: 16px;
    border-top: 1px solid #dee2e6;
    padding-top: 10px;
    margin-top: 10px;
}

.receipt-footer {
    text-align: center;
    margin-top: 20px;
    padding-top: 15px;
    border-top: 2px dashed #dee2e6;
    font-size: 12px;
    color: #666;
}
</style>

<!-- MAIN CONTENT -->
<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="text-success mb-0">
                    <i class="fas fa-cash-register"></i> Point of Sale (POS)
                </h3>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb bg-transparent p-0">
                        <li class="breadcrumb-item"><a href="../dashboard.php">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="list_sales.php">Sales</a></li>
                        <li class="breadcrumb-item active">New Sale</li>
                    </ol>
                </nav>
            </div>
            <div>
                <span class="badge badge-info mr-3">
                    <i class="fas fa-store"></i> <?= htmlspecialchars($shop['name']) ?>
                </span>
                <button type="button" class="btn btn-secondary" onclick="window.history.back()">
                    <i class="fas fa-arrow-left"></i> Back
                </button>
            </div>
        </div>

        <!-- POS System -->
        <div class="pos-container">
            <!-- Left Column: Products -->
            <div class="pos-left">
                <!-- Product Search -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-search"></i> Search Products
                    </div>
                    <div class="card-body">
                        <div class="product-search">
                            <i class="fas fa-search search-icon"></i>
                            <input type="text" id="productSearch" class="form-control" 
                                   placeholder="Type product name, SKU, or category..."
                                   autocomplete="off">
                        </div>
                        <div class="mt-2">
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-secondary active" 
                                        onclick="setProductFilter('all')">All</button>
                                <button type="button" class="btn btn-outline-secondary" 
                                        onclick="setProductFilter('in_stock')">In Stock</button>
                                <button type="button" class="btn btn-outline-secondary" 
                                        onclick="setProductFilter('category', 'Anti-pain')">Anti-pain</button>
                                <button type="button" class="btn btn-outline-secondary" 
                                        onclick="setProductFilter('category', 'Antibiotic')">Antibiotic</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Products Grid -->
                <div class="card flex-fill">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-boxes"></i> Products
                            <small id="productCount" class="text-white ml-2">0</small>
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-light" onclick="refreshProducts()">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body scrollable p-3" id="productsContainer">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading products...</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Column: Cart and Checkout -->
            <div class="pos-right">
                <!-- Cart -->
                <div class="card flex-fill cart-container">
                    <div class="card-header bg-success">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <i class="fas fa-shopping-cart"></i> Shopping Cart
                                <small id="cartCount" class="text-white ml-2">0 items</small>
                            </div>
                            <div>
                                <button type="button" class="btn btn-sm btn-light" onclick="clearCart()">
                                    <i class="fas fa-trash"></i> Clear All
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body scrollable p-0">
                        <table class="cart-table" id="cartTable">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th class="text-center">Batch</th>
                                    <th class="text-center">Qty</th>
                                    <th class="text-center">Price</th>
                                    <th class="text-center">Total</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="cartBody">
                                <tr id="emptyCart">
                                    <td colspan="6" class="text-center py-5">
                                        <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                                        <h5 class="text-muted">Your cart is empty</h5>
                                        <p class="text-muted small">Add products from the list on the left</p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer">
                        <table class="totals-table">
                            <tr>
                                <td class="label">Subtotal:</td>
                                <td class="value" id="cartSubtotal">TZS 0.00</td>
                            </tr>
                            <tr>
                                <td class="label">Tax:</td>
                                <td class="value" id="cartTax">TZS 0.00</td>
                            </tr>
                            <tr>
                                <td class="label">Discount:</td>
                                <td class="value" id="cartDiscount">TZS 0.00</td>
                            </tr>
                            <tr class="total-row">
                                <td class="label"><strong>TOTAL:</strong></td>
                                <td class="value"><strong id="cartTotal">TZS 0.00</strong></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Customer & Checkout -->
                <div class="card">
                    <div class="card-header bg-info">
                        <i class="fas fa-user"></i> Customer & Checkout
                    </div>
                    <div class="card-body">
                        <!-- Customer Selection -->
                        <div class="customer-section mb-3">
                            <label class="form-label"><i class="fas fa-user"></i> Customer</label>
                            <div class="customer-selector">
                                <input type="text" id="customerSearch" class="form-control" 
                                       placeholder="Type customer name (or select from list)..." 
                                       autocomplete="off">
                                <div class="customer-dropdown" id="customerDropdown">
                                    <?php foreach($recent_customers as $customer): ?>
                                        <div class="customer-item" onclick="selectCustomer(<?= $customer['id'] ?>, '<?= htmlspecialchars($customer['name']) ?>')">
                                            <div class="customer-name"><?= htmlspecialchars($customer['name']) ?></div>
                                            <?php if($customer['phone']): ?>
                                                <div class="customer-phone"><?= htmlspecialchars($customer['phone']) ?></div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                    <div class="customer-item text-primary" onclick="showNewCustomerModal()">
                                        <i class="fas fa-plus"></i> Add New Customer to Database
                                    </div>
                                    <div class="customer-item text-success" onclick="useTemporaryCustomer()">
                                        <i class="fas fa-user-clock"></i> Use as Temporary Customer
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" id="customerId" value="">
                            <small class="text-muted mt-1 d-block" id="selectedCustomer">
                                No customer selected (can type any name)
                            </small>
                        </div>

                        <!-- Discount -->
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-tag"></i> Discount</label>
                            <div class="input-group">
                                <input type="number" id="discountAmount" class="form-control" 
                                       placeholder="0" min="0" step="0.01" value="0">
                                <div class="input-group-append">
                                    <select id="discountType" class="form-control" style="width: 120px;">
                                        <option value="fixed">TZS Fixed</option>
                                        <option value="percent">% Percent</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Payment Method -->
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-money-check-alt"></i> Payment Method</label>
                            <div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
                                <label class="btn btn-outline-success active">
                                    <input type="radio" name="paymentMethod" value="CASH" checked> CASH
                                </label>
                                <label class="btn btn-outline-primary">
                                    <input type="radio" name="paymentMethod" value="M-PESA"> M-PESA
                                </label>
                                <label class="btn btn-outline-primary">
                                    <input type="radio" name="paymentMethod" value="TIGO-PESA"> TIGO-PESA
                                </label>
                                <label class="btn btn-outline-primary">
                                    <input type="radio" name="paymentMethod" value="AIRTEL-MONEY"> AIRTEL
                                </label>
                                <label class="btn btn-outline-info">
                                    <input type="radio" name="paymentMethod" value="CARD"> CARD
                                </label>
                            </div>
                        </div>

                        <!-- Amount Paid -->
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-money-bill-wave"></i> Amount Paid</label>
                            <input type="number" id="amountPaid" class="form-control" 
                                   placeholder="Enter amount paid" min="0" step="0.01" 
                                   value="0" onchange="calculateChange()">
                        </div>

                        <!-- Change -->
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-exchange-alt"></i> Change</label>
                            <input type="text" id="changeAmount" class="form-control" 
                                   value="TZS 0.00" readonly style="background: #f8f9fa;">
                        </div>

                        <!-- Action Buttons -->
                        <div class="action-buttons">
                            <button type="button" class="btn-pos btn-success" id="saveSaleBtn" onclick="saveSale()">
                                <i class="fas fa-save"></i> Save & Print
                            </button>
                            <button type="button" class="btn-pos btn-danger" onclick="clearCart()">
                                <i class="fas fa-times"></i> Cancel
                            </button>
                            <button type="button" class="btn-pos btn-warning" onclick="holdSale()">
                                <i class="fas fa-pause"></i> Hold
                            </button>
                            <button type="button" class="btn-pos btn-info" onclick="showReceiptPreview()">
                                <i class="fas fa-receipt"></i> Preview
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Batch Selection Modal -->
<div class="modal fade" id="batchModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="batchModalTitle">
                    <i class="fas fa-boxes"></i> Select Batch
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="batchSelectionContent">
                    <!-- Batch options will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <button type="button" class="btn btn-success" id="confirmBatchBtn" onclick="confirmBatchSelection()" disabled>
                    <i class="fas fa-check"></i> Add to Cart
                </button>
            </div>
        </div>
    </div>
</div>

<!-- New Customer Modal -->
<div class="modal fade" id="newCustomerModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus"></i> New Customer
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="newCustomerForm">
                    <div class="form-group">
                        <label>Full Name *</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Phone Number</label>
                        <input type="tel" name="phone" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <textarea name="address" class="form-control" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    Cancel
                </button>
                <button type="button" class="btn btn-success" onclick="saveNewCustomer()">
                    <i class="fas fa-save"></i> Save Customer
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Receipt Preview Modal -->
<div class="modal fade" id="receiptModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-receipt"></i> Receipt Preview
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="receiptContent">
                    <!-- Receipt will be generated here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    Close
                </button>
                <button type="button" class="btn btn-primary" onclick="printReceipt()">
                    <i class="fas fa-print"></i> Print Receipt
                </button>
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>

<script>
// Global variables
let cart = [];
let currentProduct = null;
let selectedBatch = null;
let products = [];
let temporaryCustomer = false;

// Initialize POS
$(document).ready(function() {
    console.log('POS System Initialized');
    
    // Initialize totals to 0
    $('#cartSubtotal').text('TZS 0.00');
    $('#cartDiscount').text('TZS 0.00');
    $('#cartTax').text('TZS 0.00');
    $('#cartTotal').text('TZS 0.00');
    
    // Load products
    loadProducts();
    
    // Load cart from localStorage if exists
    loadCartFromStorage();
    
    // Setup event listeners
    setupEventListeners();
});

function setupEventListeners() {
    // Product search
    $('#productSearch').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        filterProducts(searchTerm);
    });
    
    // Customer search
    $('#customerSearch').on('focus click', function() {
        $('#customerDropdown').show();
    });
    
    $('#customerSearch').on('keyup', function() {

        const searchTerm = $(this).val().toLowerCase();
        filterCustomerDropdown(searchTerm);
        
        // If user types something, clear the customer ID (they're typing a new name)
        if (searchTerm.trim() !== '') {
            $('#customerId').val('');
            temporaryCustomer = true;
            updateCustomerStatus();
        }
    });
    
    // Hide dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.customer-selector').length) {
            $('#customerDropdown').hide();
        }
    });
    
    // Discount amount change
    $('#discountAmount').on('input', updateCartTotals);
    $('#discountType').on('change', updateCartTotals);
    
    // Amount paid change
    $('#amountPaid').on('input', calculateChange);
}

// ==================== PRODUCT FUNCTIONS ====================

function loadProducts() {
    $.ajax({
        url: 'ajax_load_products.php',
        type: 'GET',
        data: { shop_id: <?= $shop_id ?> },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                products = response.products;
                renderProducts(products);
                $('#productCount').text(response.count + ' products');
            } else {
                showError('Failed to load products: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showError('Network error loading products: ' + error);
        }
    });
}

function refreshProducts() {
    $('#productsContainer').addClass('loading');
    setTimeout(() => {
        loadProducts();
        $('#productsContainer').removeClass('loading');
    }, 500);
}

function filterProducts(searchTerm = '', filterType = 'all', filterValue = '') {
    let filtered = products;
    
    // Apply search filter
    if (searchTerm) {
        filtered = filtered.filter(p => 
            p.name.toLowerCase().includes(searchTerm) ||
            p.sku.toLowerCase().includes(searchTerm) ||
            p.category.toLowerCase().includes(searchTerm)
        );
    }
    
    // Apply additional filters
    if (filterType === 'in_stock') {
        filtered = filtered.filter(p => p.total_qty > 0);
    } else if (filterType === 'category') {
        filtered = filtered.filter(p => p.category === filterValue);
    }
    
    renderProducts(filtered);
    $('#productCount').text(filtered.length + ' products');
}

function setProductFilter(filterType, filterValue = '') {
    // Update button states
    $('.btn-group .btn').removeClass('active');
    $(event.target).addClass('active');
    
    // Apply filter
    const searchTerm = $('#productSearch').val().toLowerCase();
    filterProducts(searchTerm, filterType, filterValue);
}

function renderProducts(productList) {
    const container = $('#productsContainer');
    
    if (productList.length === 0) {
        container.html(`
            <div class="text-center py-5">
                <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">No products found</h5>
                <p class="text-muted small">Try a different search term</p>
            </div>
        `);
        return;
    }
    
    let html = '<div class="product-grid">';
    
    productList.forEach(product => {
        const stockClass = product.total_qty <= 0 ? 'out' : (product.total_qty <= 10 ? 'low' : '');
        const stockText = product.total_qty <= 0 ? 'Out of stock' : `${product.total_qty} in stock`;
        const sellingPrice = parseFloat(product.selling_price) || 0;
        
        html += `
            <div class="product-item" onclick="selectProduct(${product.id})" 
                 data-product-id="${product.id}">
                <div class="product-stock ${stockClass}">${stockText}</div>
                <div class="product-name" title="${product.name}">${product.name}</div>
                <div class="product-sku">${product.sku}</div>
                <div class="product-price">TZS ${sellingPrice.toFixed(2)}</div>
                <div class="text-muted small mt-1">${product.category}</div>
            </div>
        `;
    });
    
    html += '</div>';
    container.html(html);
}

function selectProduct(productId) {
    currentProduct = products.find(p => p.id == productId);
    
    if (!currentProduct) {
        showError('Product not found!');
        return;
    }
    
    // Check if product has stock
    if (currentProduct.total_qty <= 0) {
        showError('This product is out of stock!');
        return;
    }
    
    // Load available batches
    loadProductBatches(productId);
}

function loadProductBatches(productId) {
    $.ajax({
        url: 'ajax_load_batches.php',
        type: 'GET',
        data: { 
            product_id: productId,
            shop_id: <?= $shop_id ?>
        },
        success: function(response) {
            $('#batchSelectionContent').html(response);
            $('#batchModal').modal('show');
        },
        error: function(xhr, status, error) {
            showError('Failed to load batches: ' + error);
        }
    });
}

function selectBatch(batchId) {
    $('.batch-item').removeClass('selected');
    $(`[data-batch-id="${batchId}"]`).addClass('selected');
    selectedBatch = batchId;
    $('#confirmBatchBtn').prop('disabled', false);
}

function confirmBatchSelection() {
    if (!currentProduct || !selectedBatch) {
        showError('Please select a batch first!');
        return;
    }
    
    // Get selected batch info
    const batchItem = $(`[data-batch-id="${selectedBatch}"]`);
    const batchInfo = batchItem.find('.batch-info').text();
    const batchStockText = batchItem.find('.batch-stock').text();
    const batchPriceText = batchItem.find('.batch-price').text();
    
    // Parse stock number
    const stockMatch = batchStockText.match(/(\d+)/);
    const batchStock = stockMatch ? parseInt(stockMatch[1]) : 0;
    
    // Parse price
    const priceMatch = batchPriceText.match(/TZS\s*([\d,.]+)/);
    const batchPrice = priceMatch ? parseFloat(priceMatch[1].replace(/,/g, '')) : 0;
    
    // Check if item already in cart
    const existingItem = cart.find(item => item.batch_id == selectedBatch);
    
    if (existingItem) {
        if (existingItem.qty >= batchStock) {
            showError('Cannot add more. Stock limit reached!');
            return;
        }
        existingItem.qty++;
    } else {
        // Add new item to cart
        cart.push({
            product_id: currentProduct.id,
            product_name: currentProduct.name,
            batch_id: selectedBatch,
            batch_info: batchInfo,
            price: batchPrice,
            qty: 1,
            max_qty: batchStock
        });
    }
    
    // Update cart display
    updateCartDisplay();
    
    // Close modal and reset
    $('#batchModal').modal('hide');
    selectedBatch = null;
    currentProduct = null;
    $('#confirmBatchBtn').prop('disabled', true);
    
    showSuccess('Product added to cart!');
}

// ==================== CART FUNCTIONS ====================

function updateCartDisplay() {
    const cartBody = $('#cartBody');
    const emptyCart = $('#emptyCart');
    const cartCount = $('#cartCount');
    
    // Save cart to localStorage
    saveCartToStorage();
    
    if (cart.length === 0) {
        emptyCart.show();
        cartBody.html('');
        cartCount.text('0 items');
        // Reset totals to zero
        $('#cartSubtotal').text('TZS 0.00');
        $('#cartDiscount').text('TZS 0.00');
        $('#cartTax').text('TZS 0.00');
        $('#cartTotal').text('TZS 0.00');
        $('#changeAmount').val('TZS 0.00');
        return;
    }
    
    emptyCart.hide();
    
    let html = '';
    let itemCount = 0;
    
    cart.forEach((item, index) => {
        const price = parseFloat(item.price) || 0;
        const qty = parseInt(item.qty) || 1;
        itemCount += qty;
        const itemTotal = price * qty;
        
        html += `
            <tr>
                <td class="product-cell">
                    <strong>${item.product_name}</strong><br>
                    <small class="text-muted">${item.batch_info}</small>
                </td>
                <td class="text-center">${item.batch_id}</td>
                <td class="text-center">
                    <div class="qty-control">
                        <button class="qty-btn" onclick="updateCartQty(${index}, -1)">
                            <i class="fas fa-minus"></i>
                        </button>
                        <input type="number" class="qty-input" value="${qty}" 
                               min="1" max="${item.max_qty}" 
                               onchange="updateCartInput(${index}, this.value)">
                        <button class="qty-btn" onclick="updateCartQty(${index}, 1)">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </td>
                <td class="text-center price-cell">TZS ${price.toFixed(2)}</td>
                <td class="text-center total-cell">TZS ${itemTotal.toFixed(2)}</td>
                <td class="text-center">
                    <button class="delete-btn" onclick="removeFromCart(${index})">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    cartBody.html(html);
    cartCount.text(itemCount + ' items');
    updateCartTotals();
}

function updateCartTotals() {
    let subtotal = 0;
    
    cart.forEach(item => {
        subtotal += parseFloat(item.price) * parseInt(item.qty);
    });
    
    // Calculate discount
    const discountType = $('#discountType').val();
    const discountAmount = parseFloat($('#discountAmount').val()) || 0;
    let discount = 0;
    
    if (discountType === 'percent') {
        discount = subtotal * (discountAmount / 100);
    } else {
        discount = Math.min(discountAmount, subtotal);
    }
    
    // Calculate tax (simplified - assuming 0% for now)
    const taxRate = 0; // You can make this configurable
    const tax = subtotal * (taxRate / 100);
    
    // Calculate total
    const total = subtotal - discount + tax;
    
    // Update display - ensure numbers are formatted
    $('#cartSubtotal').text('TZS ' + subtotal.toFixed(2));
    $('#cartDiscount').text('TZS ' + discount.toFixed(2));
    $('#cartTax').text('TZS ' + tax.toFixed(2));
    $('#cartTotal').text('TZS ' + total.toFixed(2));
    
    // Calculate change if amount paid is entered
    calculateChange();
}

function calculateChange() {
    const totalText = $('#cartTotal').text();
    const total = parseFloat(totalText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const paid = parseFloat($('#amountPaid').val()) || 0;
    const change = paid - total;
    
    if (change >= 0) {
        $('#changeAmount').val('TZS ' + change.toFixed(2)).css('color', '#28a745');
    } else {
        $('#changeAmount').val('TZS ' + Math.abs(change).toFixed(2) + ' due').css('color', '#dc3545');
    }
}

function updateCartQty(index, change) {
    const item = cart[index];
    const newQty = parseInt(item.qty) + change;
    
    if (newQty < 1) {
        removeFromCart(index);
        return;
    }
    
    if (newQty > item.max_qty) {
        showError(`Cannot add more than ${item.max_qty} units. Stock limit reached!`);
        return;
    }
    
    item.qty = newQty;
    updateCartDisplay();
}

function updateCartInput(index, value) {
    const item = cart[index];
    const newQty = parseInt(value) || 1;
    
    if (newQty < 1) {
        item.qty = 1;
    } else if (newQty > item.max_qty) {
        item.qty = item.max_qty;
        showError(`Stock limit: ${item.max_qty} units`);
    } else {
        item.qty = newQty;
    }
    
    updateCartDisplay();
}

function removeFromCart(index) {
    cart.splice(index, 1);
    updateCartDisplay();
    showSuccess('Item removed from cart!');
}

function clearCart() {
    if (cart.length === 0) {
        showInfo('Cart is already empty!');
        return;
    }
    
    if (confirm('Are you sure you want to clear the cart?')) {
        cart = [];
        updateCartDisplay();
        showSuccess('Cart cleared!');
    }
}

// ==================== CUSTOMER FUNCTIONS ====================

function filterCustomerDropdown(searchTerm) {
    const items = $('.customer-item');
    items.show();
    
    if (searchTerm) {
        items.each(function() {
            const text = $(this).text().toLowerCase();
            if (!text.includes(searchTerm)) {
                $(this).hide();
            }
        });
    }
}

function selectCustomer(customerId, customerName) {
    $('#customerId').val(customerId);
    $('#customerSearch').val(customerName);
    temporaryCustomer = false;
    updateCustomerStatus();
    $('#customerDropdown').hide();
}

function useTemporaryCustomer() {
    const customerName = $('#customerSearch').val().trim();
    if (!customerName) {
        showError('Please type a customer name first!');
        return;
    }
    
    $('#customerId').val('');
    temporaryCustomer = true;
    updateCustomerStatus();
    $('#customerDropdown').hide();
    showInfo('Using temporary customer: ' + customerName);
}

function updateCustomerStatus() {
    const customerName = $('#customerSearch').val().trim();
    
    if (!customerName) {
        $('#selectedCustomer').html('No customer selected (can type any name)');
    } else if (temporaryCustomer) {
        $('#selectedCustomer').html(`
            <i class="fas fa-user-clock text-warning"></i> Temporary: <strong>${customerName}</strong>
            <br><small class="text-muted">Will not be saved to customer database</small>
        `);
    } else if ($('#customerId').val()) {
        $('#selectedCustomer').html(`
            <i class="fas fa-check-circle text-success"></i> Registered Customer: <strong>${customerName}</strong>
        `);
    } else {
        $('#selectedCustomer').html(`
            <i class="fas fa-user text-info"></i> Customer: <strong>${customerName}</strong>
            <br><small class="text-muted">Type name or select from list</small>
        `);
    }
}

function showNewCustomerModal() {
    // Pre-fill name if user typed something
    const typedName = $('#customerSearch').val().trim();
    if (typedName) {
        $('#newCustomerForm input[name="name"]').val(typedName);
    }
    
    $('#newCustomerModal').modal('show');
    $('#customerDropdown').hide();
}

function saveNewCustomer() {
    const form = $('#newCustomerForm')[0];
    
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = new FormData(form);
    formData.append('shop_id', <?= $shop_id ?>);
    
    $.ajax({
        url: 'ajax_save_customer.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                selectCustomer(response.customer_id, response.customer_name);
                $('#newCustomerModal').modal('hide');
                showSuccess('Customer saved to database!');
                
                // Add to dropdown
                const dropdown = $('#customerDropdown');
                const newItem = `
                    <div class="customer-item" onclick="selectCustomer(${response.customer_id}, '${response.customer_name}')">
                        <div class="customer-name">${response.customer_name}</div>
                        <small class="text-success">New</small>
                    </div>
                `;
                dropdown.prepend(newItem);
            } else {
                showError('Failed to save customer: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showError('Network error: ' + error);
        }
    });
}

// ==================== SALE FUNCTIONS ====================

function validateSale() {
    if (cart.length === 0) {
        showError('Please add at least one item to the cart!');
        return false;
    }
    
    const total = parseFloat($('#cartTotal').text().replace('TZS ', '').replace(/,/g, ''));
    if (total <= 0) {
        showError('Total amount must be greater than zero!');
        return false;
    }
    
    // Check stock availability
    for (const item of cart) {
        if (parseInt(item.qty) > parseInt(item.max_qty)) {
            showError(`Cannot sell ${item.qty} units of "${item.product_name}". Only ${item.max_qty} available!`);
            return false;
        }
    }
    
    // Validate customer name
    const customerName = $('#customerSearch').val().trim();
    if (!customerName) {
        showError('Please enter a customer name!');
        return false;
    }
    
    return true;
}

function saveSale() {
    if (!validateSale()) {
        return;
    }
    
    // Calculate totals - parse with proper number handling
    const subtotalText = $('#cartSubtotal').text();
    const discountText = $('#cartDiscount').text();
    const taxText = $('#cartTax').text();
    const totalText = $('#cartTotal').text();
    
    const subtotal = parseFloat(subtotalText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const discount = parseFloat(discountText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const tax = parseFloat(taxText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const total = parseFloat(totalText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const paid = parseFloat($('#amountPaid').val()) || 0;
    const customerName = $('#customerSearch').val().trim();
    
    // Determine status
    let status = 'open';
    if (paid >= total) {
        status = 'paid';
    } else if (paid > 0) {
        status = 'partially_paid';
    }
    
    // Prepare sale data - ensure all numbers are properly typed
    const saleData = {
        invoice_no: '<?= $invoice_no ?>',
        customer_name: customerName, // Send customer name directly
        customer_id: $('#customerId').val() || null,
        shop_id: <?= $shop_id ?>,
        created_by: <?= $user_id ?>,
        discount: discount,
        tax: tax,
        total: total,
        paid: paid,
        status: status,
        payment_method: $('input[name="paymentMethod"]:checked').val(),
        items: cart.map(item => ({
            product_id: parseInt(item.product_id),
            batch_id: parseInt(item.batch_id),
            qty: parseInt(item.qty),
            unit_price: parseFloat(item.price),
            discount: 0,
            line_total: parseFloat(item.price) * parseInt(item.qty)
        }))
    };
    
    console.log('Saving sale:', saleData);
    
    // Show progress
    $('#saveSaleBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');
    
    $.ajax({
        url: 'ajax_save_sale.php',
        type: 'POST',
        data: JSON.stringify(saleData),
        contentType: 'application/json',
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showSuccess('Sale saved successfully!', 'Success');
                
                // Store receipt info for printing
                localStorage.setItem('lastSaleId', response.sale_id);
                localStorage.setItem('lastInvoiceNo', response.invoice_no);
                
                // Show success and redirect/print
                setTimeout(() => {
                    // Clear cart
                    cart = [];
                    updateCartDisplay();
                    
                    // Reset form
                    $('#customerId').val('');
                    $('#customerSearch').val('');
                    $('#selectedCustomer').html('No customer selected (can type any name)');
                    $('#discountAmount').val(0);
                    $('#amountPaid').val(0);
                    $('#changeAmount').val('TZS 0.00').css('color', '');
                    $('input[name="paymentMethod"][value="CASH"]').prop('checked', true);
                    temporaryCustomer = false;
                    
                    // Print receipt
                    printSaleReceipt(response.sale_id);
                    
                    // Re-enable button
                    $('#saveSaleBtn').prop('disabled', false).html('<i class="fas fa-save"></i> Save & Print');
                    
                }, 1000);
                
            } else {
                showError('Failed to save sale: ' + response.message);
                $('#saveSaleBtn').prop('disabled', false).html('<i class="fas fa-save"></i> Save & Print');
            }
        },
        error: function(xhr, status, error) {
            showError('Network error saving sale: ' + error);
            $('#saveSaleBtn').prop('disabled', false).html('<i class="fas fa-save"></i> Save & Print');
        }
    });
}

function holdSale() {
    if (cart.length === 0) {
        showError('Cannot hold empty cart!');
        return;
    }
    
    // Save cart to localStorage with timestamp
    const holdData = {
        cart: cart,
        timestamp: new Date().toISOString(),
        customer_id: $('#customerId').val(),
        customer_name: $('#customerSearch').val(),
        temporary_customer: temporaryCustomer
    };
    
    localStorage.setItem('heldSale', JSON.stringify(holdData));
    showSuccess('Sale held successfully! You can retrieve it later.');
    clearCart();
}

function showReceiptPreview() {
    if (cart.length === 0) {
        showError('Cannot preview empty cart!');
        return;
    }
    
    // Generate receipt HTML
    const customerName = $('#customerSearch').val().trim() || 'Walk-in Customer';
    
    let receiptHTML = `
        <div class="receipt-preview">
            <div class="receipt-header">
                <h4>${$('h3.text-success').text().split('>')[1]?.trim() || 'Point of Sale'}</h4>
                <p>${$('h3.text-success').text().split('>')[1]?.trim() || 'POS System'}</p>
                <p>Invoice: <?= $invoice_no ?></p>
                <p>Date: ${new Date().toLocaleString()}</p>
            </div>
            
            <div class="receipt-items">
    `;
    
    let subtotal = 0;
    cart.forEach(item => {
        const price = parseFloat(item.price) || 0;
        const qty = parseInt(item.qty) || 1;
        const itemTotal = price * qty;
        subtotal += itemTotal;
        
        receiptHTML += `
            <div class="receipt-item">
                <div class="qty">${qty}x</div>
                <div class="name">${item.product_name}</div>
                <div class="price">TZS ${itemTotal.toFixed(2)}</div>
            </div>
        `;
    });
    
    const discountText = $('#cartDiscount').text();
    const taxText = $('#cartTax').text();
    const totalText = $('#cartTotal').text();
    
    const discount = parseFloat(discountText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const tax = parseFloat(taxText.replace('TZS ', '').replace(/,/g, '')) || 0;
    const total = parseFloat(totalText.replace('TZS ', '').replace(/,/g, '')) || 0;
    
    receiptHTML += `
            </div>
            
            <div class="receipt-totals">
                <div class="receipt-total-row">
                    <span>Subtotal:</span>
                    <span>TZS ${subtotal.toFixed(2)}</span>
                </div>
                <div class="receipt-total-row">
                    <span>Discount:</span>
                    <span>TZS ${discount.toFixed(2)}</span>
                </div>
                <div class="receipt-total-row">
                    <span>Tax:</span>
                    <span>TZS ${tax.toFixed(2)}</span>
                </div>
                <div class="receipt-total-row total">
                    <span>TOTAL:</span>
                    <span>TZS ${total.toFixed(2)}</span>
                </div>
            </div>
            
            <div class="receipt-footer">
                <p>Thank you for your purchase!</p>
                <p>Customer: ${customerName}</p>
                <p>Payment: ${$('input[name="paymentMethod"]:checked').val()}</p>
                ${temporaryCustomer ? '<p><small class="text-warning">* Temporary customer</small></p>' : ''}
            </div>
        </div>
    `;
    
    $('#receiptContent').html(receiptHTML);
    $('#receiptModal').modal('show');
}

function printReceipt() {
    const receiptContent = $('#receiptContent').html();
    const printWindow = window.open('', '_blank');
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print Receipt</title>
            <style>
                body { font-family: 'Courier New', monospace; margin: 0; padding: 20px; }
                @media print {
                    body { padding: 0; }
                    .no-print { display: none !important; }
                }
            </style>
        </head>
        <body>
            ${receiptContent}
            <div class="no-print" style="text-align: center; margin-top: 20px;">
                <button onclick="window.print()" style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">
                    Print Receipt
                </button>
                <button onclick="window.close()" style="padding: 10px 20px; background: #dc3545; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px;">
                    Close
                </button>
            </div>
        </body>
        </html>
    `);
    
    printWindow.document.close();
}

function printSaleReceipt(saleId) {
    window.open(`print_sale_receipt.php?id=${saleId}`, '_blank');
}

// ==================== STORAGE FUNCTIONS ====================

function saveCartToStorage() {
    localStorage.setItem('posCart', JSON.stringify(cart));
}

function loadCartFromStorage() {
    try {
        const savedCart = localStorage.getItem('posCart');
        if (savedCart) {
            cart = JSON.parse(savedCart);
            if (cart.length > 0) {
                updateCartDisplay();
                // Initialize totals
                updateCartTotals();
                showInfo('Loaded ' + cart.length + ' items from previous session');
            }
        }
    } catch (e) {
        console.error('Error loading cart from storage:', e);
    }
}

// ==================== HELPER FUNCTIONS ====================

function showSuccess(message, title = 'Success') {
    Swal.fire({
        icon: 'success',
        title: title,
        text: message,
        timer: 2000,
        showConfirmButton: false
    });
}

function showError(message, title = 'Error') {
    Swal.fire({
        icon: 'error',
        title: title,
        text: message,
        timer: 3000
    });
}

function showInfo(message, title = 'Info') {
    Swal.fire({
        icon: 'info',
        title: title,
        text: message,
        timer: 2000,
        showConfirmButton: false
    });
}



</script>