<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

include '../config/db.php';

// Update the database query to include image_path and barcode
$query = "SELECT id, drug_name, quantity, selling_price, volume_price, image_path, barcode FROM drugs";
$result = $pdo->query($query);
$drugs = $result->fetchAll(PDO::FETCH_ASSOC);

$query = "SELECT pharmacy_name FROM settings LIMIT 1"; // Assuming only one entry
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name'; // Fallback to a default if not found

// Fetch payment methods from the database
try {
    $stmt = $pdo->query("SELECT id, method_name FROM payment_methods ORDER BY method_name ASC");
    $payment_methods = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error fetching payment methods: " . $e->getMessage());
}
// Fetch customers from the database
$query = "SELECT id, full_name FROM customers ORDER BY full_name ASC";
$stmt = $pdo->prepare($query);
$stmt->execute();
$customers = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $customers[] = $row;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sell Product - Store Management System</title>
    <link rel="stylesheet" href="..\libs\select2\css\select2.min.css">
    <link rel="stylesheet" href="../libs/bootsrtap2/css/bootstrap.min.css">
    <link rel="stylesheet" href="../libs/fontawesome/css/all.min.css">
    <script src="..\libs\bootsrtap2\js\bootstrap.bundle.min.js"></script>
    <script src="../libs/jquery/jquery-3.7.1.min.js"></script>
 

    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
   
    <style>
        .card {
    background-color: #ffffff;
    border: 1px solid #dee2e6;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-title {
    font-weight: bold;
    color: #343a40;
}

.form-group label {
    font-weight: 600;
    color: #495057;
}

