<?php
require_once '../config/db.php';

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

// Initialize cart if not set
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_modal_item'])) {
    $index = $_POST['index'];
    $cost_price = $_POST['modal_cost_price'];
    $selling_price = $_POST['modal_selling_price'];
    $expiration_date = $_POST['modal_expiration_date'];

    if (isset($_SESSION['cart'][$index])) {
        $_SESSION['cart'][$index]['cost_price'] = $cost_price;
        $_SESSION['cart'][$index]['selling_price'] = $selling_price;
        $_SESSION['cart'][$index]['expiration_date'] = $expiration_date;
        $_SESSION['cart'][$index]['total_price'] = $cost_price * $_SESSION['cart'][$index]['quantity'];
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}


// Fetch all drugs from the database
$sql = "SELECT id, drug_name, cost_price, selling_price, expiration_date, quantity FROM drugs";
$stmt = $pdo->query($sql);
$drugs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all suppliers from the database
$sql = "SELECT id, business_name FROM suppliers";
$stmt = $pdo->query($sql);
$suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Add to cart functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    $drug_id = $_POST['drug_id'];
    $quantity = $_POST['quantity'];

    // Fetch drug details based on the selected drug
    $sql = "SELECT * FROM drugs WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$drug_id]);
    $drug = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($drug) {
        $total_price = $drug['cost_price'] * $quantity;

        // Add drug to cart
        $_SESSION['cart'][] = [
            'drug_id' => $drug['id'],
            'drug_name' => $drug['drug_name'],
            'quantity' => $quantity,
            'available_quantity' => $drug['quantity'],
            'cost_price' => $drug['cost_price'],
            'selling_price' => $drug['selling_price'],
            'total_price' => $total_price,
            'expiration_date' => $drug['expiration_date']
        ];
    } 
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Rest of the functionality (update, remove, submit supply) remains as-is

// Remove item from cart
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_item'])) {
    $index = $_POST['index'];
    if (isset($_SESSION['cart'][$index])) {
        unset($_SESSION['cart'][$index]);
        $_SESSION['cart'] = array_values($_SESSION['cart']); // Re-index array
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Update cart functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) {
    foreach ($_SESSION['cart'] as $index => &$item) {
        $item['cost_price'] = $_POST['cost_price'][$index];
        $item['selling_price'] = $_POST['selling_price'][$index];
        $item['expiration_date'] = $_POST['expiration_date'][$index];
        $item['total_price'] = $item['cost_price'] * $item['quantity'];
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}
$totalCost = array_sum(array_column($_SESSION['cart'], 'total_price'));

// Submit cart as supply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_supply'])) {
    $supplier_id = $_POST['supplier_id'];
    $supply_date = $_POST['supply_date'];
    $total_paid = $_POST['total_paid'];
    $added_by = $_SESSION['username']; // Assuming user_id is stored in the session

    // Start transaction
    $pdo->beginTransaction();

    try {
        // Insert into supplies table
        $sql = "INSERT INTO supplies (supplier_id, supply_date, total_cost, total_paid) 
                VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$supplier_id, $supply_date, $totalCost, $total_paid]);
        $supply_id = $pdo->lastInsertId();

        

        // Insert into supply_details table and update drugs table
        foreach ($_SESSION['cart'] as $item) {
            // Insert into supply details table
            $sql = "INSERT INTO supply_details (supply_id, drug_id, quantity_supplied, cost_price) 
                    VALUES (?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$supply_id, $item['drug_id'], $item['quantity'], $item['cost_price']]);

             // Insert into drug history table
             // Fetch supplier business name
$sql = "SELECT business_name FROM suppliers WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$supplier_id]);
$supplier = $stmt->fetch(PDO::FETCH_ASSOC);

if ($supplier) {
    $business_name = $supplier['business_name'];
} else {
    $business_name = "Unknown Supplier"; // Fallback if the supplier is not found
}

             
             $action = "Supply"; // Record action as "Supply"
             $details = "Supplied by: $business_name"; // Include supplier name
             $sql = "INSERT INTO drug_history (drug_id, action, quantity, details, user, action_date) 
                     VALUES (?, ?, ?, ?, ?, ?)";
             $stmt = $pdo->prepare($sql);
             $stmt->execute([$item['drug_id'], $action, $item['quantity'], $details, $added_by, $supply_date]);
 

            // Update drug quantity
            $sql = "UPDATE drugs SET quantity = quantity + ?, selling_price = ?, expiration_date = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$item['quantity'], $item['selling_price'], $item['expiration_date'], $item['drug_id']]);
        
         
        
        }
        

        // Insert into supply_payments table
        $sql = "INSERT INTO supply_payments (supply_id, amount_paid, payment_date, added_by) 
                VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$supply_id, $total_paid, $supply_date, $added_by]);

        // Commit transaction
        $pdo->commit();

        // Clear cart after submitting
        $_SESSION['cart'] = [];

        echo "<script>alert('Supply successfully added!'); window.location.href = 'add_supply.php';</script>";
    } catch (Exception $e) {
        $pdo->rollBack();
        echo "<script>alert('An error occurred: " . $e->getMessage() . "');</script>";
    }

    exit();
}

