<?php
session_start();
// Check if the user is logged in and if they have the correct role
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'manager')) {
    header("Location: login.php");
    exit();
}

// Include database configuration file
include '../config/db.php';

// Display success or error message if present
if (isset($_SESSION['success'])) {
    echo '<div class="alert alert-success">' . $_SESSION['success'] . '</div>';
    unset($_SESSION['success']);
} elseif (isset($_SESSION['error'])) {
    echo '<div class="alert alert-danger">' . $_SESSION['error'] . '</div>';
    unset($_SESSION['error']);
}

// Initialize search variable
$searchTerm = '';
$sortColumn = 'id'; // Default sorting column
$sortOrder = 'ASC'; // Default sorting order

if (isset($_POST['search'])) {
    $searchTerm = $_POST['search'];
}

if (isset($_GET['sort']) && isset($_GET['order'])) {
    $sortColumn = $_GET['sort'];
    $sortOrder = $_GET['order'] === 'ASC' ? 'DESC' : 'ASC'; // Toggle order
}

// Fetch drugs from the database based on search term and sorting
$query = "SELECT * FROM drugs WHERE drug_name LIKE :searchTerm ORDER BY $sortColumn $sortOrder LIMIT 30";
$stmt = $pdo->prepare($query);
$stmt->execute(['searchTerm' => '%' . $searchTerm . '%']);
$drugs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get today's date
$today = new DateTime();
$lowStockAlert = [];
$expiringSoonAlert = [];

// Check for low stock and expiring drugs
foreach ($drugs as $drug) {
    if ($drug['quantity'] < 0) {
        $lowStockAlert[] = htmlspecialchars($drug['drug_name']) . " (Low Stock)";
    }

    $expirationDate = new DateTime($drug['expiration_date']);
    if ($expirationDate->diff($today)->days <= 60 && $expirationDate > $today) {
        $expiringSoonAlert[] = htmlspecialchars($drug['drug_name']);
    }
}
?>


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Products</title>

    <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>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            overflow-x: hidden;
            font-size: 14px;
        }

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

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

        .container-fluid {
            padding: 20px;
            scroll-padding-top: 70px; /* Height of your sticky header */
        }

        /* Ensure other elements don't overlap with sticky header */
        .table-container {
            position: relative;
            z-index: 1;
        }

        /* Add gap styling for flexbox items */
        .gap-3 {
            gap: 1rem;
        }

        .table {
            background-color: #ffffff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .table thead th {
            background-color: #2c3e50;
            color: #fff;
            padding: 12px;
        }

        .low-stock {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
        }

        .expiring-soon {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }

        .search-form {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        @media (max-width: 768px) {
            .table {
                font-size: 0.8rem;
            }

            .table th,
            .table td {
                padding: 0.3rem;
            }

            h2 {
                font-size: 1.5rem;
            }
        }

        .product-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 5px;
            transition: transform 0.3s ease;
        }

        .product-image:hover {
            transform: scale(1.1);
        }

        #imageModalImg {
            max-width: 100%;
            max-height: 80vh;
            object-fit: contain;
        }

        .modal-header.image-header {
            background: #2c3e50;
            color: white;
        }
    </style>
</head>