#totalPaymentSplit, #remainingBalance {
    font-size: 1rem;
    font-weight: bold;
    color: #007bff;
}

         h2, h5 {
    font-size: 1.2rem; /* Smaller font sizes */
}
p {
    font-size: 0.9rem;
}
        body {
            background-color: #f5f6fa;
            font-family: mulish, sans-serif;
            overflow-x: hidden;
            font-size: 14px
        }
       
        .content {
            margin-left: 10px;
            padding: 0px;
            transition: margin-left 0.3s ease;
        }
        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            display: flex;
            
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .ftop-bar {
    background-color: #ffffff;
    padding: 15px;
    
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    margin-bottom: 1px;

    position: sticky; /* Makes the element sticky */
    top: 0; /* Sticks at the top when scrolling */
    z-index: 1000; /* Ensures it stays above other elements */
}
        body { background-color: #f8f9fa; 
        
            font-family: 'Mulish', sans-serif; /* Apply Mulish font */
        }
        
        
        /* Shared styles */
        .card { border-radius: 10px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); }
        .btn-primary { background-color: #007bff; border: none; }
        .btn-secondary, .btn-danger { border: none; }
        h3, h5 { color: #343a40; }
        .form-control, .select2-container--default .select2-selection--single { border-radius: 5px; }

        /* Desktop-specific styling */
        @media (min-width: 992px) {
            .container { margin-top: 30px; }
            .desktop-only { display: block; }
            .mobile-only { display: none; }
        }

        /* Mobile-specific styling */
        @media (max-width: 991px) {
            .mobile-container { padding: 10px; }
            .desktop-only { display: none; }
            .mobile-only { display: block; }
            h3 { font-size: 1.5rem; text-align: center; }
            h5, .form-control, .btn { font-size: 0.9rem; }
            .btn { width: 100%; } /* Buttons take full width on mobile */
        }
        .close_nav{
            display:none;
        }
        .show_nav{
            display:none;
        }
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            .sidebar.active {
                transform: translateX(0);
            }
            .content {
                margin-left: 0;
            }
            .close_nav{
                display:inline-block;
            }
            .show_nav{
            display:inline-block;
        }
    }
    </style>
    <style>
        body {
            background-color: #f5f6fa;
            font-family: 'Mulish', sans-serif;
            font-size: 14px;
        }

        .pos-container {
            display: grid;
            grid-template-columns: 65% 35%;
            gap: 20px;
            padding: 20px;
            height: calc(100vh - 70px);
        }

        .products-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }

        .search-section {
            padding: 15px;
            border-bottom: 1px solid #eee;
        }

        .barcode-section {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            padding: 15px;
            overflow-y: auto;
        }

        .product-card {
            background: white;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .product-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .product-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .cart-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }

        .cart-items {
            flex-grow: 1;
            overflow-y: auto;
        }

        .cart-summary {
            padding: 15px;
            border-top: 1px solid #eee;
            background: #f8f9fa;
        }

        .payment-methods {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 10px;
            margin: 15px 0;
        }

        .payment-method-btn {
            padding: 10px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .payment-method-btn.active {
            background: #2c3e50;
            color: white;
            border-color: #2c3e50;
        }

        /* Add more styles as needed */
    </style>
    <style>
        .pos-container {
    display: grid;
    grid-template-columns: 65% 35%;
    gap: 20px;
    padding: 20px;
    height: calc(100vh - 70px);
}

.products-section {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.search-section {
    padding: 15px;
    border-bottom: 1px solid #eee;
    background: #f8f9fa;
}

.barcode-section {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
    padding: 15px;
    overflow-y: auto;
    height: calc(100vh - 200px);
}

.product-card {
    background: white;
    border: 1px solid #eee;
    border-radius: 8px;
    padding: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.product-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.product-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 5px;
    margin-bottom: 10px;
}

@media (max-width: 768px) {
    .pos-container {
        grid-template-columns: 1fr;
    }
}
    </style>
</head>
<body>
<div class="wrapper">
    <div class="main-content">
        <!-- Top Navigation Bar -->
        <nav class="navbar navbar-expand-lg main-navbar">
            <div class="container-fluid">
                <button class="btn btn-link sidebar-toggler" onclick="toggleSidebar(this)">
                    <i class="fas fa-bars"></i>
                </button>

                <div class="navbar-brand">
                    <h4 class="mb-0"><?php echo htmlspecialchars($pharmacy_name); ?></h4>
                </div>

                <ul class="navbar-nav ml-auto">
                    <li class="nav-item dropdown">
                        <button class="btn btn-link nav-link dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle"></i>
                            <span><?php echo htmlspecialchars($_SESSION['username']); ?></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog"></i> Settings</a></li>
                            <li><a class="dropdown-item" href="log_history.php"><i class="fas fa-history"></i> Log History</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Rest of your existing content stays the same -->
        <div class="content-wrapper">
        
<div class="container mobile-container">
    
    <div class="text-left mb-3 desktop-only">
        <a href="index.php" class="btn btn-outline-secondary">Back to Dashboard</a>
    </div>

    

       

<!-- Modal for adding new customer -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" aria-labelledby="addCustomerModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCustomerModalLabel">Add New Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addCustomerForm">
                    <div class="mb-3">
                        <label for="full_name" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="full_name" name="full_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="phone_number" class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="phone_number" name="phone_number" required>
                    </div>
                    <div class="form-group">
    <label for="gender">Gender:</label>
    <select class="form-control" id="gender" name="gender" required>
    <option value="">--Select Gender--</option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
        <option value="Other">Other</option>
    </select>
</div>
                    <div class="mb-3">
                        <label for="address" class="form-label">Address</label>
                        <textarea class="form-control" id="address" name="address"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Save Customer</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <div class="row">
        <!-- Left Side - Product Selection -->
        <div class="col-md-7">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="card-title mb-0">Select Products</h5>
                        <a href="index.php" class="btn btn-outline-secondary btn-sm">
                            <i class="fas fa-arrow-left"></i> Back
                        </a>
                    </div>

                    <!-- Search and Barcode Section -->
                    <div class="mb-3">
                        <div class="input-group mb-2">
                            <span class="input-group-text">
                                <i class="fas fa-barcode"></i>
                            </span>
                            <input type="text" id="barcodeInput" class="form-control" 
                                   placeholder="Scan barcode"
                                   onkeypress="handleBarcodeInput(event)">
                            <button class="btn btn-primary" onclick="toggleCamera()">
                                <i class="fas fa-camera"></i>
                            </button>
                        </div>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-search"></i>
                            </span>
                            <input type="text" id="searchInput" class="form-control" 
                                   placeholder="Search products" oninput="filterProducts()">
                        </div>
                    </div>

                    <!-- Products Grid -->
                    <div class="products-grid">
                        <?php foreach ($drugs as $drug): ?>
                            <div class="product-card" onclick='addToCart(<?= htmlspecialchars(json_encode($drug)) ?>)'>
                                <img src="<?= !empty($drug['image_path']) ? htmlspecialchars($drug['image_path']) : 'uploads/products/default.png' ?>" 
                                     class="product-image" 
                                     alt="<?= htmlspecialchars($drug['drug_name']) ?>">
                                <div class="product-info">
                                    <h6><?= htmlspecialchars($drug['drug_name']) ?></h6>
                                    <p class="price">₦<?= number_format($drug['selling_price'], 2) ?></p>
                                    <span class="stock-badge <?= $drug['quantity'] < 10 ? 'low-stock' : 'in-stock' ?>">
                                        <i class="fas <?= $drug['quantity'] < 10 ? 'fa-exclamation-triangle' : 'fa-check-circle' ?>"></i>
                                        Stock: <?= $drug['quantity'] ?>
                                    </span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Side - Cart Section -->
        <div class="col-md-5">
            <div class="card h-100">
                <div class="card-body d-flex flex-column">
                    <h5 class="card-title">Current Sale</h5>
                    
                    <!-- Cart Items -->
                    <div class="flex-grow-1 overflow-auto mb-3">
                        <table class="table table-sm" id="cartTable">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                    <th>Total</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>

                    <!-- Customer Selection -->
                    <div class="mb-3">
                        <select id="customer" class="form-select">
                            <option value="1">Walking Customer</option>
                            <?php foreach ($customers as $customer): ?>
                                <option value="<?= $customer['id'] ?>"><?= htmlspecialchars($customer['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Cart Summary -->
                    <div class="cart-summary border-top pt-3">
                        <!-- Owing Checkbox -->
                        <div class="form-check">
                            <input type="checkbox" id="owingCheckbox" class="form-check-input">
                            <label class="form-check-label" for="owingCheckbox" style="color: blue;">Attach owing?</label>

                            <!-- Display Owing Amount in Red -->
                            <div id="owingAmountDisplay" style="display: none; color: red; font-weight: bold; margin-top: 10px;">
                                Owing Amount: <span id="owingAmountText"></span>
                            </div>
                        </div>

                        <!-- Modal -->
                        <div class="modal fade" id="owingModal" tabindex="-1" aria-labelledby="owingModalLabel" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="owingModalLabel">Set Owing Details</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="form-group">
                                            <label for="owingAmount" class="font-weight-bold">Owing Amount</label>
                                            <input type="number" id="owingAmount" class="form-control form-control-sm" placeholder="Enter the owing amount">
                                        </div>
                                        <div class="form-group">
                                            <label for="owingType" class="font-weight-bold">Owing Type</label>
                                            <select id="owingType" class="form-control form-control-sm">
                                                <option value="owed_to">Owed to me</option>
                                                <option value="owed_by">I owe</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                        <button type="button" class="btn btn-primary" id="saveOwingBtn">Save</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Include Bootstrap JS (if not already included) -->

                        <script>
                            // Show Modal when checkbox is checked
                            document.getElementById('owingCheckbox').addEventListener('change', function() {
                                const owingModal = new bootstrap.Modal(document.getElementById('owingModal'));
                                const owingAmountDisplay = document.getElementById('owingAmountDisplay');
                                const owingAmountText = document.getElementById('owingAmountText');
                                
                                if (this.checked) {
                                    owingModal.show();  // Show the modal automatically when checkbox is checked
                                    owingAmountDisplay.style.display = 'block'; // Show the owing amount display
                                } else {
                                    owingModal.hide();  // Hide the modal when checkbox is unchecked
                                    owingAmountDisplay.style.display = 'none'; // Hide the owing amount display
                                }
                            });

                            // Save Button in Modal (for demonstration)
                            document.getElementById('saveOwingBtn').addEventListener('click', function() {
                                const owingAmount = document.getElementById('owingAmount').value;
                                const owingType = document.getElementById('owingType').value;
                                console.log("Owing Amount: ", owingAmount);
                                console.log("Owing Type: ", owingType);

                                // Update the owing amount display with the entered value
                                const owingAmountText = document.getElementById('owingAmountText');
                                owingAmountText.textContent = owingAmount;

                                // Handle saving this data as needed (e.g., send to the server)
                                const owingModal = bootstrap.Modal.getInstance(document.getElementById('owingModal'));
                                owingModal.hide();  // Close the modal after saving
                            });
                        </script>

                        <!-- Add this to your CSS for modal appearance -->
                        <style>
                            /* Keep the modal compact and clean */
                            .modal-content {
                                border-radius: 10px;
                            }
                            .modal-header {
                                background-color: #f7f7f7;
                                border-bottom: 1px solid #ddd;
                            }
                            .modal-footer {
                                border-top: 1px solid #ddd;
                            }
                            .modal-body .form-group {
                                margin-bottom: 15px;
                            }
                            .btn-primary {
                                border-radius: 30px;
                            }
                        </style>

                        <!-- Discount Checkbox -->
                        <div class="form-check">
                            <input type="checkbox" id="discountCheckbox" class="form-check-input" onchange="toggleDiscountField()">
                            <label class="form-check-label" for="discountCheckbox">Apply Discount</label>
                        </div>

                        <!-- Discount Input Field -->
                        <div class="form-group" id="discountField" style="display: none;">
                            <label for="discount">Discount (₦)</label>
                            <input type="number" id="discount" class="form-control" min="0" value="0" oninput="applyDiscount()">
                        </div>

                        <!-- Total Price After Discount -->
                        <h6 style="display: none" id="cartTotalAfterDiscount1">Total Price after Discount (₦): <span id="cartTotalAfterDiscount">0.00</span></h6>

                        <script>
                            // Toggle the discount input field visibility based on checkbox state
                            function toggleDiscountField() {
                                const discountCheckbox = document.getElementById('discountCheckbox');
                                const discountField = document.getElementById('discountField');

                                if (discountCheckbox.checked) {
                                    discountField.style.display = 'block';  // Show discount input
                                    cartTotalAfterDiscount1.style.display = 'block';  // Show discount input
                                } else {
                                    cartTotalAfterDiscount1.style.display = 'none';
                                    discountField.style.display = 'none';   // Hide discount input
                                    document.getElementById('discount').value = 0;  // Reset discount value
                                    applyDiscount();  // Recalculate total without discount
                                }
                            }

                            // Apply the discount to the total price
                            function applyDiscount() {
                                // Get the current total price (you may replace this with actual cart total logic)
                                let cartTotal = parseFloat(document.getElementById('cartTotal').innerText); // Assuming you have a cart total element

                                // Get the discount value
                                const discount = parseFloat(document.getElementById('discount').value) || 0;

                                // Calculate the new total after discount
                                const totalAfterDiscount = cartTotal - discount;

                                // Update the total price after discount
                                document.getElementById('cartTotalAfterDiscount').innerText = totalAfterDiscount.toFixed(2);
                            }

                            // Example to simulate the cart total (for demonstration purposes)
                            // You can remove or replace this part with your actual cart total calculation logic
                            window.onload = function() {
                                document.getElementById('cartTotal').innerText = '5000.00'; // Example initial total
                                applyDiscount(); // Recalculate total on page load
                            }
                        </script>
                        <div class="form-group">
                            <h6>Total Price (₦): <span id="cartTotalPrice">0.00</span></h6>
                        </div>
                    </div>

                    <!-- Payment Section -->
                    <div class="payment-section border-top pt-3 mt-3">
                        <div class="card mt-4 p-3 shadow-sm">
                            <h5 class="card-title mb-4">Payment Details</h5>

                            <!-- Primary Payment Fields -->
                            <div class="row g-3 align-items-center mb-3">
                                <!-- Primary Payment Method -->
                                <div class="col-md-6">
                                    <label for="primary_payment_method" class="form-label">Primary Payment Method</label>
                                    <select id="primary_payment_method" name="primary_payment_method" class="form-control" required>
                                        <option value="" disabled selected>Select Payment Method</option>
                                        <?php foreach ($payment_methods as $method): ?>
                                            <option value="<?= htmlspecialchars($method['method_name']) ?>"><?= htmlspecialchars($method['method_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <!-- Primary Payment Amount -->
                                <div class="col-md-6 d-none" id="primary_payment_amount_div">
                                    <label for="primary_payment_amount" class="form-label">Amount</label>
                                    <input type="number" id="primary_payment_amount" name="primary_payment_amount" class="form-control" placeholder="Enter amount for primary payment">
                                </div>
                            </div>

                            <!-- Split Payment Checkbox -->
                            <div class="form-check mb-3">
                                <input type="checkbox" class="form-check-input" id="split_payment" name="split_payment">
                                <label class="form-check-label" for="split_payment">Split Payment?</label>
                            </div>

                            <!-- Secondary Payment Fields (Hidden by default) -->
                            <div id="split_payment_fields" class="d-none">
                                <div class="row g-3 align-items-center mb-3">
                                    <!-- Secondary Payment Method -->
                                    <div class="col-md-6">
                                        <label for="secondary_payment_method" class="form-label">Secondary Payment Method</label>
                                        <select id="secondary_payment_method" name="secondary_payment_method" class="form-select">
                                            <option value="" disabled selected>Select Payment Method</option>
                                            <?php foreach ($payment_methods as $method): ?>
                                                <option value="<?= htmlspecialchars($method['method_name']) ?>"><?= htmlspecialchars($method['method_name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <!-- Secondary Payment Amount -->
                                    <div class="col-md-6">
                                        <label for="secondary_payment_amount" class="form-label">Amount</label>
                                        <input type="number" id="secondary_payment_amount" name="secondary_payment_amount" class="form-select" placeholder="Enter amount for secondary payment">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="mt-3">
                        <button type="button" id="proceedButton" class="btn btn-primary w-100" onclick="delayAndProceedToSale()">
                            Proceed to Sale
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
            <!-- Your existing content here -->
        </div>

        <!-- Add Footer -->
        <footer class="main-footer">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-0">&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($pharmacy_name); ?></p>
                    </div>
                    <div class="col-md-6 text-end">
                        <p class="mb-0">Version 1.0</p>
                    </div>
                </div>
            </div>
        </footer>
    </div>
</div>

<!-- Add these styles to your existing CSS -->
<style>
.main-navbar {
    background: #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,.1);
    padding: 0.5rem 1rem;
    margin-bottom: 1rem;
}

.navbar-brand h4 {
    color: #333;
    font-weight: 600;
}

.sidebar-toggler {
    color: #333;
    padding: 0.5rem;
}

.nav-link {
    color: #333;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.main-footer {
    background: #fff;
    padding: 1rem;
    border-top: 1px solid #dee2e6;
    margin-top: auto;
}

.wrapper {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.content-wrapper {
    flex: 1;
    padding: 1rem;
}

/* Adjust existing container padding */
.container-fluid {
    padding-left: 1rem;
    padding-right: 1rem;
}

/* Update button styles to match dashboard */
.btn-primary {
    background-color: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    background-color: #0056b3;
    border-color: #0056b3;
}
</style>



<style>
    .products-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 10px;
        max-height: calc(100vh - 250px);
        overflow-y: auto;
        padding: 10px;
    }

    .product-card {
        background: white;
        border: 1px solid #eee;
        border-radius: 8px;
        padding: 8px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .product-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .product-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 5px;
        margin-bottom: 8px;
    }

    .product-card h6 {
        font-size: 0.9rem;
        margin-bottom: 5px;
    }

    .product-card p {
        font-size: 0.85rem;
        font-weight: bold;
    }

    .product-card small {
        font-size: 0.8rem;
    }
</style>

<!-- Barcode Scanner Modal -->
<div class="modal fade" id="scannerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Scan Barcode</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <video id="scanner" style="width: 100%"></video>
            </div>
        </div>
    </div>
</div>

<!-- Quantity Input Modal -->
<div class="modal fade" id="quantityModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add to Cart</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <img id="selectedProductImage" src="" alt="Product Image" 
                         class="img-fluid" style="max-height: 150px; width: auto;">
                </div>
                <div class="mb-3">
                    <strong>Product:</strong> 
                    <span id="selectedProductName" class="ms-2"></span>
                </div>

                <!-- Add sale type selection -->
                <div class="mb-3">
                    <label class="form-label">Sale Type</label>
                    <div class="btn-group w-100" role="group">
                        <input type="radio" class="btn-check" name="saleType" id="unitSale" value="unit" checked>
                        <label class="btn btn-outline-primary" for="unitSale">Unit Sale</label>

                        <input type="radio" class="btn-check" name="saleType" id="volumeSale" value="volume">
                        <label class="btn btn-outline-primary" for="volumeSale">Volume Sale</label>
                    </div>
                </div>

                <div class="mb-3">
                    <strong>Price:</strong> 
                    <span id="selectedProductPrice" class="ms-2"></span>
                    <span id="volumePriceInfo" class="d-none text-success ms-2">
                        (Volume Price Available)
                    </span>
                </div>

                <div class="mb-3">
                    <strong>Available Stock:</strong> 
                    <span id="selectedProductStock" class="ms-2"></span>
                </div>

                <div class="mb-3">
                    <label for="productQuantity" class="form-label">Quantity</label>
                    <input type="number" 
                           class="form-control" 
                           id="productQuantity" 
                           min="1" 
                           value="1"
                           oninput="updateTotalPrice()">
                </div>

                <div class="mb-3">
                    <strong>Total Price:</strong> 
                    <span id="selectedProductTotal" class="ms-2"></span>
                </div>
                <input type="hidden" id="currentProduct">
            </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" onclick="confirmAddToCart()">Add to Cart</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
// JavaScript functions remain the same
</script>
</body>
</html>

<script src="..\libs\select2\js\select2.min.js"></script>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
 window.onload = function() {

    discount = parseFloat(document.getElementById("discount").value) || 0;
    loadCartFromStorage();
    renderCart();
   
    };
    
$(document).ready(function() {
    $('#drug').select2({
        placeholder: '-- Choose a drug --',
        allowClear: true
        
    });

   
});


 // Retrieve the logged-in user's username from the session
 const username = '<?php echo $_SESSION["username"]; ?>';

// Function to save the cart to localStorage for the specific user
function saveCartToStorage() {
    if (username) {
        localStorage.setItem(`cart_${username}`, JSON.stringify(cart));
    }
}
function clearCart() {
    if (username) {
        localStorage.removeItem(`cart_${username}`); // Removes the cart from localStorage
        cart = []; // Optionally, reset the cart array in memory as well
    }
}
// Function to load the cart from localStorage for the specific user
function loadCartFromStorage() {
    if (username) {
        const storedCart = localStorage.getItem(`cart_${username}`);
        if (storedCart) {
            cart = JSON.parse(storedCart);
            let discount = parseFloat(document.getElementById("discount").value) || 0;
            renderCart();
        }
    }
}

// Initialize the cart for the current user
let cart = [];

$(document).ready(function() {
    // Initialize Select2
    $('#customer').select2({
        placeholder: "Select a customer",
        allowClear: true,
        language: {
            noResults: function() {
                return '<p>Customer Not Found<p><button id="add-customer-btn" style="width: 100%; padding: 10px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; text-align: center;">Add New Customer</button>';
            }
        },
        escapeMarkup: function (markup) { return markup; } // To allow HTML content in the dropdown
    });

    // Event listener for the "Add New Customer" button (opens the modal)
    $(document).on('click', '#add-customer-btn', function() {
        $('#addCustomerModal').modal('show'); // Show the modal when the button is clicked
    });

    // Handle form submission (using AJAX)
    $('#addCustomerForm').submit(function(e) {
    e.preventDefault(); // Prevent default form submission

    // Collect form data
    var customerData = {
        full_name: $('#full_name').val(),
        email: $('#email').val(),
        phone_number: $('#phone_number').val(),
        gender: $('#gender').val(),
        address: $('#address').val()
    };

    // Send data to the PHP script using AJAX
    $.ajax({
        type: 'POST',
        url: 'add_customer.php', // PHP script that handles the form submission
        data: customerData,
        success: function(response) {
            // Check if the response is successful
            if (response === 'success') {
                alert('Customer added successfully!');
                $('#addCustomerModal').modal('hide'); // Close the modal
                $('#addCustomerForm')[0].reset(); // Reset the form
                location.reload();
                
                // Optionally, you can update the Select2 dropdown here to include the new customer
            } else {
                alert('Error: ' + response); // Show error if something went wrong
            }
        },
        error: function() {
            alert('An error occurred while submitting the form.');
        }
    });
});

});

       
function updateDrugDetails() {
    const selectedOption = document.getElementById("drug").options[document.getElementById("drug").selectedIndex];
    document.getElementById("availableQuantity").value = selectedOption.getAttribute("data-quantity");
    document.getElementById("price").value = selectedOption.getAttribute("data-unitprice"); 
    document.getElementById("quantity").value = "";
    document.getElementById('drugId').value = drugId;

}

function updatePriceForType() {
    const saleType = document.getElementById("saleType").value;
    const selectedOption = document.getElementById("drug").options[document.getElementById("drug").selectedIndex];
    document.getElementById("price").value = saleType === 'volume' ? selectedOption.getAttribute("data-volumeprice") : selectedOption.getAttribute("data-unitprice");
}

function calculateTotalPrice() {
    const quantity = parseInt(document.getElementById("quantity").value);
    const price = parseFloat(document.getElementById("price").value);
    return (quantity * price).toFixed(2);
}
function splitAmountToDrugs() {
    const totalCartPrice = calculateTotalPrice();

    // Loop through each drug in the cart and calculate its proportion
    cart.forEach(item => {
        const drugTotalPrice = parseFloat(item.totalPrice); // Total price for this drug
        const drugShare = (drugTotalPrice / totalCartPrice) * totalCartPrice;

        // Insert the proportion (drugShare) into the drug object or prepare it for the sale
        item.proportionalAmount = drugShare.toFixed(2); // Store this amount for each drug
    });
}

function addToCart(product) {
    const quantityModal = new bootstrap.Modal(document.getElementById('quantityModal'));
    
    // Set product image and basic info
    document.getElementById('selectedProductImage').src = product.image_path || 'uploads/products/default.png';
    document.getElementById('selectedProductName').textContent = product.drug_name;
    document.getElementById('selectedProductStock').textContent = product.quantity;
    document.getElementById('productQuantity').value = '1';
    document.getElementById('productQuantity').max = product.quantity;
    document.getElementById('currentProduct').value = JSON.stringify(product);

    // Show volume price info if available
    const volumePriceInfo = document.getElementById('volumePriceInfo');
    if (product.volume_price) {
        volumePriceInfo.classList.remove('d-none');
        document.getElementById('volumeSale').disabled = false;
    } else {
        volumePriceInfo.classList.add('d-none');
        document.getElementById('volumeSale').disabled = true;
    }

    // Set initial price (unit price by default)
    updatePriceDisplay(product);

    // Add event listeners for sale type change
    document.querySelectorAll('input[name="saleType"]').forEach(radio => {
        radio.addEventListener('change', () => updatePriceDisplay(product));
    });

    quantityModal.show();
}

function updatePriceDisplay(product) {
    const saleType = document.querySelector('input[name="saleType"]:checked').value;
    const price = saleType === 'volume' ? product.volume_price : product.selling_price;
    document.getElementById('selectedProductPrice').textContent = '₦' + parseFloat(price).toFixed(2);
    updateTotalPrice();
}

function updateTotalPrice() {
    const product = JSON.parse(document.getElementById('currentProduct').value);
    const quantity = parseInt(document.getElementById('productQuantity').value);
    const saleType = document.querySelector('input[name="saleType"]:checked').value;
    
    const price = saleType === 'volume' ? product.volume_price : product.selling_price;
    const totalPrice = quantity * parseFloat(price);
    
    document.getElementById('selectedProductTotal').textContent = '₦' + totalPrice.toFixed(2);
    
    // Validate quantity against available stock
    if (quantity > product.quantity) {
        alert('Quantity cannot exceed available stock!');
        document.getElementById('productQuantity').value = product.quantity;
        updateTotalPrice();
    }
}

function confirmAddToCart() {
    const product = JSON.parse(document.getElementById('currentProduct').value);
    const quantity = parseInt(document.getElementById('productQuantity').value);
    const saleType = document.querySelector('input[name="saleType"]:checked').value;
    const price = saleType === 'volume' ? product.volume_price : product.selling_price;

    if (isNaN(quantity) || quantity <= 0 || quantity > product.quantity) {
        alert('Please enter a valid quantity');
        return;
    }

    const item = {
        id: product.id,
        drugName: product.drug_name,
        quantity: quantity,
        unitPrice: parseFloat(price),
        totalPrice: (quantity * parseFloat(price)).toFixed(2),
        saleType: saleType
    };

    // Check if item already exists in cart
    const existingItem = cart.find(i => i.id === item.id && i.saleType === item.saleType);
    if (existingItem) {
        existingItem.quantity += quantity;
        existingItem.totalPrice = (existingItem.quantity * existingItem.unitPrice).toFixed(2);
    } else {
        cart.push(item);
    }

    saveCartToStorage();
    renderCart();

    // Close the modal
    const quantityModal = bootstrap.Modal.getInstance(document.getElementById('quantityModal'));
    quantityModal.hide();
}

function applyDiscount() {
    discount = parseFloat(document.getElementById("discount").value) || 0;
    console.log("Discount applied:", discount); // Log discount
    saveCartToStorage();

    renderCart();
}
function renderCart() {
    const cartTableBody = document.querySelector("#cartTable tbody");
    cartTableBody.innerHTML = "";
    let cartTotal = 0;

    cart.forEach((item, index) => {
        cartTotal += parseFloat(item.totalPrice);
        cartTableBody.innerHTML += `
            <tr>
                <td>${item.drugName}</td>
                <td>
                    <input 
                        type="number" 
                        value="${item.quantity}" 
                        min="1" 
                        class="form-control form-control-sm quantity-input" 
                        onchange="updateCartQuantity(${index}, this.value)" 
                        style="width: 80px;"
                    >
                    ${item.saleType === 'volume' ? 'Volume' : 'Units'}
                </td>
                <td>₦${item.unitPrice}</td>
                <td>₦${item.totalPrice}</td>
                <td><button class="btn btn-danger btn-sm" onclick="removeFromCart(${index})">Remove</button></td>
            </tr>
        `;
    });

  
    document.getElementById("cartTotalPrice").textContent = cartTotal.toFixed(2);

    // Calculate and display Total Paid After Discount
    let totalPaid = cartTotal - discount;
    document.getElementById("cartTotalAfterDiscount").textContent = totalPaid.toFixed(2);
}
function updateCartQuantity(index, newQuantity) {
    
    if (newQuantity < 1) {
        alert("Quantity cannot be less than 1.");
        return;
    }

    const item = cart[index];
    item.quantity = parseInt(newQuantity, 10);
    item.totalPrice = (item.unitPrice * item.quantity).toFixed(2);
    saveCartToStorage();
    // Re-render the cart to reflect changes
    renderCart();
}

function removeFromCart(index) {
    if (index >= 0 && index < cart.length) {
        cart.splice(index, 1); // Remove the item at the specified index
        saveCartToStorage();
        renderCart(); // Re-render the cart to reflect changes
    } else {
        console.error("Invalid index for removal:", index);
    }
}

function delayAndProceedToSale() {
    const proceedButton = document.getElementById('proceedButton');
    
    // Disable the button and change the text to indicate it's waiting
    proceedButton.disabled = true;
    proceedButton.textContent = "Please wait...";  // Optional: to show the user it's loading

    // Wait for 20 seconds (20000ms)
    setTimeout(function() {
        // After 20 seconds, re-enable the button and restore its text
       

        // Now that the button is re-enabled, call the function to proceed with the sale
        proceedToSale();
    }, 3000); // 20,000ms = 20 seconds
}


function proceedToSale() {
    const totalPaid = parseFloat(document.getElementById("cartTotalAfterDiscount").textContent);

    const paymentMethod1 = document.getElementById('primary_payment_method').value;
    let paymentAmount1 = parseFloat(document.getElementById('primary_payment_amount').value) || 0.00;

    const paymentMethod2 = document.getElementById('secondary_payment_method').value;
    let paymentAmount2 = parseFloat(document.getElementById('secondary_payment_amount').value) || 0.00;
    const customer = document.getElementById('customer').value;

    


     // Capture owing data
     const owingCheckbox = document.getElementById('owingCheckbox');
    let owingAmount = 0;
    let owingType = '';
    if (owingCheckbox.checked) {
        owingAmount = parseFloat(document.getElementById('owingAmount').value) || 0;
        owingType = document.getElementById('owingType').value;
    }



    if (!paymentMethod1) {
        alert("Please select a payment method.");
        proceedButton.disabled = false;
        proceedButton.textContent = "Proceed to Sale";
        return;
    }
    // Calculate proportional amounts for each drug
    const cartTotalPrice = cart.reduce((sum, item) => sum + item.totalPrice, 0);
    cart.forEach(item => {
        item.proportionalAmount = (item.totalPrice / cartTotalPrice) * totalPaid;
    });

    

    // Check if payment is split
    const splitPaymentCheckbox = document.getElementById('split_payment');
    if (!splitPaymentCheckbox.checked) {
        paymentAmount1 = totalPaid;
        paymentAmount2 = 0;
    }

    const totalPayment = paymentAmount1 + paymentAmount2;
    if (totalPayment !== totalPaid) {
        alert("The total payment amount must be exactly equal to the total after discount.");
        proceedButton.disabled = false;
        proceedButton.textContent = "Proceed to Sale";
        return;
    }

    

    const requestData = { 
        cart, 
        discount: discount, 
        totalPaid: totalPaid,
        paymentMethod1: paymentMethod1,
        paymentAmount1: paymentAmount1,
        paymentMethod2: paymentMethod2,
        paymentAmount2: paymentAmount2, 
        customer: customer,
        owingAmount: owingAmount,
        owingType: owingType // Include owing data
    };

    $.ajax({
        url: 'process_cart_sale.php',
        type: 'POST',
        data: JSON.stringify(requestData),
        contentType: 'application/json',
        success: function (response) {
            let res = JSON.parse(response);
            if (res.success) {
                alert("Sale completed successfully!");
                clearCart();
                window.location.href = `receipt.php?receipt_no=${res.receipt}`;
            } else {
                alert("Error: " + res.message);
                proceedButton.disabled = false;
                proceedButton.textContent = "Proceed to Sale";
            }
        },
        error: function () {
            alert("An error occurred. Please try again.");
            
        }
    });
}


 
document.addEventListener('DOMContentLoaded', function () {
        const splitPaymentCheckbox = document.getElementById('split_payment');
        const splitPaymentFields = document.getElementById('split_payment_fields');
        const primaryPaymentAmountDiv = document.getElementById('primary_payment_amount_div');
        const secondaryPaymentMethodSelect = document.getElementById('secondary_payment_method');
        const primaryPaymentMethodSelect = document.getElementById('primary_payment_method');

        // Toggle the visibility of secondary payment fields and amount input for primary payment
        splitPaymentCheckbox.addEventListener('change', function () {
            if (splitPaymentCheckbox.checked) {
                splitPaymentFields.classList.remove('d-none'); // Show secondary payment fields
                primaryPaymentAmountDiv.classList.remove('d-none'); // Show primary payment amount field
                
                // Automatically select the second payment method (e.g., payment_method2)
                if (secondaryPaymentMethodSelect.options.length > 1) {
                    secondaryPaymentMethodSelect.value = secondaryPaymentMethodSelect.options[1].value; // Automatically select payment_method2
                }
            } else {
                splitPaymentFields.classList.add('d-none'); // Hide secondary payment fields
                primaryPaymentAmountDiv.classList.add('d-none'); // Hide primary payment amount field
            }
        });
    });

    // Show the Add Customer Popup when the button is clicked
    document.getElementById('add-customer-btn').addEventListener('click', function() {
        document.getElementById('add-customer-popup').style.display = 'block';
    });

    // Close the popup
    document.getElementById('close-popup').addEventListener('click', function() {
        document.getElementById('add-customer-popup').style.display = 'none';
    });
</script>
<script src="https://unpkg.com/@zxing/library@latest"></script>
<script>
    // Function to load products
    async function loadProducts() {
    try {
        const response = await fetch('get_products.php');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const products = await response.json();
        
        // Check if we received an error response
        if (products.error) {
            throw new Error(products.message);
        }

        const productsGrid = document.querySelector('.products-grid');
        productsGrid.innerHTML = products.map(product => `
            <div class="product-card" onclick='addToCart(${JSON.stringify(product)})'>
                <img src="${product.image_path || 'uploads/products/default.png'}" 
                     class="product-image" 
                     alt="${product.drug_name}"
                     loading="lazy">
                <div class="product-info">
                    <h6>${product.drug_name}</h6>
                    <p class="mb-0">₦${parseFloat(product.selling_price).toFixed(2)}</p>
                    <small>Stock: ${product.quantity}</small>
                </div>
            </div>
        `).join('');

    } catch (error) {
        console.error('Error loading products:', error);
        const productsGrid = document.querySelector('.products-grid');
        productsGrid.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                Error loading products. Please try refreshing the page.
                <br>
                <small>${error.message}</small>
            </div>`;
    }
}

// Add this helper function for HTML escaping
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// Add this to your existing JavaScript code
function filterProducts() {
    const searchTerm = document.getElementById('searchInput').value.trim();
    const productsGrid = document.querySelector('.products-grid');

    // Show loading state
    productsGrid.innerHTML = `
        <div class="text-center w-100">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Searching...</span>
            </div>
        </div>`;

    // Fetch filtered products
    fetch(`get_products.php?search=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(products => {
            productsGrid.innerHTML = products.map(product => `
                <div class="product-card" onclick='addToCart(${JSON.stringify(product)})'>
                    <img src="${product.image_path || 'uploads/products/default.png'}" 
                         class="product-image" 
                         alt="${escapeHtml(product.drug_name)}">
                    <div class="product-info">
                        <h6>${escapeHtml(product.drug_name)}</h6>
                        <p class="mb-0">₦${parseFloat(product.selling_price).toFixed(2)}</p>
                        <small>Stock: ${product.quantity}</small>
                    </div>
                </div>
            `).join('') || '<div class="text-center w-100">No products found</div>';
        })
        .catch(error => {
            console.error('Error:', error);
            productsGrid.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    Error searching products
                </div>`;
        });
}

// Add debouncing to prevent too many requests
let searchTimeout;
document.getElementById('searchInput').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(filterProducts, 300);
});
</script>