?>

<style>
    :root {
        --primary-color: #2c3e50;
        --border-color: #dee2e6;
        --text-color: #333333;
        --background-color: #f8f9fa;
    }

    body {
        background-color: var(--background-color);
        font-family: 'Mulish', sans-serif;
        color: var(--text-color);
    }

    .content {
        margin-left: 240px;
        padding: 20px;
    }

    .top-bar {
        background-color: #ffffff;
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 4px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }

    .supply-card {
        background: white;
        border-radius: 4px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .card-header {
        background: var(--primary-color);
        color: white;
        padding: 15px;
        border-radius: 4px 4px 0 0;
    }

    .table thead th {
        background-color: var(--primary-color);
        color: white;
        font-weight: 500;
    }

    .btn-primary {
        background: var(--primary-color);
        border: none;
    }

    .btn-success {
        background: #28a745;
        border: none;
    }

    .btn-warning {
        background: #ffc107;
        border: none;
    }

    .btn-danger {
        background: #dc3545;
        border: none;
    }

    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(44, 62, 80, 0.15);
    }

    .select2-container .select2-selection--single {
        height: 38px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
    }

    .modal-content {
        border-radius: 4px;
    }

    .modal-header {
        background: var(--primary-color);
        color: white;
    }

    @media (max-width: 768px) {
        .content {
            margin-left: 0;
            padding: 10px;
        }
    }
</style>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Supply - Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <link rel="stylesheet" href="..\libs\select2\css\select2.min.css">
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --success-color: #2ecc71;
            --warning-color: #f1c40f;
            --danger-color: #e74c3c;
        }

        body {
            background-color: #f5f6fa;
            font-family: 'Mulish', sans-serif;
            overflow-x: hidden;
        }

        .content {
            margin-left: 240px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
            backdrop-filter: blur(10px);
        }

        .supply-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }

        .supply-card:hover {
            transform: translateY(-2px);
        }

        .card-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 15px;
            border-radius: 10px 10px 0 0;
        }

        .table {
            margin-bottom: 0;
        }

        .table thead th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 500;
            border: none;
            padding: 12px;
        }

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

        .select2-container .select2-selection--single {
            height: 38px;
            line-height: 38px;
            border: 1px solid #ced4da;
            border-radius: 0.25rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .btn-success {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
            border: none;
        }

        .btn-warning {
            background: linear-gradient(135deg, #f39c12, #f1c40f);
            border: none;
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #c0392b, #e74c3c);
            border: none;
        }

        .currency {
            font-family: 'Consolas', monospace;
            font-weight: 500;
            color: var(--primary-color);
        }

        .modal-content {
            border-radius: 10px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.2);
        }

        .modal-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 10px 10px 0 0;
        }

        .modal-body {
            padding: 20px;
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
            
            .mobile-toggle {
                display: block;
            }
        }

        /* Toast Notification */
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1051;
        }

        /* Loading Spinner */
        .spinner-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1052;
        }
    </style>
