<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
include '../auth.php';
checkAuth();

// Handle AJAX request for product history
if (isset($_GET['ajax']) && $_GET['ajax'] == '1' && !empty($_GET['product_id'])) {
    $product_id = (int)$_GET['product_id'];
    $history_limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    
    // Get product info
    $stmt = $conn->prepare("SELECT id, name, barcode, created_at FROM products WHERE id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc();
    
    if (!$product) {
        die('Product not found');
    }
    
    // Get product transaction history
    $stmt = $conn->prepare("
        SELECT it.*, u.full_name as user_name 
        FROM inventory_transactions it 
        JOIN users u ON it.created_by = u.id 
        WHERE it.product_id = ? 
        ORDER BY it.created_at DESC 
        LIMIT ?
    ");
    $stmt->bind_param("ii", $product_id, $history_limit);
    $stmt->execute();
    $transactions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    // Count total transactions for the product
    $count_stmt = $conn->prepare("SELECT COUNT(*) as total FROM inventory_transactions WHERE product_id = ?");
    $count_stmt->bind_param("i", $product_id);
    $count_stmt->execute();
    $total_rows = $count_stmt->get_result()->fetch_assoc()['total'] ?? 0;
    
    // Output HTML for history
    ?>
    <h6 class="text-info d-flex justify-content-between align-items-center">
        <span><i class="fas fa-history"></i> Transaction History for <?= htmlspecialchars($product['name']) ?></span>
        <small class="text-muted">Showing <?= count($transactions) ?> of <?= $total_rows ?> records</small>
    </h6>
    <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
        <table class="table table-sm table-striped mb-0">
            <thead class="table-light sticky-top">
                <tr>
                    <th><small>Date & Time</small></th>
                    <th><small>Type</small></th>
                    <th><small>Change</small></th>
                    <th><small>Stock</small></th>
                    <th><small>User</small></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($transactions)): ?>
                <tr>
                    <td colspan="5" class="text-center text-muted py-3">
                        <small>
                            <i class="fas fa-info-circle"></i>
                            No transactions yet. Product created on <strong><?= date('M d, Y', strtotime($product['created_at'] ?? 'now')) ?></strong>
                        </small>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($transactions as $t): ?>
                <tr>
                    <td><small><?= date('M d, H:i', strtotime($t['created_at'])) ?></small></td>
                    <td>
                        <small>
                            <span class="badge bg-<?= $t['transaction_type'] === 'sale' ? 'danger' : ($t['transaction_type'] === 'purchase' ? 'success' : 'warning') ?>">
                                <?= ucfirst($t['transaction_type']) ?>
                            </span>
                        </small>
                    </td>
                    <td>
                        <small class="fw-bold <?= $t['quantity_change'] > 0 ? 'text-success' : 'text-danger' ?>">
                            <?= $t['quantity_change'] > 0 ? '+' : '' ?><?= $t['quantity_change'] ?>
                        </small>
                    </td>
                    <td><small><?= $t['new_stock'] ?></small></td>
                    <td><small><?= htmlspecialchars(substr($t['user_name'], 0, 10)) ?></small></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($total_rows > $history_limit): ?>
    <div class="text-end mt-2">
        <button class="btn btn-sm btn-outline-primary" onclick="loadMoreHistory(<?= $product_id ?>, <?= min($total_rows, $history_limit + 50) ?>)">
            <i class="fas fa-plus-circle"></i> Load more
        </button>
    </div>
    <?php endif; ?>
    <?php
    exit;
}

// Get date range filters
$start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$product_filter = $_GET['product_id'] ?? '';
$limit = $_GET['limit'] ?? 50;

// Handle stock adjustment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['adjust_stock'])) {
    $product_id = $_POST['product_id'];
    $adjustment = (int)$_POST['adjustment'];
    $reason = $_POST['reason'];
    
    // Get current stock
    $stmt = $conn->prepare("SELECT stock FROM products WHERE id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $current_stock = $stmt->get_result()->fetch_assoc()['stock'];
    
    $new_stock = $current_stock + $adjustment;
    
    if ($new_stock >= 0) {
        // Update product stock
        $stmt = $conn->prepare("UPDATE products SET stock = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_stock, $product_id);
        $stmt->execute();
        
        // Log transaction
        $stmt = $conn->prepare("INSERT INTO inventory_transactions (product_id, transaction_type, quantity_change, old_stock, new_stock, notes, created_by) VALUES (?, 'adjustment', ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiisi", $product_id, $adjustment, $current_stock, $new_stock, $reason, $_SESSION['user_id']);
        $stmt->execute();
        
        $message = "Stock adjusted successfully!";
    } else {
        $error = "Cannot adjust stock below zero!";
    }
}

// Get low stock products
$low_stock_query = "
    SELECT p.*, c.name as category_name 
    FROM products p 
    LEFT JOIN categories c ON p.category_id = c.id 
    WHERE p.stock <= p.min_stock 
    ORDER BY p.stock ASC
";
$low_stock_products = $conn->query($low_stock_query)->fetch_all(MYSQLI_ASSOC);

// Get recent inventory transactions with filters
$transaction_query = "
    SELECT it.*, p.name as product_name, p.barcode, u.full_name as user_name 
    FROM inventory_transactions it 
    JOIN products p ON it.product_id = p.id 
    JOIN users u ON it.created_by = u.id 
    WHERE DATE(it.created_at) BETWEEN ? AND ?";

if (!empty($product_filter)) {
    $transaction_query .= " AND it.product_id = ?";
}

$transaction_query .= " ORDER BY it.created_at DESC LIMIT ?";

$stmt = $conn->prepare($transaction_query);

if (!empty($product_filter)) {
    $stmt->bind_param("ssii", $start_date, $end_date, $product_filter, $limit);
} else {
    $stmt->bind_param("ssi", $start_date, $end_date, $limit);
}

$stmt->execute();
$result = $stmt->get_result();
$recent_transactions = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

// Get product count for filtered results
$count_query = "SELECT COUNT(*) as total FROM inventory_transactions it WHERE DATE(it.created_at) BETWEEN ? AND ?";
if (!empty($product_filter)) {
    $count_query .= " AND it.product_id = ?";
}
$count_stmt = $conn->prepare($count_query);
if (!empty($product_filter)) {
    $count_stmt->bind_param("ssi", $start_date, $end_date, $product_filter);
} else {
    $count_stmt->bind_param("ss", $start_date, $end_date);
}
$count_stmt->execute();
$count_result = $count_stmt->get_result()->fetch_assoc();
$total_records = $count_result ? $count_result['total'] : 0;

// Get all products for adjustment (include price so UI can show it)
$all_products = $conn->query("SELECT id, name, stock, barcode, price FROM products ORDER BY name")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Inventory Management - Textile POS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
        .critical-stock { background-color: #f8d7da !important; }
        .low-stock { background-color: #fff3cd !important; }
        .good-stock { background-color: #d1e7dd !important; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-warehouse"></i> Inventory Management</h1>
            <div>
                <a href="../pos/" class="btn btn-success me-2"><i class="fas fa-cash-register"></i> POS</a>
                <a href="../" class="btn btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
            </div>
        </div>

        <?php if (isset($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= $error ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Quick Stats -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-exclamation-triangle fa-2x text-danger mb-2"></i>
                        <h3 class="text-danger"><?= count(array_filter($low_stock_products, fn($p) => $p['stock'] == 0)) ?></h3>
                        <small>Out of Stock</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-exclamation-circle fa-2x text-warning mb-2"></i>
                        <h3 class="text-warning"><?= count($low_stock_products) ?></h3>
                        <small>Low Stock Items</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-box fa-2x text-info mb-2"></i>
                        <h3 class="text-info"><?= $conn->query("SELECT COUNT(*) as count FROM products")->fetch_assoc()['count'] ?></h3>
                        <small>Total Products</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-dollar-sign fa-2x text-success mb-2"></i>
                        <h3 class="text-success">LKR<?= number_format($conn->query("SELECT SUM(stock * cost_price) as value FROM products")->fetch_assoc()['value'] ?? 0, 2) ?></h3>
                        <small>Inventory Value</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stock Transaction History (collapsible) -->
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h5 class="mb-0"><i class="fas fa-history text-info"></i> Stock Transaction History</h5>
            <div class="btn-group">
                <button id="showHistoryBtn" type="button" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i> Show</button>
                <button id="hideHistoryBtn" type="button" class="btn btn-sm btn-outline-secondary" style="display:none;"><i class="fas fa-eye-slash"></i> Hide</button>
            </div>
        </div>

        <div id="historyCard" class="card mb-4" style="display:none;">
            <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                <span><i class="fas fa-history"></i> Stock Transaction History</span>
                <span class="badge bg-light text-dark ms-2"><?= number_format($total_records ?? 0) ?> Total Records</span>
            </div>
            <div class="card-body">
                <!-- Date Range Filters -->
                <form method="GET" class="row g-3 mb-4">
                    <div class="col-md-3">
                        <label class="form-label fw-bold"><i class="fas fa-calendar-alt"></i> Start Date</label>
                        <input type="date" name="start_date" class="form-control" value="<?= htmlspecialchars($start_date) ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold"><i class="fas fa-calendar-alt"></i> End Date</label>
                        <input type="date" name="end_date" class="form-control" value="<?= htmlspecialchars($end_date) ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold"><i class="fas fa-box"></i> Filter by Product</label>
                        <select name="product_id" class="form-select">
                            <option value="">All Products</option>
                            <?php foreach ($all_products as $prod): ?>
                            <option value="<?= $prod['id'] ?>" <?= $product_filter == $prod['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($prod['name']) ?> (Stock: <?= $prod['stock'] ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-bold"><i class="fas fa-list"></i> Records</label>
                        <select name="limit" class="form-select">
                            <option value="20" <?= $limit == 20 ? 'selected' : '' ?>>20</option>
                            <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50</option>
                            <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                            <option value="200" <?= $limit == 200 ? 'selected' : '' ?>>200</option>
                            <option value="500" <?= $limit == 500 ? 'selected' : '' ?>>500</option>
                        </select>
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-filter"></i></button>
                    </div>
                </form>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div>
                        <small class="text-muted">
                            Showing <?= count($recent_transactions) ?> of <?= number_format($total_records ?? 0) ?> records
                            <?php if (!empty($product_filter)): ?>
                                <?php 
                                $selected_prod = array_filter($all_products, fn($p) => $p['id'] == $product_filter);
                                $selected_prod = reset($selected_prod);
                                ?>
                                for <strong><?= htmlspecialchars($selected_prod['name'] ?? 'Unknown') ?></strong>
                            <?php endif; ?>
                        </small>
                    </div>
                    <a href="?" class="btn btn-sm btn-outline-secondary"><i class="fas fa-redo"></i> Reset</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th><i class="fas fa-calendar"></i> Date & Time</th>
                                <th><i class="fas fa-box"></i> Product</th>
                                <th><i class="fas fa-barcode"></i> Barcode</th>
                                <th><i class="fas fa-tag"></i> Type</th>
                                <th><i class="fas fa-sort-numeric-up"></i> Change</th>
                                <th>Old Stock</th>
                                <th>New Stock</th>
                                <th><i class="fas fa-user"></i> User</th>
                                <th><i class="fas fa-sticky-note"></i> Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recent_transactions)): ?>
                            <tr>
                                <td colspan="9" class="text-center text-muted py-4">
                                    <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
                                    No transactions found for the selected date range.
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($recent_transactions as $transaction): ?>
                            <tr>
                                <td>
                                    <strong><?= date('M d, Y', strtotime($transaction['created_at'])) ?></strong><br>
                                    <small class="text-muted"><?= date('h:i:s A', strtotime($transaction['created_at'])) ?></small>
                                </td>
                                <td><strong><?= htmlspecialchars($transaction['product_name']) ?></strong></td>
                                <td><code><?= htmlspecialchars($transaction['barcode'] ?? 'N/A') ?></code></td>
                                <td>
                                    <span class="badge bg-<?= $transaction['transaction_type'] === 'sale' ? 'danger' : ($transaction['transaction_type'] === 'purchase' ? 'success' : 'warning') ?>">
                                        <?= ucfirst($transaction['transaction_type']) ?>
                                    </span>
                                </td>
                                <td class="fw-bold <?= $transaction['quantity_change'] > 0 ? 'text-success' : 'text-danger' ?>">
                                    <i class="fas fa-<?= $transaction['quantity_change'] > 0 ? 'arrow-up' : 'arrow-down' ?>"></i>
                                    <?= $transaction['quantity_change'] > 0 ? '+' : '' ?><?= number_format($transaction['quantity_change']) ?>
                                </td>
                                <td><span class="badge bg-secondary"><?= number_format($transaction['old_stock']) ?></span></td>
                                <td><span class="badge bg-<?= $transaction['new_stock'] > $transaction['old_stock'] ? 'success' : 'info' ?>"><?= number_format($transaction['new_stock']) ?></span></td>
                                <td><small><?= htmlspecialchars($transaction['user_name']) ?></small></td>
                                <td><small class="text-muted"><?= htmlspecialchars($transaction['notes'] ?? '-') ?></small></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Stock Adjustment -->
            <div class="col-lg-4 mb-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <i class="fas fa-edit"></i> Stock Adjustment
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="adjust_stock" value="1">
                            <div class="mb-3">
                                <label class="form-label">Product</label>
                                <input type="text" id="barcodeInput" class="form-control mb-2" placeholder="Scan barcode or enter barcode number...">
                                <select name="product_id" class="form-select" id="productSelect" required>
                                    <option value="">Select Product...</option>
                                    <?php foreach ($all_products as $product): ?>
                                    <option value="<?= $product['id'] ?>" data-barcode="<?= htmlspecialchars($product['barcode'] ?? '') ?>" data-name="<?= htmlspecialchars($product['name']) ?>" data-stock="<?= $product['stock'] ?>" data-price="<?= isset($product['price']) ? htmlspecialchars($product['price']) : '' ?>">
                                        <?= htmlspecialchars($product['name']) ?> (Current: <?= $product['stock'] ?><?= isset($product['price']) && $product['price'] !== null ? ' | Price: LKR ' . number_format((float)$product['price'], 2) : '' ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <div id="selectedProductInfo" class="mt-2" style="display:none;"></div>
                                <script>
                                function showSelectedProductInfo() {
                                    var select = document.getElementById('productSelect');
                                    var infoDiv = document.getElementById('selectedProductInfo');
                                    var idx = select.selectedIndex;
                                    if (idx > 0) {
                                        var opt = select.options[idx];
                                        var name = opt.dataset.name || '';
                                        var stock = opt.dataset.stock || '';
                                        var barcode = opt.dataset.barcode || '';
                                        var price = opt.dataset.price || '';
                                        var priceLabel = '';
                                        if (price !== '') {
                                            var numericPrice = parseFloat(price);
                                            priceLabel = isFinite(numericPrice) ? 'LKR ' + numericPrice.toFixed(2) : price;
                                        }
                                        infoDiv.innerHTML = `<div class='alert alert-info p-2 mb-2'><strong>Selected:</strong> ${name}<br><strong>Stock:</strong> ${stock}<br><strong>Barcode:</strong> ${barcode}${priceLabel ? '<br><strong>Price:</strong> ' + priceLabel : ''}</div>`;
                                        infoDiv.style.display = '';
                                    } else {
                                        infoDiv.innerHTML = '';
                                        infoDiv.style.display = 'none';
                                    }
                                }
                                document.getElementById('productSelect').addEventListener('change', showSelectedProductInfo);

                                // Load product transaction history when selected
                                document.getElementById('productSelect').addEventListener('change', function() {
                                    var productId = this.value;
                                    if (productId) {
                                        var historyDiv = document.getElementById('productHistoryModal');
                                        // Fetch transactions for this product via AJAX
                                        loadMoreHistory(productId, 50);
                                    }
                                });

                                // Helper to load history with a given limit
                                window.loadMoreHistory = function(productId, limit) {
                                    var historyDiv = document.getElementById('productHistoryModal');
                                    var url = window.location.pathname;
                                    url += (url.indexOf('?') > -1 ? '&' : '?') + 'product_id=' + productId + '&limit=' + limit + '&ajax=1';
                                    fetch(url)
                                        .then(r => r.text())
                                        .then(html => {
                                            historyDiv.innerHTML = html;
                                            historyDiv.style.display = '';
                                        })
                                        .catch(e => console.error('Error loading history:', e));
                                }

                                // Modal for multiple products with same barcode
                                function showBarcodeSelectModal(matches) {
                                    var modal = document.createElement('div');
                                    modal.id = 'barcodeSelectModal';
                                    modal.style.position = 'fixed';
                                    modal.style.top = '0';
                                    modal.style.left = '0';
                                    modal.style.width = '100vw';
                                    modal.style.height = '100vh';
                                    modal.style.background = 'rgba(0,0,0,0.4)';
                                    modal.style.zIndex = '9999';
                                    modal.innerHTML = `<div style="background:#fff;max-width:400px;margin:100px auto;padding:24px;border-radius:8px;box-shadow:0 2px 12px #0002;position:relative;">
                                        <h5>Select Product (Multiple Prices)</h5>
                                        <ul class='list-group mb-3'>
                                            ${matches.map(opt => {
                                                var displayPrice = '';
                                                if (opt.price !== '') {
                                                    var priceNum = parseFloat(opt.price);
                                                    displayPrice = isFinite(priceNum) ? 'LKR ' + priceNum.toFixed(2) : opt.price;
                                                }
                                                return `<li class='list-group-item d-flex justify-content-between align-items-center' style='cursor:pointer;' onclick='selectProductFromModal(${opt.index})'><span><strong>${opt.name}</strong><br>Stock: ${opt.stock}${displayPrice ? ' | Price: ' + displayPrice : ''}</span><span class='badge bg-primary'>ID: ${opt.id}</span></li>`;
                                            }).join('')}
                                        </ul>
                                        <button class='btn btn-secondary w-100' onclick='closeBarcodeSelectModal()'>Cancel</button>
                                    </div>`;
                                    document.body.appendChild(modal);
                                }
                                window.selectProductFromModal = function(idx) {
                                    var select = document.getElementById('productSelect');
                                    select.selectedIndex = idx;
                                    showSelectedProductInfo();
                                    closeBarcodeSelectModal();
                                }
                                window.closeBarcodeSelectModal = function() {
                                    var modal = document.getElementById('barcodeSelectModal');
                                    if (modal) modal.remove();
                                }

                                document.getElementById('barcodeInput').addEventListener('keydown', function(e) {
                                    if (e.key === 'Enter') {
                                        var barcode = this.value.trim();
                                        if (!barcode) return;
                                        var select = document.getElementById('productSelect');
                                        var matches = [];
                                        for (var i = 0; i < select.options.length; i++) {
                                            var opt = select.options[i];
                                            if (opt.dataset.barcode && opt.dataset.barcode === barcode) {
                                                matches.push({
                                                    index: i,
                                                    id: opt.value,
                                                    name: opt.dataset.name,
                                                    stock: opt.dataset.stock,
                                                    price: opt.dataset.price
                                                });
                                            }
                                        }
                                        if (matches.length === 1) {
                                            select.selectedIndex = matches[0].index;
                                            showSelectedProductInfo();
                                        } else if (matches.length > 1) {
                                            showBarcodeSelectModal(matches);
                                        } else {
                                            alert('No product found for this barcode.');
                                        }
                                        this.value = '';
                                    }
                                });
                                </script>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Adjustment (+/-)</label>
                                <input type="number" name="adjustment" class="form-control" required>
                                <small class="text-muted">Use negative numbers to reduce stock</small>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-save"></i> Adjust Stock
                            </button>
                        </form>
                        <!-- Product History Modal -->
                        <div id="productHistoryModal" style="display: none; margin-top: 20px; padding-top: 20px; border-top: 2px solid #e0e0e0;"></div>
                    </div>
                </div>
            </div>

            <!-- Low Stock Alerts -->
            <div class="col-lg-8 mb-4">
                <div class="card">
                    <div class="card-header bg-warning text-dark">
                        <i class="fas fa-exclamation-triangle"></i> Stock Alerts
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($low_stock_products)): ?>
                        <div class="p-4 text-center text-success">
                            <i class="fas fa-check-circle fa-3x mb-3"></i>
                            <h5>All products are well stocked!</h5>
                        </div>
                        <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped mb-0">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Category</th>
                                        <th>Current Stock</th>
                                        <th>Min Stock</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($low_stock_products as $product): ?>
                                    <?php 
                                    $stock_class = '';
                                    $status = '';
                                    if ($product['stock'] == 0) {
                                        $stock_class = 'critical-stock';
                                        $status = '<span class="badge bg-danger">Out of Stock</span>';
                                    } else {
                                        $stock_class = 'low-stock';
                                        $status = '<span class="badge bg-warning">Low Stock</span>';
                                    }
                                    ?>
                                    <tr class="<?= $stock_class ?>">
                                        <td><strong><?= htmlspecialchars($product['name']) ?></strong></td>
                                        <td><?= htmlspecialchars($product['category_name'] ?? 'N/A') ?></td>
                                        <td class="fw-bold"><?= $product['stock'] ?></td>
                                        <td><?= $product['min_stock'] ?></td>
                                        <td><?= $status ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle history visibility
        const historyCard = document.getElementById('historyCard');
        const showHistoryBtn = document.getElementById('showHistoryBtn');
        const hideHistoryBtn = document.getElementById('hideHistoryBtn');

        function showHistory() {
            historyCard.style.display = '';
            showHistoryBtn.style.display = 'none';
            hideHistoryBtn.style.display = '';
        }

        function hideHistory() {
            historyCard.style.display = 'none';
            hideHistoryBtn.style.display = 'none';
            showHistoryBtn.style.display = '';
        }

        showHistoryBtn?.addEventListener('click', showHistory);
        hideHistoryBtn?.addEventListener('click', hideHistory);
    </script>
</body>
</html>
