<?php include '../store_keeper/auth_check.php'; ?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Store Keeper Dashboard - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="./store-keeper-theme.css?v=1.1">
    <style>
        .metric-strip {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 16px;
            margin-bottom: 22px;
        }

        .metric-card {
            position: relative;
            overflow: hidden;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 16px 16px 14px;
            background: radial-gradient(circle at top right, rgba(37, 99, 235, 0.12), transparent 42%),
                        linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
            box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
            transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        }

        .metric-card::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: #2563eb;
        }

        .metric-card.warning::before {
            background: #f59e0b;
        }

        .metric-card.danger::before {
            background: #ef4444;
        }

        .metric-card.success::before {
            background: #10b981;
        }

        .metric-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 14px 28px rgba(15, 23, 42, 0.12);
            border-color: rgba(37, 99, 235, 0.35);
        }

        .metric-card::after {
            content: "";
            position: absolute;
            right: -26px;
            bottom: -32px;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(37, 99, 235, 0.08);
            pointer-events: none;
        }

        .metric-card.warning::after {
            background: rgba(245, 158, 11, 0.12);
        }

        .metric-card.danger::after {
            background: rgba(239, 68, 68, 0.12);
        }

        .metric-card.success::after {
            background: rgba(16, 185, 129, 0.12);
        }

        .metric-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 8px;
        }

        .metric-card .label {
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.02em;
            text-transform: uppercase;
            color: var(--text-secondary);
        }

        .metric-icon {
            width: 34px;
            height: 34px;
            border-radius: 10px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: rgba(37, 99, 235, 0.14);
            color: #1d4ed8;
            font-size: 14px;
            box-shadow: 0 6px 14px rgba(37, 99, 235, 0.18);
        }

        .metric-card.warning .metric-icon {
            background: rgba(245, 158, 11, 0.18);
            color: #b45309;
            box-shadow: 0 6px 14px rgba(245, 158, 11, 0.2);
        }

        .metric-card.danger .metric-icon {
            background: rgba(239, 68, 68, 0.16);
            color: #b91c1c;
            box-shadow: 0 6px 14px rgba(239, 68, 68, 0.18);
        }

        .metric-card.success .metric-icon {
            background: rgba(16, 185, 129, 0.18);
            color: #047857;
            box-shadow: 0 6px 14px rgba(16, 185, 129, 0.18);
        }

        .metric-card .value {
            font-size: 38px;
            line-height: 1.1;
            font-weight: 900;
            letter-spacing: -0.02em;
            color: #0f172a;
            text-shadow: 0 2px 0 rgba(255, 255, 255, 0.65);
        }

        .metric-card .trend {
            margin-top: 6px;
            font-size: 12px;
            font-weight: 600;
            color: var(--text-secondary);
        }

        @media (max-width: 768px) {
            .metric-card .value {
                font-size: 30px;
            }
        }
    </style>
    <title>Store Keeper Dashboard</title>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="dashboard-container">
    <div class="main-content">
        <div class="page-header">
            <div class="page-header-content">
                <h1>Dashboard</h1>
            <p>Real-time overview of inventory and stock management</p>
        </div>
        <div class="page-actions">
            <button class="btn btn-primary" onclick="location.href='stock_receiving.php'">
                <i class="fas fa-box-open"></i> Receive Stock
            </button>
        </div>
    </div>

    <!-- KEY METRICS -->
    <div class="metric-strip" id="metricStrip">
        <div class="metric-card">
            <div class="metric-head">
                <div class="label">Total Active Ingredients</div>
                <span class="metric-icon"><i class="fas fa-seedling"></i></span>
            </div>
            <div class="value" id="totalIngredients">0</div>
        </div>
        <div class="metric-card warning">
            <div class="metric-head">
                <div class="label">Low Stock Items</div>
                <span class="metric-icon"><i class="fas fa-triangle-exclamation"></i></span>
            </div>
            <div class="value" id="lowStockCount">0</div>
            <div class="trend">Needs attention</div>
        </div>
        <div class="metric-card danger">
            <div class="metric-head">
                <div class="label">Expiring Soon (7 days)</div>
                <span class="metric-icon"><i class="fas fa-hourglass-end"></i></span>
            </div>
            <div class="value" id="expiringCount">0</div>
            <div class="trend">Critical</div>
        </div>
        <div class="metric-card success">
            <div class="metric-head">
                <div class="label">Stock Received Today</div>
                <span class="metric-icon"><i class="fas fa-box-open"></i></span>
            </div>
            <div class="value" id="receivedToday">0</div>
        </div>
    </div>

    <!-- MAIN CONTENT GRID -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 20px; margin-bottom: 20px;">
        
        <!-- LOW STOCK ITEMS -->
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-exclamation-triangle"></i> Low Stock Items</h2>
            </div>
            <div class="card-body">
                <div id="lowStockList" style="max-height: 400px; overflow-y: auto;">
                    <div style="text-align: center; padding: 20px; color: var(--text-secondary);">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
            </div>
        </div>

        <!-- EXPIRING ITEMS -->
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-calendar-times"></i> Items Expiring Soon</h2>
            </div>
            <div class="card-body">
                <div id="expiringList" style="max-height: 400px; overflow-y: auto;">
                    <div style="text-align: center; padding: 20px; color: var(--text-secondary);">
                        <i class="fas fa-spinner fa-spin"></i> Loading...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- RECENT ACTIVITIES -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fas fa-history"></i> Recent Stock Activities</h2>
        </div>
        <div class="card-body">
            <table class="table">
                <thead>
                    <tr>
                        <th>Date & Time</th>
                        <th>Ingredient</th>
                        <th>Action</th>
                        <th>Quantity</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody id="activityList">
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 30px; color: var(--text-secondary);">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3/dist/chart.min.js"></script>