<body>
    <?php if (isset($_SESSION['error'])): ?>
        <script type="text/javascript">
            alert("<?php echo $_SESSION['error']; ?>");
        </script>
        <?php unset($_SESSION['error']); // Clear the error message after displaying it 
        ?>
    <?php elseif (isset($_SESSION['success'])): ?>
        <script type="text/javascript">
            alert("<?php echo $_SESSION['success']; ?>");
        </script>
        <?php unset($_SESSION['success']); // Clear the success message after displaying it 
        ?>
    <?php endif; ?>
    <?php

    if (isset($_SESSION['success'])) { ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['success']); // Clear the session message 
        ?>
    <?php } elseif (isset($_SESSION['error'])) { ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['error']); // Clear the session message 
        ?>
    <?php }
    ?>
    <div class="container-fluid">
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center w-100">
                <div class="d-flex align-items-center gap-3">
                    <a href="<?php echo ($_SESSION['role'] == 'manager') ? 'manager_dashboard.php' : 'admin_dashboard.php'; ?>" 
                       class="btn btn-primary">
                        <i class="fas fa-arrow-left"></i> Dashboard
                    </a>
                    <h2 class="mb-0">Manage Products</h2>
                </div>
                <div>
                    <a href="add_drug.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add New Product
                    </a>
                </div>
            </div>
        </div>

        <div class="alert alert-warning alert-notification" role="alert">
            <?php if (count($lowStockAlert) > 0): ?>
                <strong><i class="fas fa-exclamation-triangle"></i> Low Stock Alert:</strong> <?php echo implode(', ', $lowStockAlert); ?> (Quantity < 10)
                    <?php endif; ?>
                    <?php if (count($expiringSoonAlert) > 0): ?>
                    <strong>Expiring Soon:</strong> <?php echo implode(', ', $expiringSoonAlert); ?> (Expiring within 2 months)
                <?php endif; ?>
        </div>
        <!-- Wrap the search input and button in a form tag -->
        <form action="" method="POST" class="search-form">
            <input type="text" name="search" class="form-control" placeholder="Search by drug name"
                value="<?php echo htmlspecialchars($searchTerm); ?>" id="searchInput" onkeyup="showSuggestions(this.value)">
            <div id="suggestions" class="list-group"></div>
            <button class="btn btn-primary mt-2" type="submit">Search</button>
        </form>


        <div class="table-container">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th><a href="?sort=id&order=<?php echo $sortOrder; ?>" class="text-light">ID</a></th>
                        <th style="width: 80px;">Image</th>
                        <th><a href="?sort=drug_name&order=<?php echo $sortOrder; ?>" class="text-light">Product Name</a></th>
                        <th><a href="?sort=quantity&order=<?php echo $sortOrder; ?>" class="text-light">Stock</a></th>
                        <th><a href="?sort=cost_price&order=<?php echo $sortOrder; ?>" class="text-light">Cost Price</a></th>
                        <th><a href="?sort=selling_price&order=<?php echo $sortOrder; ?>" class="text-light">Selling Price</a></th>
                        <th><a href="?sort=expiration_date&order=<?php echo $sortOrder; ?>" class="text-light">Expiry Date</a></th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="drugTableBody">
                    <?php if (count($drugs) > 0): ?>
                        <?php foreach ($drugs as $drug):
                            $expirationDate = new DateTime($drug['expiration_date']);
                            $isExpiring = ($expirationDate->diff($today)->days <= 60 && $expirationDate > $today);
                        ?>
                            <tr class="<?php echo ($drug['quantity'] < 10 ? 'low-stock' : '') . ($isExpiring ? ' expiring-soon' : ''); ?>">
                                <td><?php echo htmlspecialchars($drug['id']); ?></td>
                                <td>
                                    <?php if (!empty($drug['image_path'])): ?>
                                        <img src="<?php echo htmlspecialchars($drug['image_path']); ?>" 
                                             class="product-image" 
                                             alt="<?php echo htmlspecialchars($drug['drug_name']); ?>"
                                             data-bs-toggle="modal" 
                                             data-bs-target="#imageModal"
                                             data-img-src="<?php echo htmlspecialchars($drug['image_path']); ?>"
                                             style="cursor: pointer;">
                                    <?php else: ?>
                                        <img src="uploads/products/default.png" 
                                             class="product-image" 
                                             alt="No image">
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($drug['drug_name']); ?></td>
                                <td><?php echo htmlspecialchars($drug['quantity']); ?></td>
                                <td><?php echo htmlspecialchars($drug['cost_price']); ?></td>
                                <td><?php echo htmlspecialchars($drug['selling_price']); ?></td>

                                <td><?php echo htmlspecialchars($drug['expiration_date']); ?></td>
                                <td>
                                   <!--  <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editDrugModal"
                                        data-id="<?php echo $drug['id']; ?>"
                                        data-name="<?php echo htmlspecialchars($drug['drug_name']); ?>"
                                        data-quantity="<?php echo htmlspecialchars($drug['quantity']); ?>"
                                        data-cost="<?php echo htmlspecialchars($drug['cost_price']); ?>"
                                        data-selling="<?php echo htmlspecialchars($drug['selling_price']); ?>"
                                        data-category="<?php echo htmlspecialchars($drug['category']); ?>"
                                        data-expiration="<?php echo htmlspecialchars($drug['expiration_date']); ?>"
                                        data-volume-size="<?php echo htmlspecialchars($drug['volume_size']); ?>"
                                        data-volume-price="<?php echo htmlspecialchars($drug['volume_price']); ?>">


                                        Edit
                                    </button> -->
                                    <a href="edit_drug.php?id=<?= $drug['id']; ?>" class="btn btn-warning btn-sm">Edit</a>

                                    <!-- <a href="delete_drug.php?id=<?php echo $drug['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this drug?');">Delete</a> -->
                                    <a href="view_drug_history.php?id=<?= $drug['id']; ?>" class="btn btn-primary btn-sm">View History</a>

                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center">No drugs found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>


        <!-- Edit Drug Modal -->
        <!-- Edit Drug 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">Edit Product Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Edit Drug Form -->
                        <form id="editDrugForm" action="update_drug.php" method="POST" onsubmit="return validateForm()">
                            <input type="hidden" name="id" id="editDrugId">
                            <div class="mb-3">
                                <label for="editDrugName" class="form-label">Drug Name</label>
                                <input type="text" class="form-control" id="editDrugName" name="drug_name" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="editQuantity" class="form-label">Current Quantity</label>
                                <input type="number" class="form-control" id="editQuantity" name="quantity" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="editAddQuantity" class="form-label">Add Quantity</label>
                                <input type="number" class="form-control" id="editAddQuantity" name="add_quantity" placeholder="Enter quantity to add">
                            </div>
                            <div class="mb-3">
                                <label for="editRemoveQuantity" class="form-label">Remove Quantity</label>
                                <input type="number" class="form-control" id="editRemoveQuantity" name="remove_quantity" placeholder="Enter quantity to remove">
                            </div>
                            <div class="mb-3">
                                <label for="editCost" class="form-label">Cost Price</label>
                                <input type="text" class="form-control" id="editCost" name="cost_price">
                            </div>
                            <div class="mb-3">
                                <label for="editSelling" class="form-label">Selling Price</label>
                                <input type="text" class="form-control" id="editSelling" name="selling_price">
                            </div>
                            <div class="mb-3">
                                <label for="editCategory" class="form-label">Category</label>
                                <input type="text" class="form-control" id="editCategory" name="category">
                            </div>
                            <div class="mb-3">
                                <label for="editExpiration" class="form-label">Expiration Date</label>
                                <input type="date" class="form-control" id="editExpiration" name="expiration_date">
                            </div>
                            <div class="mb-3">
                                <label for="editVolumeSize" class="form-label">Volume Size</label>
                                <input type="text" class="form-control" id="editVolumeSize" name="volume_size" value="">
                            </div>
                            <div class="mb-3">
                                <label for="editVolumePrice" class="form-label">Volume Price</label>
                                <input type="text" class="form-control" id="editVolumePrice" name="volume_price" value="">
                            </div>

                            <button type="submit" class="btn btn-primary">Update Drug</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <script>
            function validateForm() {
                var currentQuantity = parseInt(document.getElementById('editQuantity').value);
                var removeQuantity = parseInt(document.getElementById('editRemoveQuantity').value);

                if (removeQuantity > currentQuantity) {
                    alert("Remove quantity cannot be greater than the current quantity.");
                    return false; // Prevent form submission
                }
                return true; // Allow form submission
            }
        </script>



        <script>
            // Populate the edit drug modal with data
            editDrugModal.addEventListener('show.bs.modal', event => {
                const button = event.relatedTarget;

                // Fetch data attributes
                const id = button.getAttribute('data-id');
                const name = button.getAttribute('data-name');
                const quantity = button.getAttribute('data-quantity');
                const cost = button.getAttribute('data-cost');
                const selling = button.getAttribute('data-selling');
                const category = button.getAttribute('data-category');
                const expiration = button.getAttribute('data-expiration');
                const volumeSize = button.getAttribute('data-volume-size');
                const volumePrice = button.getAttribute('data-volume-price');

                console.log("Volume Size:", volumeSize); // Debug
                console.log("Volume Price:", volumePrice); // Debug

                // Select modal inputs
                editDrugModal.querySelector('#editDrugId').value = id;
                editDrugModal.querySelector('#editDrugName').value = name;
                editDrugModal.querySelector('#editQuantity').value = quantity;
                editDrugModal.querySelector('#editCost').value = cost;
                editDrugModal.querySelector('#editSelling').value = selling;
                editDrugModal.querySelector('#editCategory').value = category;
                editDrugModal.querySelector('#editExpiration').value = expiration;
                editDrugModal.querySelector('#editVolumeSize').value = volumeSize;
                editDrugModal.querySelector('#editVolumePrice').value = volumePrice;

                // Reset Add/Remove Quantity fields
                editDrugModal.querySelector('#editAddQuantity').value = '';
                editDrugModal.querySelector('#editRemoveQuantity').value = '';
            });


            // Prevent form submission unless a quantity adjustment is made
            const editDrugForm = document.getElementById('editDrugForm');
            editDrugForm.addEventListener('submit', function(event) {
                const addQuantity = document.getElementById('editAddQuantity').value;
                const removeQuantity = document.getElementById('editRemoveQuantity').value;


            });
        </script>


        <div class="footer">
            <p>&copy; <?php echo date("Y"); ?> Store Management System. All rights reserved.</p>
        </div>
    </div>



    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        // Populate the edit drug modal with data
        editDrugModal.addEventListener('show.bs.modal', event => {
            const button = event.relatedTarget;

            // Fetch data attributes
            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');
            const quantity = button.getAttribute('data-quantity');
            const cost = button.getAttribute('data-cost');
            const selling = button.getAttribute('data-selling');
            const category = button.getAttribute('data-category');
            const expiration = button.getAttribute('data-expiration');
            const volumeSize = button.getAttribute('data-volume-size');
            const volumePrice = button.getAttribute('data-volume-price');

            console.log("Volume Size:", volumeSize); // Debug
            console.log("Volume Price:", volumePrice); // Debug

            // Select modal inputs
            editDrugModal.querySelector('#editDrugId').value = id;
            editDrugModal.querySelector('#editDrugName').value = name;
            editDrugModal.querySelector('#editQuantity').value = quantity;
            editDrugModal.querySelector('#editCost').value = cost;
            editDrugModal.querySelector('#editSelling').value = selling;
            editDrugModal.querySelector('#editCategory').value = category;
            editDrugModal.querySelector('#editExpiration').value = expiration;
            editDrugModal.querySelector('#editVolumeSize').value = volumeSize;
            editDrugModal.querySelector('#editVolumePrice').value = volumePrice;

            // Reset Add/Remove Quantity fields
            editDrugModal.querySelector('#editAddQuantity').value = '';
            editDrugModal.querySelector('#editRemoveQuantity').value = '';
        });



        function showSuggestions(str) {
            if (str.length === 0) {
                document.getElementById("suggestions").innerHTML = "";
                return;
            }
            const xhr = new XMLHttpRequest();
            xhr.open("GET", "search_suggestions.php?q=" + encodeURIComponent(str), true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById("suggestions").innerHTML = xhr.responseText;
                    document.getElementById("suggestions").style.display = "block";
                }
            };
            xhr.send();
        }

        // Function to fill the search input with the selected suggestion
        function selectSuggestion(drugName) {
            document.getElementById("searchInput").value = drugName;
            document.getElementById("suggestions").style.display = "none"; // Hide suggestions after selection
            document.getElementById("suggestions").innerHTML = ""; // Clear suggestions after selection
        }

        // Hide suggestions when clicking outside the suggestions box
        document.addEventListener("click", function(event) {
            const suggestionsBox = document.getElementById("suggestions");
            const searchInput = document.getElementById("searchInput");

            if (!suggestionsBox.contains(event.target) && event.target !== searchInput) {
                suggestionsBox.style.display = "none";
            }
        });
    </script>
    
    <!-- Add this before the closing body tag -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header image-header">
                    <h5 class="modal-title">Product Image</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="" id="imageModalImg" alt="Product Image">
                </div>
            </div>
        </div>
    </div>

    <script>
        // Add this to your existing script section
        document.addEventListener('DOMContentLoaded', function() {
            const imageModal = document.getElementById('imageModal');
            const modalImg = document.getElementById('imageModalImg');

            imageModal.addEventListener('show.bs.modal', function(event) {
                const img = event.relatedTarget;
                const imgSrc = img.getAttribute('data-img-src');
                modalImg.src = imgSrc;
            });
        });
    </script>
</body>

</html>