<?php
session_start();
// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Include database connection
include '../config/db.php';

// Fetch drugs from the database for the dropdown
$query = "SELECT id, drug_name, quantity, selling_price, volume_price, volume_size FROM drugs";
$result = $pdo->query($query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sell Drug - Pharmacy Management System</title>
    <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">
    <style>
        body { background-color: #e9ecef; }
        .container { margin-top: 30px; }
        .card { background-color: #ffffff; border-radius: 10px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); }
        .btn-primary { background-color: #007bff; border: none; }
        .btn-secondary { background-color: #6c757d; border: none; }
        h3, h5 { color: #343a40; }
        .form-control, .select2-container--default .select2-selection--single { border-radius: 5px; }
    </style>
</head>
<body>
<div class="container">
    <h3 class="text-center mb-4">Sell Drugs (Cart System)</h3>
    <p class="text-center mb-4">Select drugs, add quantities, and view the total before proceeding to sell.</p>

    <div class="text-right mb-3">
        <a href="index.php" class="btn btn-outline-secondary">Back to Dashboard</a>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-body">
                    <div class="form-group">
                        <label for="drug">Select Drug</label>
                        <select id="drug" class="form-control" onchange="updateDrugDetails()">
                            <option value="">-- Choose a drug --</option>
                            <?php while ($row = $result->fetch(PDO::FETCH_ASSOC)): ?>
                                <option value="<?php echo htmlspecialchars($row['id']); ?>"
                                        data-quantity="<?php echo $row['quantity']; ?>"
                                        data-unitprice="<?php echo $row['selling_price']; ?>"
                                        data-volumeprice="<?php echo $row['volume_price']; ?>"
                                        data-volumesize="<?php echo $row['volume_size']; ?>">
                                    <?php echo htmlspecialchars($row['drug_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <!-- Change this part of the saleType dropdown -->
<div class="form-group">
    <label for="saleType">Select Sale Type</label>
    <select id="saleType" class="form-control" required onchange="updatePriceForType()">
        <option value="">-- Choose Sale Type --</option>
        <option value="unit">Unit</option>
        <option value="volume">Volume</option>
    </select>
</div>

                    <div class="form-group">
                        <label for="availableQuantity">Available Quantity in Store</label>
                        <input type="text" id="availableQuantity" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label for="quantity">Quantity</label>
                        <input type="number" id="quantity" class="form-control" min="1" oninput="calculateTotalPrice()">
                    </div>
                    <div class="form-group">
                        <label for="price">Price (₦)</label>
                        <input type="text" id="price" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-secondary" onclick="addToCart()">Add to Cart</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Cart Section -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Selected Drugs (Cart)</h5>
                    <table class="table table-bordered" id="cartTable">
                        <thead>
                        <tr>
                            <th>Drug Name</th>
                            <th>Quantity</th>
                            <th>Unit Price (₦)</th>
                            <th>Total Price (₦)</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div class="form-group">
                        <h5>Total Price (₦): <span id="cartTotalPrice">0.00</span></h5>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="proceedToSale()">Proceed to Sell</button>
                    </div>
                </div>
            </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>
$(document).ready(function() {
    $('#drug').select2({
        placeholder: '-- Choose a drug --',
        allowClear: true
    });
});

let cart = [];

function updateDrugDetails() {
    const drugSelect = document.getElementById("drug");
    const selectedOption = drugSelect.options[drugSelect.selectedIndex];
    const availableQuantity = selectedOption.getAttribute("data-quantity");
    const unitPrice = selectedOption.getAttribute("data-unitprice");
    const volumePrice = selectedOption.getAttribute("data-volumeprice");
    const volumeSize = selectedOption.getAttribute("data-volumesize");

    document.getElementById("availableQuantity").value = availableQuantity;
    document.getElementById("price").value = unitPrice; // Set default to unit price
    document.getElementById("quantity").value = "";
}

function updatePriceForType() {
    const saleType = document.getElementById("saleType").value;
    const selectedOption = document.getElementById("drug").options[document.getElementById("drug").selectedIndex];
    const unitPrice = selectedOption.getAttribute("data-unitprice");
    const volumePrice = selectedOption.getAttribute("data-volumeprice");

    if (saleType === 'volume') {
        document.getElementById("price").value = volumePrice; // Set to volume price
    } else {
        document.getElementById("price").value = unitPrice; // Set back to unit price
    }
}

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

function addToCart() {
    const drugSelect = document.getElementById("drug");
    const drugId = drugSelect.value;
    const drugName = drugSelect.options[drugSelect.selectedIndex].text;
    const availableQuantity = parseInt(document.getElementById("availableQuantity").value);
    const quantity = parseInt(document.getElementById("quantity").value);
    const price = parseFloat(document.getElementById("price").value);
    const saleType = document.getElementById("saleType").value; // Check if unit or volume
    const totalPrice = calculateTotalPrice();

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

    const existingItem = cart.find(item => item.id === drugId);
    if (existingItem) {
        existingItem.quantity += quantity;
        existingItem.totalPrice = (existingItem.quantity * price).toFixed(2);
    } else {
        cart.push({
            id: drugId,
            drugName: drugName,
            quantity: quantity,
            unitPrice: price,
            totalPrice: totalPrice,
            saleType: saleType
        });
    }
    renderCart();

// Clear the fields after adding to cart
document.getElementById("quantity").value = "";
document.getElementById("availableQuantity").value = "";
document.getElementById("price").value = "";
document.getElementById("drug").value = "";
$('#drug').select2().val(null).trigger('change'); // Reset select2
document.getElementById("saleType").value = "";
}

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>${item.quantity} ${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);
}

function removeFromCart(index) {
    cart.splice(index, 1);
    renderCart();
}

function proceedToSale() {
    if (cart.length === 0) {
        alert("Cart is empty.");
        return;
    }

    // Send the cart data as JSON
    $.ajax({
        type: "POST",
        url: "process_cart_sale.php",
        contentType: 'application/json', // Specify JSON content type
        data: JSON.stringify({ cart: cart }), // Convert cart array to JSON
        success: function(response) {
            const res = JSON.parse(response); // Parse the response if needed
            if (res.success) {
                alert("Sale completed successfully.");
                cart = [];
                renderCart();
                window.location.href = 'index.php';
            } else {
                alert("Error processing the sale: " + res.message);
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error: ", error);
        }
    });
}

</script>
</body>
</html>