<script>
    // Initialize page
    document.addEventListener('DOMContentLoaded', () => {
        loadDashboardData();
        // Refresh every 5 minutes
        setInterval(loadDashboardData, 300000);
    });

    async function loadDashboardData() {
        try {
            // Load all metrics in parallel
            await Promise.all([
                loadMetrics(),
                loadLowStockItems(),
                loadExpiringItems(),
                loadRecentActivities()
            ]);
        } catch (error) {
            console.error('Error loading dashboard:', error);
        }
    }

    async function logApiError(response, context) {
        let bodyText = '';
        try {
            bodyText = await response.text();
            const payload = JSON.parse(bodyText);
            if (payload && payload.message) {
                console.error(`${context} - HTTP ${response.status}: ${payload.message}`);
                return;
            }
        } catch (error) {
            // Ignore parse errors and log raw response below.
        }

        console.error(`${context} - HTTP ${response.status}${bodyText ? `: ${bodyText}` : ''}`);
    }

    async function loadMetrics() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_metrics', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                await logApiError(response, 'Metrics API error');
                return;
            }
            
            const data = await response.json();
            
            if (data.success) {
                document.getElementById('totalIngredients').textContent = data.data.total_ingredients || 0;
                document.getElementById('lowStockCount').textContent = data.data.low_stock_count || 0;
                document.getElementById('expiringCount').textContent = data.data.expiring_count || 0;
                document.getElementById('receivedToday').textContent = data.data.received_today || 0;
            } else {
                console.error('Metrics API error:', data.message);
            }
        } catch (error) {
            console.error('Error loading metrics:', error);
        }
    }

    async function loadLowStockItems() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_low_stock', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                await logApiError(response, 'Low stock API error');
                document.getElementById('lowStockList').innerHTML = '<div class="alert alert-danger">Error loading low stock items</div>';
                return;
            }
            
            const data = await response.json();
            
            const list = document.getElementById('lowStockList');
            
            if (data.success && data.data && data.data.length > 0) {
                list.innerHTML = data.data.map(item => `
                    <div style="padding: 12px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div style="font-weight: 600; color: var(--text-primary);">${item.name}</div>
                            <div style="font-size: 12px; color: var(--text-secondary);">
                                Stock: ${parseFloat(item.current_stock).toFixed(2)} / Min: ${parseFloat(item.minimum_stock).toFixed(2)} ${item.unit}
                            </div>
                        </div>
                        <button class="btn btn-sm btn-warning" onclick="location.href='stock_receiving.php?ingredient_id=${item.id}'">
                            <i class="fas fa-plus"></i> Receive
                        </button>
                    </div>
                `).join('');
            } else {
                list.innerHTML = '<div style="text-align: center; padding: 30px; color: var(--text-secondary);"><i class="fas fa-check-circle"></i> All stock levels are adequate</div>';
            }
        } catch (error) {
            console.error('Error loading low stock:', error);
            document.getElementById('lowStockList').innerHTML = '<div class="alert alert-danger">Error loading low stock items</div>';
        }
    }

    async function loadExpiringItems() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_expiring_soon', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                await logApiError(response, 'Expiring items API error');
                document.getElementById('expiringList').innerHTML = '<div class="alert alert-danger">Error loading expiring items</div>';
                return;
            }
            
            const data = await response.json();
            
            const list = document.getElementById('expiringList');
            
            if (data.success && data.data && data.data.length > 0) {
                list.innerHTML = data.data.map(item => `
                    <div style="padding: 12px; border-bottom: 1px solid var(--border-color); border-left: 3px solid var(--danger-color);">
                        <div style="font-weight: 600; color: var(--text-primary);">${item.ingredient_name}</div>
                        <div style="font-size: 12px; color: var(--text-secondary);">
                            Expires: ${item.expiry_date} (${item.days_until_expiry} days)
                        </div>
                        <div style="margin-top: 8px;">
                            <span class="badge danger">${parseFloat(item.current_stock || 0).toFixed(2)} ${item.unit || 'unit'}</span>
                        </div>
                    </div>
                `).join('');
            } else {
                list.innerHTML = '<div style="text-align: center; padding: 30px; color: var(--text-secondary);"><i class="fas fa-check-circle"></i> No items expiring soon</div>';
            }
        } catch (error) {
            console.error('Error loading expiring items:', error);
            document.getElementById('expiringList').innerHTML = '<div class="alert alert-danger">Error loading expiring items</div>';
        }
    }

    async function loadRecentActivities() {
        try {
            const response = await fetch('../backend/store_keeper_api.php?action=get_recent_activities', {
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                await logApiError(response, 'Recent activities API error');
                document.getElementById('activityList').innerHTML = '<tr><td colspan="5" class="alert alert-danger">Error loading activities</td></tr>';
                return;
            }
            
            const data = await response.json();
            
            const tbody = document.getElementById('activityList');
            
            if (data.success && data.data && data.data.length > 0) {
                tbody.innerHTML = data.data.map(activity => {
                    const actionClass = activity.action === 'add' ? 'success' : 'warning';
                    const actionIcon = activity.action === 'add' ? 'plus' : 'minus';
                    return `
                        <tr>
                            <td>${new Date(activity.created_at).toLocaleString()}</td>
                            <td><strong>${activity.ingredient_name}</strong></td>
                            <td><span class="badge ${actionClass}"><i class="fas fa-${actionIcon}"></i> ${activity.action.toUpperCase()}</span></td>
                            <td>${parseFloat(activity.quantity_changed).toFixed(2)} ${activity.unit}</td>
                            <td>${activity.reason || '-'}</td>
                        </tr>
                    `;
                }).join('');
            } else {
                tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: var(--text-secondary);">No recent activities</td></tr>';
            }
        } catch (error) {
            console.error('Error loading activities:', error);
            document.getElementById('activityList').innerHTML = '<tr><td colspan="5" class="alert alert-danger">Error loading activities</td></tr>';
        }
    }

    function handleLogout() {
        Swal.fire({
            title: 'Logout',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, logout',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('../backend/store_keeper_login.php?action=logout', {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(() => {
                    window.location.href = 'index.php';
                }).catch(error => console.error('Logout error:', error));
            }
        });
    }
</script>

<script src="store-keeper-sidebar.js"></script>
</body>
</html>

