<?php
include 'config.php';
include 'auth.php';
checkAuth();
$user = getCurrentUser();

// Handle opening cash form submission BEFORE cashier-only block
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['opening_cash'])) {
    $opening_cash = floatval($_POST['opening_cash']);
    $cash_date = date('Y-m-d');
    $entered_by = $user['username'];
    // Check if already entered for today
    $stmt = $conn->prepare("SELECT id FROM opening_cash WHERE cash_date = ? AND entered_by = ?");
    $stmt->bind_param("ss", $cash_date, $entered_by);
    $stmt->execute();
    $exists = $stmt->get_result()->fetch_assoc();
    if ($exists) {
        // Update existing
        $stmt = $conn->prepare("UPDATE opening_cash SET amount = ?, entered_by = ?, entered_at = NOW() WHERE cash_date = ? AND entered_by = ?");
        $stmt->bind_param("dsss", $opening_cash, $entered_by, $cash_date, $entered_by);
        $stmt->execute();
    } else {
        // Insert new
        $stmt = $conn->prepare("INSERT INTO opening_cash (cash_date, amount, entered_by) VALUES (?, ?, ?)");
        $stmt->bind_param("sds", $cash_date, $opening_cash, $entered_by);
        $stmt->execute();
    }
    // Redirect cashier to POS after saving opening cash
    if ($user['role'] === 'cashier') {
        header('Location: pos/index.php');
        exit;
    }
    echo '<div class="alert alert-success">Opening cash saved for today!</div>';
}