</head>
<body>
    <?php include '../includes/side_bar.php'; ?>

    <!-- Mobile Toggle Button -->
    <button class="mobile-toggle d-md-none" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Loading Spinner -->
    <div class="spinner-overlay" id="loadingSpinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <!-- Toast Notification -->
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="fas fa-info-circle me-2"></i>
            <strong class="me-auto">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body"></div>
    </div>

    <div class="content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Add New Supply</h4>
                <a href="view_supply.php" class="btn btn-outline-primary">
                    <i class="fas fa-list"></i> View Supplies
                </a>
            </div>
        </div>

        <!-- Add Drug to Cart -->
        <div class="supply-card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-plus-circle"></i> Add Drug to Invoice</h5>
            </div>
            <div class="card-body">
                <form method="POST" class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Search Drug</label>
                        <select class="form-select" id="drug_id" name="drug_id" required>
                            <option value="" disabled selected>Choose a drug</option>
                            <?php foreach ($drugs as $drug): ?>
                                <option value="<?= $drug['id'] ?>">
                                    <?= htmlspecialchars($drug['drug_name']) ?> 
                                    (Qty: <?= $drug['quantity'] ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Quantity</label>
                        <input type="number" class="form-control" name="quantity" required>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" name="add_to_cart" class="btn btn-primary w-100">
                            <i class="fas fa-plus"></i> Add
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Cart Table -->
        <div class="supply-card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-shopping-cart"></i> Supply Cart</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($_SESSION['cart'])): ?>
                    <form method="POST">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th>Drug Name</th>
                                    <th>Available Qty</th>
                                    <th>Qty Supply</th>
                                    <th>Unit Cost</th>
                                    <th>Selling Price</th>
                    
                                    <th>Total Cost</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($_SESSION['cart'] as $index => $item): ?>
                                    <tr>
                                        <td><?= $item['drug_name'] ?></td>
                                        <td><?= $item['available_quantity'] ?></td>
                                        <td><?= $item['quantity'] ?></td>
                                        <td><?= '₦' . number_format($item['cost_price'], 2) ?></td>

                                        <td><?= '₦' . number_format($item['selling_price'], 2) ?></td>

                                       
                                        <td><?= '₦' . number_format($item['total_price'], 2) ?></td>

                                        <td>
    <button type="button" class="btn btn-warning btn-sm edit-drug-btn" 
            data-index="<?= $index ?>" 
             data-drug-name="<?= $item['drug_name'] ?>"
            data-cost="<?= $item['cost_price'] ?>" 
            data-selling="<?= $item['selling_price'] ?>" 
            data-expiration="<?= $item['expiration_date'] ?>">
        <i >Edit</i>
    </button>
    <button type="submit" name="remove_item" class="btn btn-danger btn-sm ">
        <i>Remove</i>
    </button>
    <input type="hidden" name="index" value="<?= $index ?>">
