<?php
// Include database connection
include '../config/db.php'; // Adjust the path as necessary
session_start();

// Check if the user is logged in and has an admin role
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Update function and variable names
function get_product_history($pdo, $product_id) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM drug_history WHERE drug_id = ? ORDER BY action_date DESC");
        $stmt->execute([$product_id]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        die("Error fetching product history: " . $e->getMessage());
    }
}

// Update search functionality
$product_history = [];
if (isset($_POST['search'])) {
    $search_term = htmlspecialchars($_POST['search_term']);
    try {
        $stmt = $pdo->prepare("SELECT id, drug_name as product_name FROM drugs WHERE drug_name LIKE ? LIMIT 1");
        $stmt->execute(['%' . $search_term . '%']);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($product) {
            $product_id = $product['id'];
            $product_history = get_product_history($pdo, $product_id);
        } else {
            echo "No product found with that name.";
        }
    } catch (PDOException $e) {
        die("Error searching for product: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product History</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>
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            overflow-x: hidden;
            font-size: 14px;
        }

        .container {
            padding: 20px;
        }

        .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;
        }

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

        .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;
        }

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

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

        #drug-suggestions {
            position: absolute;
            z-index: 1000;
            width: 100%;
            max-height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-bar">
            <h2>Product History</h2>
            <a href="<?php echo ($_SESSION['role'] == 'admin') ? 'admin_dashboard.php' : 'manager_dashboard.php'; ?>" 
               class="btn btn-primary">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
        </div>

        <div class="search-form">
            <form method="POST">
                <div class="form-group">
                    <label for="search_term">Search Product by Name:</label>
                    <input type="text" class="form-control" name="search_term" id="search_term" 
                           required autocomplete="off" placeholder="Enter product name...">
                    <div id="drug-suggestions" class="list-group mt-2" style="display: none;"></div>
                </div>
                <button type="submit" class="btn btn-primary" name="search">
                    <i class="fas fa-search"></i> Search
                </button>
            </form>
        </div>

        <?php if (count($product_history) > 0): ?>
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>Action</th>
                            <th>Quantity</th>
                            <th>Details</th>
                            <th>User</th>
                            <th>Action Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($product_history as $history): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($history['action']); ?></td>
                                <td><?php echo htmlspecialchars($history['quantity']); ?></td>
                                <td><?php echo htmlspecialchars($history['details']); ?></td>
                                <td><?php echo htmlspecialchars($history['user']); ?></td>
                                <td><?php echo htmlspecialchars($history['action_date']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php elseif (isset($_POST['search'])): ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> No history found for this product.
            </div>
        <?php endif; ?>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            // Handle input for drug search and show suggestions
            $('#search_term').keyup(function() {
                var query = $(this).val();
                if (query.length > 0) {
                    $.ajax({
                        url: "search.php", // Use a separate PHP file to fetch suggestions
                        method: "GET",
                        data: { query: query },
                        success: function(response) {
                            $('#drug-suggestions').html(response).show();
                        }
                    });
                } else {
                    $('#drug-suggestions').hide();
                }
            });

            // When a drug suggestion is selected
            $(document).on('click', '.suggestion-item', function() {
                var drugName = $(this).text();
                $('#search_term').val(drugName);
                $('#drug-suggestions').hide();
                // Optionally, trigger a form submission or AJAX call here to fetch the drug's history
            });
        });
    </script>
</body>
</html>