// Cashier: if opening cash set, redirect to POS. If not, show only opening cash form.
if ($user['role'] === 'cashier') {
    $cash_date = date('Y-m-d');
    $stmt = $conn->prepare("SELECT amount FROM opening_cash WHERE cash_date = ? AND entered_by = ?");
    $stmt->bind_param("ss", $cash_date, $user['username']);
    $stmt->execute();
    $opening_cash_today = $stmt->get_result()->fetch_assoc();
    if ($opening_cash_today) {
        header('Location: pos/index.php');
        exit;
    }
    // Only show opening cash form, skip rest of dashboard
    ?>
    <!DOCTYPE html>
    <html><head>
        <title>Enter Opening Cash - POS</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head><body style="background:#f8f9fa;">
    <div class="container" style="max-width:400px;margin-top:80px;">
        <div class="card p-4 shadow">
            <h3 class="mb-3 text-center">Enter Opening Cash</h3>
            <form method="post">
                <div class="mb-3">
                    <label for="opening_cash" class="form-label">Opening Cash Amount</label>
                    <input type="number" step="0.01" min="0" class="form-control" id="opening_cash" name="opening_cash" required autofocus>
                </div>
                <button type="submit" class="btn btn-primary w-100">Save & Go to POS</button>
            </form>
        </div>
    </div>
    </body></html>
    <?php exit; }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Dilrukshi Tex</title>
    <!-- Preconnect to CDNs for faster loading -->
    <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
    <link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
    <!-- Critical CSS inline for faster first paint -->
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .navbar { background: rgba(255,255,255,0.95) !important; backdrop-filter: blur(10px); }
        .main-content { padding: 20px 0; }
        .pos-card { 
            background: rgba(255,255,255,0.95); 
            border-radius: 15px; 
            box-shadow: 0 8px 32px rgba(0,0,0,0.1); 
            border: 1px solid rgba(255,255,255,0.2);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            backdrop-filter: blur(10px);
        }
        .pos-card:hover { 
            transform: translateY(-5px); 
            box-shadow: 0 12px 40px rgba(0,0,0,0.2);
        }
        .pos-icon { font-size: 3rem; margin-bottom: 1rem; }
        .quick-stats { background: rgba(255,255,255,0.95); border-radius: 15px; backdrop-filter: blur(10px); }
        .feature-badge { position: absolute; top: -8px; right: -8px; }
        .module-grid { position: relative; }
        
        /* Icon fallback handling */
        .fas::before { display: inline-block; }
        .icon-fallback { font-style: normal; font-size: 3rem; margin-bottom: 1rem; display: inline-block; }
        
        /* Ensure Font Awesome icons load properly */
        .fas { font-family: "Font Awesome 6 Free", "Font Awesome 5 Free", FontAwesome; font-weight: 900; }
    </style>
    <!-- Async CSS loading for non-critical resources -->
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></noscript>
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"></noscript>
</head>
<body>
    <?php
    // Handle opening cash form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['opening_cash'])) {
        $opening_cash = floatval($_POST['opening_cash']);
        $cash_date = date('Y-m-d');
        $entered_by = $user['username'];
        // Check if already entered for today
        $stmt = $conn->prepare("SELECT id FROM opening_cash WHERE cash_date = ?");
        $stmt->bind_param("s", $cash_date);
        $stmt->execute();
        $exists = $stmt->get_result()->fetch_assoc();
        if ($exists) {
            // Update existing
            $stmt = $conn->prepare("UPDATE opening_cash SET amount = ?, entered_by = ?, entered_at = NOW() WHERE cash_date = ?");
            $stmt->bind_param("dss", $opening_cash, $entered_by, $cash_date);
            $stmt->execute();
        } else {
            // Insert new
            $stmt = $conn->prepare("INSERT INTO opening_cash (cash_date, amount, entered_by) VALUES (?, ?, ?)");
            $stmt->bind_param("sds", $cash_date, $opening_cash, $entered_by);
            $stmt->execute();
        }
        // Redirect cashier to POS after saving opening cash
        if ($user['role'] === 'cashier') {
            header('Location: pos/index.php');
            exit;
        }
        echo '<div class="alert alert-success">Opening cash saved for today!</div>';
    }
    // Get today's opening cash
    $cash_date = date('Y-m-d');
    $stmt = $conn->prepare("SELECT amount FROM opening_cash WHERE cash_date = ?");
    $stmt->bind_param("s", $cash_date);
    $stmt->execute();
    $opening_cash_today = $stmt->get_result()->fetch_assoc();
    $opening_cash_value = $opening_cash_today ? $opening_cash_today['amount'] : '';
    ?>
    <nav class="navbar navbar-expand-lg navbar-light fixed-top">
        <div class="container">
            <a class="navbar-brand fw-bold" href="#"><i class="fas fa-store"></i> Dilrukshi Tex</a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    <i class="fas fa-user-circle"></i> <?= htmlspecialchars($user['full_name']) ?> 
                    <span class="badge bg-<?= $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'manager' ? 'warning' : 'info') ?> ms-1">
                        <?= ucfirst($user['role']) ?>
                    </span>
                </span>
                <a class="nav-link" href="pos/"><i class="fas fa-cash-register"></i> POS Terminal</a>
                <?php if ($user['role'] !== 'cashier') { ?>
                <a class="nav-link" href="reports/"><i class="fas fa-chart-bar"></i> Reports</a>
                <?php } ?>
                <?php if ($user['role'] === 'admin') { ?>
                <a class="nav-link" href="admin/"><i class="fas fa-cogs"></i> Admin</a>
                <?php } ?>
                <a class="nav-link" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>
    </nav>

    <div class="container main-content" style="margin-top: 80px;">
        <div class="row mb-4">
            <div class="col-12">
                <div class="quick-stats p-4 text-center">
                    <h2 class="fw-bold mb-3">Dilrukshi Tex Dashboard
                        <span class="badge bg-success ms-2">Professional Edition</span>
                    </h2>
                    <div class="row">
                        <div class="col-md-2">
                            <h4 class="text-primary">Today's Sales</h4>
                            <h3 id="todaySales">$0.00</h3>
                        </div>
                        <div class="col-md-2">
                            <h4 class="text-success">Products</h4>
                            <h3 id="totalProducts">0</h3>
                        </div>
                        <div class="col-md-2">
                            <h4 class="text-warning">Low Stock</h4>
                            <h3 id="lowStock" style="cursor:pointer;" data-bs-toggle="modal" data-bs-target="#lowStockModal">0</h3>
                        </div>
                        <div class="col-md-2">
                            <h4 class="text-info">Customers</h4>
                            <h3 id="totalCustomers">0</h3>
                        </div>
                        <div class="col-md-2">
                            <h4 class="text-danger">Categories</h4>
                            <h3 id="totalSuppliers">0</h3>
                        </div>
                        <div class="col-md-2">
                            <h4 class="text-secondary">Users</h4>
                            <h3 id="activeUsers">0</h3>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <h4 class="text-warning">Opening Cash</h4>
                            <h3 id="openingCash">Rs 0.00</h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row g-4">
            <!-- Opening Cash Card -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-warning feature-badge">CASH</span>
                    <i class="fas fa-money-bill-wave pos-icon text-warning"></i>
                    <h4>Opening Cash</h4>
                    <form method="POST" class="mt-3">
                        <div class="mb-2">
                            <label for="opening_cash" class="form-label fw-bold">Enter Opening Cash (Today):</label>
                            <input type="number" step="0.01" min="0" class="form-control text-center" name="opening_cash" id="opening_cash" value="<?= htmlspecialchars($opening_cash_value) ?>" required>
                        </div>
                        <button type="submit" class="btn btn-warning w-100">Save</button>
                    </form>
                </div>
            </div>
            <!-- Barcode Generator -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-info feature-badge">TOOL</span>
                    <i class="fas fa-barcode pos-icon text-info"></i>
                    <h4>Barcode Generator</h4>
                    <p>Create and print product barcodes</p>
                    <a href="barcode_generator.php" class="btn btn-info btn-lg">Generate Barcode</a>
                </div>
            </div>
            <!-- POS Terminal -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-success feature-badge">CORE</span>
                    <i class="fas fa-cash-register pos-icon text-primary"></i>
                    <h4>POS Terminal</h4>
                    <p>Complete sales processing with barcode scanning</p>
                    <a href="pos/" class="btn btn-primary btn-lg">Start Sale</a>
                </div>
            </div>

            <!-- Daily Summary -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-info feature-badge">DAILY</span>
                    <i class="fas fa-file-alt pos-icon text-info"></i>
                    <h4>Daily Summary</h4>
                    <p>Daily sales report & cash till reconciliation</p>
                    <a href="reports/daily_summary.php" class="btn btn-info btn-lg">View Summary</a>
                </div>
            </div>

            <!-- Products -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-success feature-badge">CORE</span>
                    <i class="fas fa-box pos-icon text-success"></i>
                    <h4>Products</h4>
                    <p>Complete product catalog with wholesale & profit tracking</p>
                    <a href="products/products.php" class="btn btn-success btn-lg">Manage Products</a>
                </div>
            </div>

            <!-- Inventory -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-warning feature-badge">PRO</span>
                    <i class="fas fa-warehouse pos-icon text-warning"></i>
                    <h4>Inventory</h4>
                    <p>Advanced stock management & tracking</p>
                    <a href="inventory/" class="btn btn-warning btn-lg">Manage Inventory</a>
                </div>
            </div>

            <!-- Customers -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-success feature-badge">CORE</span>
                    <i class="fas fa-users pos-icon text-info"></i>
                    <h4>Customers</h4>
                    <p>Customer database & purchase history</p>
                    <a href="customers/" class="btn btn-info btn-lg">Manage Customers</a>
                </div>
            </div>

            <!-- Expenses -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-warning feature-badge">DAILY</span>
                    <i class="fas fa-receipt pos-icon text-warning"></i>
                    <h4>Expenses</h4>
                    <p>Track daily business expenses & costs</p>
                    <a href="expenses/" class="btn btn-warning btn-lg">Add Expenses</a>
                </div>
            </div>

            <!-- Suppliers -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-warning feature-badge">PRO</span>
                    <i class="fas fa-truck pos-icon text-danger"></i>
                    <h4>Suppliers</h4>
                    <p>Supplier management & purchase orders</p>
                    <a href="suppliers/" class="btn btn-danger btn-lg">Manage Suppliers</a>
                </div>
            </div>

            <?php if ($user['role'] !== 'cashier'): ?>
            <!-- Reports -->
            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-success feature-badge">CORE</span>
                    <i class="fas fa-chart-line pos-icon text-purple"></i>
                    <h4>Reports</h4>
                    <p>Sales analytics & business intelligence</p>
                    <a href="reports/" class="btn btn-secondary btn-lg">View Reports</a>
                </div>
            </div>


               <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-success feature-badge">CORE</span>
                    <i class="fas fa-coins pos-icon text-danger"></i>
                    <h4>Sales Reports</h4>
                    <p>Sales analytics </p>
                    <a href="sales/sales.php" class="btn btn-secondary btn-lg">View Reports</a>
                </div>
            </div>

            <div class="col-lg-4 col-md-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-info feature-badge">COMMISSIONS</span>
                    <i class="fas fa-hand-holding-usd pos-icon text-info"></i>
                    <h4>Sales Commissions</h4>
                    <p>Monthly totals by sales officer</p>
                    <a href="reports/commissions.php" class="btn btn-info btn-lg">View Commissions</a>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($user['role'] === 'admin'): ?>
            <!-- Admin Panel -->
            <div class="col-lg-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-danger feature-badge">ADMIN</span>
                    <i class="fas fa-cogs pos-icon text-dark"></i>
                    <h4>Admin Panel</h4>
                    <p>System administration & user management</p>
                    <a href="admin/" class="btn btn-dark btn-lg">Admin Panel</a>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-danger feature-badge">ADMIN</span>
                    <i class="fas fa-user-tie pos-icon text-primary"></i>
                    <h4>Sales Officers</h4>
                    <p>Manage sales representatives</p>
                    <a href="sales_officers.php" class="btn btn-primary btn-lg">Manage Officers</a>
                </div>
            </div>

            <!-- Security Dashboard -->
            <div class="col-lg-6">
                <div class="pos-card p-4 text-center h-100 module-grid">
                    <span class="badge bg-warning feature-badge">🛡️ NEW</span>
                    <i class="fas fa-shield-alt pos-icon text-warning"></i>
                    <h4>Security Monitor</h4>
                    <p>Real-time security monitoring & bot protection</p>
                    <a href="security_dashboard.php" class="btn btn-warning btn-lg">
                        <i class="fas fa-shield-alt"></i> Security Center
                    </a>
                </div>
            </div>

            <!-- System Tools -->
            <div class="col-lg-6">
                <div class="pos-card p-4">
                    <h5><i class="fas fa-tools"></i> System Tools</h5>
                    <div class="row g-2">
                        <div class="col-6">
                            <a href="setup_check.php" class="btn btn-outline-primary w-100 btn-sm">
                                <i class="fas fa-check-circle"></i> System Check
                            </a>
                        </div>
                        <div class="col-6">
                            <a href="case_closed.php" class="btn btn-outline-success w-100 btn-sm">
                                <i class="fas fa-check-double"></i> Mystery Solved
                            </a>
                        </div>
                        <div class="col-6">
                            <a href="admin/settings.php" class="btn btn-outline-warning w-100 btn-sm">
                                <i class="fas fa-cog"></i> Settings
                            </a>
                        </div>
                        <div class="col-6">
                            <a href="detective.php" class="btn btn-outline-info w-100 btn-sm">
                                <i class="fas fa-search"></i> Detective
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Feature Overview -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="pos-card p-4">
                    <h5 class="text-center mb-4"><i class="fas fa-star"></i> Professional Features</h5>
                    <div class="row text-center">
                        <div class="col-md-2">
                            <i class="fas fa-barcode fa-2x text-primary mb-2"></i>
                            <p><small>Barcode Scanning</small></p>
                        </div>
                        <div class="col-md-2">
                            <i class="fas fa-receipt fa-2x text-success mb-2"></i>
                            <p><small>Receipt Printing</small></p>
                        </div>
                        <div class="col-md-2">
                            <i class="fas fa-users-cog fa-2x text-info mb-2"></i>
                            <p><small>User Management</small></p>
                        </div>
                        <div class="col-md-2">
                            <i class="fas fa-chart-pie fa-2x text-warning mb-2"></i>
                            <p><small>Advanced Reports</small></p>
                        </div>
                        <div class="col-md-2">
                            <i class="fas fa-shield-alt fa-2x text-danger mb-2"></i>
                            <p><small>Role-based Access</small></p>
                        </div>
                        <div class="col-md-2">
                            <i class="fas fa-mobile-alt fa-2x text-secondary mb-2"></i>
                            <p><small>Mobile Responsive</small></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Low Stock Modal -->
    <div class="modal fade" id="lowStockModal" tabindex="-1" aria-labelledby="lowStockModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="lowStockModalLabel">Low Stock Items</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div id="lowStockList">Loading...</div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" defer></script>
    <script>
        // Enhanced dashboard stats with debouncing and performance optimization
        let statsCache = null;
        let lastFetch = 0;
        const CACHE_DURATION = 30000; // 30 seconds cache for better performance
        
        async function loadStats() {
            try {
                // Use cached data if recent
                const now = Date.now();
                if (statsCache && (now - lastFetch < CACHE_DURATION)) {
                    updateUI(statsCache);
                    return;
                }
                
                const response = await fetch('./api/enhanced_stats.php', {
                    method: 'GET',
                    cache: 'no-cache', // Always fetch fresh data
                    credentials: 'same-origin'
                });
                
                if (!response.ok) {
                    if (response.status === 401) {
                        window.location.href = './login.php';
                        return;
                    }
                    throw new Error('HTTP error ' + response.status);
                }
                
                const stats = await response.json();
                statsCache = stats;
                lastFetch = now;
                updateUI(stats);
            } catch (error) {
                console.error('Error loading stats:', error);
                // Retry once after a short delay
                setTimeout(loadStats, 2000);
            }
        }
        
        function updateUI(stats) {
            document.getElementById('todaySales').textContent = stats.todaySales;
            document.getElementById('totalProducts').textContent = stats.totalProducts;
            document.getElementById('lowStock').textContent = stats.lowStock;
            document.getElementById('totalCustomers').textContent = stats.totalCustomers;
            document.getElementById('totalSuppliers').textContent = stats.totalSuppliers;
            document.getElementById('activeUsers').textContent = stats.activeUsers;
            document.getElementById('openingCash').textContent = 'Rs ' + Number(stats.openingCash).toFixed(2);
            var recElem = document.getElementById('reconciliationOpeningCash');
            if (recElem) {
                recElem.textContent = 'Rs ' + Number(stats.openingCash).toFixed(2);
            }
        }
        
        // Load stats when page is ready - defer to improve initial page load
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => setTimeout(loadStats, 100));
        } else {
            setTimeout(loadStats, 100);
        }
        // Refresh every 60 seconds to reduce server load
        setInterval(loadStats, 60000);
        
        // Icon fallback system
        function checkFontAwesome() {
            setTimeout(function() {
                const testIcon = document.querySelector('.fas.fa-shield-alt');
                if (testIcon) {
                    const computedStyle = window.getComputedStyle(testIcon, '::before');
                    const content = computedStyle.getPropertyValue('content');
                    
                    if (!content || content === 'none' || content === '""') {
                        console.log('Font Awesome not loaded, applying emoji fallbacks');
                        
                        // Add emoji fallbacks for key icons
                        const iconFallbacks = {
                            'fa-shield-alt': '🛡️',
                            'fa-cash-register': '💰',
                            'fa-barcode': '📊', 
                            'fa-box': '📦',
                            'fa-chart-line': '📈',
                            'fa-users': '👥',
                            'fa-cogs': '⚙️'
                        };
                        
                        Object.keys(iconFallbacks).forEach(function(iconClass) {
                            const icons = document.querySelectorAll('.fas.' + iconClass + '.pos-icon');
                            icons.forEach(function(icon) {
                                icon.innerHTML = iconFallbacks[iconClass];
                                icon.className = 'icon-fallback text-' + (icon.className.match(/text-(\w+)/) || ['', 'primary'])[1];
                            });
                        });
                    } else {
                        console.log('Font Awesome loaded successfully');
                    }
                }
            }, 1000);
        }
        
        checkFontAwesome();

        // Low Stock Modal
        document.addEventListener('DOMContentLoaded', function() {
          var lowStockModal = document.getElementById('lowStockModal');
          if (lowStockModal) {
            lowStockModal.addEventListener('show.bs.modal', function () {
              fetch('/malshanlast/api/low_stock.php', {
                method: 'GET',
                cache: 'no-cache',
                credentials: 'same-origin'
              })
                .then(response => {
                  if (!response.ok) {
                    if (response.status === 401) {
                      window.location.href = '/malshanlast/login.php';
                      return;
                    }
                    throw new Error('HTTP error ' + response.status);
                  }
                  return response.json();
                })
                .then(data => {
                  if (!data) return;
                  let html = '<table class="table table-bordered table-striped"><thead><tr><th>Product</th><th>Stock</th><th>Min Stock</th></tr></thead><tbody>';
                  if (data.length > 0) {
                    data.forEach(item => {
                      html += `<tr><td>${item.name}</td><td>${item.stock}</td><td>${item.min_stock}</td></tr>`;
                    });
                  } else {
                    html += '<tr><td colspan="3" class="text-center">No low stock items.</td></tr>';
                  }
                  html += '</tbody></table>';
                  document.getElementById('lowStockList').innerHTML = html;
                })
                .catch((error) => {
                  console.error('Low stock fetch error:', error);
                  document.getElementById('lowStockList').innerHTML = '<div class="text-danger">Failed to load low stock items. Please refresh the page.</div>';
                });
            });
          }
        });
    </script>
</body>
</html>