</td>

                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <p class="text-end"><strong>Total Cost:</strong> <?= '₦' . number_format($totalCost, 2) ?></p>
                   
                </form>
                <?php else: ?>
                    <p class="text-center text-muted py-5">
                        <i class="fas fa-shopping-cart fa-3x mb-3"></i><br>
                        No items in the cart
                    </p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Submit Supply Form -->
        <div class="supply-card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-check-circle"></i> Submit Supply</h5>
            </div>
            <div class="card-body">
                <form method="POST" class="row g-3">
                <div class="col-md-6">
                    <label for="supplier_id" class="form-label">Select Supplier</label>
                    <select class="form-select" id="supplier_id" name="supplier_id" required>
                        <option value="" disabled selected>Choose a supplier</option>
                        <?php foreach ($suppliers as $supplier): ?>
                            <option value="<?= $supplier['id'] ?>"><?= $supplier['business_name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label for="total_paid" class="form-label">Amount Paid</label>
                    <input type="number" class="form-control" id="total_paid" name="total_paid" placeholder="Enter amount paid" required>
                </div>
                <div class="col-md-6">
                    <label for="supply_date" class="form-label">Supply Date</label>
                    <input type="date" class="form-control" id="supply_date" name="supply_date" required>
                </div>
                <div class="col-md-6 d-flex align-items-end">
                    <button type="submit" name="submit_supply" class="btn btn-success w-100 addn">Submit Supply</button>
                </div>
            </form>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal fade" id="editDrugModal" tabindex="-1" aria-labelledby="editDrugModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editDrugModalLabel">Edit Drug Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <input type="hidden" name="index" id="modal-index">
                    <div class="mb-3">
                        <label for="modal-drug-name" class="form-label">Drug Name</label>
                        <input type="text" class="form-control" id="modal-drug-name" name="modal-drug-name" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="modal-cost-price" class="form-label">Cost Price</label>
                        <input type="number" class="form-control" id="modal-cost-price" name="modal_cost_price" required>
                    </div>
                    <div class="mb-3">
                        <label for="modal-selling-price" class="form-label">Selling Price</label>
                        <input type="number" class="form-control" id="modal-selling-price" name="modal_selling_price" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="modal-expiration-date" class="form-label">Expiration Date</label>
                        <input type="date" class="form-control" id="modal-expiration-date" name="modal_expiration_date" required>
                    </div>
                    <button type="submit" name="update_modal_item" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
</div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script src="..\libs\select2\js\select2.min.js"></script>
    <script>
        function toggleSidebar() {
            document.querySelector('.sidebar').classList.toggle('active');
            document.querySelector('.content').classList.toggle('sidebar-active');
        }

        $(document).ready(function() {
            $('#drug_id, #supplier_id').select2({
                theme: 'bootstrap4',
                width: '100%'
            });
        });

        // ... rest of your existing JavaScript ...
    </script>
<script>
 $(document).ready(function() {
    // Event listener for the Add Invoice button
    $('#addn').click(function(event) {
        event.preventDefault(); // Prevent default form submission or button behavior

        // Check if the cart is not empty
        <?php if (!empty($_SESSION['cart'])): ?>
            var lastItem = <?= json_encode($_SESSION['cart'][count($_SESSION['cart']) - 1]); ?>;
            $('#modal-index').val(<?= count($_SESSION['cart']) - 1; ?>); // Set index to last item
            $('#modal-drug-name').val(lastItem.drug_name);  // Set drug name
            $('#modal-cost-price').val(lastItem.cost_price);  // Set cost price
            $('#modal-selling-price').val(lastItem.selling_price);  // Set selling price
            $('#modal-expiration-date').val(lastItem.expiration_date);  // Set expiration date

            // Show the modal
            $('#editDrugModal').modal('show');
        <?php else: ?>
            alert('Your cart is empty. Please add items to the cart first.');
        <?php endif; ?>
    });
});


</script>
<script>
    // When the edit button is clicked, populate the modal fields with the drug data
    document.querySelectorAll('.edit-drug-btn').forEach(button => {
        button.addEventListener('click', function() {
            const index = this.getAttribute('data-index');
            const drugName = this.getAttribute('data-drug-name');
            const costPrice = this.getAttribute('data-cost');
            const sellingPrice = this.getAttribute('data-selling');
            const expirationDate = this.getAttribute('data-expiration');

            document.getElementById('modal-index').value = index;
            document.getElementById('modal-drug-name').value = drugName;
            document.getElementById('modal-cost-price').value = costPrice;
            document.getElementById('modal-selling-price').value = sellingPrice;
            document.getElementById('modal-expiration-date').value = expirationDate;
        });
    });



    // Function to trigger the modal automatically when an item is added to the cart
$(document).ready(function() {
    // Check if an item has been added to the cart
    <?php if (isset($_POST['add_to_cart'])): ?>
        // Trigger modal to open
        $('#editDrugModal').modal('show');
    <?php endif; ?>

    // Handle the edit button click event to populate the modal
    $('.edit-drug-btn').click(function() {
        var index = $(this).data('index');
        var cost = $(this).data('cost');
        var selling = $(this).data('selling');
        var expiration = $(this).data('expiration');
        
        // Populate modal fields with data
        $('#modalIndex').val(index);
        $('#modalCostPrice').val(cost);
        $('#modalSellingPrice').val(selling);
        $('#modalExpirationDate').val(expiration);

        // Open the modal
        $('#editDrugModal').modal('show');
    });
});

</script>

<script>
    $(document).ready(function () {
        $('#drug_id, #supplier_id').select2({
            placeholder: "Select an option",
            width: '100%'
        });
    });
</script>
<script>
        // Enhanced JavaScript functionality
        $(document).ready(function() {
            // Initialize Select2
            $('#drug_id, #supplier_id').select2({
                theme: 'bootstrap4',
                width: '100%',
                placeholder: "Select an option"
            });

            // Show loading spinner during form submission
            $('form').on('submit', function() {
                $('#loadingSpinner').css('display', 'flex');
            });

            // Handle edit button click
            $('.edit-drug-btn').click(function() {
                const data = $(this).data();
                $('#modal-index').val(data.index);
                $('#modal-drug-name').val(data.drugName);
                $('#modal-cost-price').val(data.cost);
                $('#modal-selling-price').val(data.selling);
                $('#modal-expiration-date').val(data.expiration);
                $('#editDrugModal').modal('show');
            });

            // Show toast notification
            function showToast(message, type = 'success') {
                $('.toast-body').text(message);
                $('.toast').toast('show');
            }

            // Auto-calculate total on amount paid input
            $('#total_paid').on('input', function() {
                const totalCost = <?= $totalCost ?>;
                const amountPaid = parseFloat($(this).val()) || 0;
                const remaining = totalCost - amountPaid;
                
                if (remaining > 0) {
                    showToast(`Remaining amount: ₦${remaining.toFixed(2)}`, 'info');
                }
            });
        });
    </script>
</body>
</html>

