<?php
/**
 * Dashboard — WITH USER-BOUND DATA
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session for API calls
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// AUTH CHECK
$auth_token = $_COOKIE['rcp_auth'] ?? null;
if (!$auth_token) {
    header("Location: login.php");
    exit;
}

try {
    require_once __DIR__ . '/../includes/config.php';
    require_once __DIR__ . '/../includes/database.php';
    
    $pdo = Database::getInstance()->getConnection();
    
    $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
    $stmt->execute([$auth_token]);
    $session_data = $stmt->fetchColumn();
    
    if (!$session_data) {
        header("Location: login.php");
        exit;
    }
    
    $user = json_decode($session_data, true);
    $user_id = $user['user_id'] ?? $user['id'] ?? null;
    
    if (!$user_id) {
        die("User ID not found in session.");
    }
    
    // Store user_id in session for API calls
    $_SESSION['user_id'] = $user_id;
    
    // Update last activity
    $user['last_activity'] = time();
    $updateStmt = $pdo->prepare("UPDATE user_sessions SET session_data = ?, expires_at = DATE_ADD(NOW(), INTERVAL 2 HOUR) WHERE session_id = ?");
    $updateStmt->execute([json_encode($user), $auth_token]);
    
    // Let's first check what tables and columns actually exist
    $tables = [];
    try {
        $tableResult = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        $tables = array_flip($tableResult);
    } catch (Exception $e) {
        // Continue with empty tables array
    }
    
    // Get recent costings - user-bound
    $recentCostings = [];
    if (isset($tables['recipe_costings'])) {
        try {
            // Check if recipe_costings has user_id column
            $columns = $pdo->query("SHOW COLUMNS FROM recipe_costings")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            $selectColumns = ['id', 'created_at'];
            if (isset($columnMap['recipe_name'])) {
                $selectColumns[] = 'recipe_name';
            } elseif (isset($columnMap['name'])) {
                $selectColumns[] = 'name as recipe_name';
            } elseif (isset($columnMap['title'])) {
                $selectColumns[] = 'title as recipe_name';
            }
            
            $query = "SELECT " . implode(', ', $selectColumns) . " FROM recipe_costings";
            
            // Add user filter if user_id column exists
            if (isset($columnMap['user_id'])) {
                $query .= " WHERE user_id = ?";
                $stmt = $pdo->prepare($query . " ORDER BY created_at DESC LIMIT 5");
                $stmt->execute([$user_id]);
                $recentCostings = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } else {
                // If no user_id column, show all (fallback)
                $recentCostings = $pdo->query($query . " ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
            }
        } catch (Exception $e) {
            $recentCostings = [];
        }
    }
    
    // Get recent meals - user-bound
    $recentMeals = [];
    if (isset($tables['meals'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM meals")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            $selectColumns = ['id', 'created_at'];
            if (isset($columnMap['meal_name'])) {
                $selectColumns[] = 'meal_name';
            } elseif (isset($columnMap['name'])) {
                $selectColumns[] = 'name as meal_name';
            } elseif (isset($columnMap['title'])) {
                $selectColumns[] = 'title as meal_name';
            } elseif (isset($columnMap['recipe_name'])) {
                $selectColumns[] = 'recipe_name as meal_name';
            }
            
            $query = "SELECT " . implode(', ', $selectColumns) . " FROM meals";
            
            if (isset($columnMap['user_id'])) {
                $query .= " WHERE user_id = ?";
                $stmt = $pdo->prepare($query . " ORDER BY created_at DESC LIMIT 5");
                $stmt->execute([$user_id]);
                $recentMeals = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } else {
                // Try recipes table if meals doesn't work
                try {
                    $columns = $pdo->query("SHOW COLUMNS FROM recipes")->fetchAll(PDO::FETCH_COLUMN);
                    $columnMap = array_flip($columns);
                    
                    $selectColumns = ['id', 'created_at'];
                    if (isset($columnMap['recipe_name'])) {
                        $selectColumns[] = 'recipe_name as meal_name';
                    } elseif (isset($columnMap['name'])) {
                        $selectColumns[] = 'name as meal_name';
                    } elseif (isset($columnMap['title'])) {
                        $selectColumns[] = 'title as meal_name';
                    }
                    
                    $query = "SELECT " . implode(', ', $selectColumns) . " FROM recipes";
                    if (isset($columnMap['user_id'])) {
                        $query .= " WHERE user_id = ?";
                        $stmt = $pdo->prepare($query . " ORDER BY created_at DESC LIMIT 5");
                        $stmt->execute([$user_id]);
                        $recentMeals = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    } else {
                        $recentMeals = $pdo->query($query . " ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
                    }
                } catch (Exception $e2) {
                    $recentMeals = [];
                }
            }
        } catch (Exception $e) {
            $recentMeals = [];
        }
    }
    
    // Get recent production schedules - user-bound
    $recentSchedules = [];
    if (isset($tables['production_schedules'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM production_schedules")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            $query = "SELECT id, schedule_name, created_at, unit_name FROM production_schedules";
            if (isset($columnMap['user_id'])) {
                $query .= " WHERE user_id = ?";
                $stmt = $pdo->prepare($query . " ORDER BY created_at DESC LIMIT 5");
                $stmt->execute([$user_id]);
                $recentSchedules = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } else {
                $recentSchedules = $pdo->query($query . " ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
            }
        } catch (Exception $e) {
            $recentSchedules = [];
        }
    }
    
    // Get statistics based on user-bound data
    $stats = [];
    
    // Total meals costed - user-bound
    if (isset($tables['recipe_costings'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM recipe_costings")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            if (isset($columnMap['user_id'])) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM recipe_costings WHERE user_id = ?");
                $stmt->execute([$user_id]);
                $stats['total_meals_costed'] = $stmt->fetchColumn();
            } else {
                $stats['total_meals_costed'] = $pdo->query("SELECT COUNT(*) FROM recipe_costings")->fetchColumn();
            }
        } catch (Exception $e) {
            $stats['total_meals_costed'] = 0;
        }
    } else {
        $stats['total_meals_costed'] = 0;
    }
    
    // Total meals - user-bound
    $stats['total_meals'] = 0;
    if (isset($tables['meals'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM meals")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            if (isset($columnMap['user_id'])) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM meals WHERE user_id = ?");
                $stmt->execute([$user_id]);
                $stats['total_meals'] = $stmt->fetchColumn();
            } else {
                $stats['total_meals'] = $pdo->query("SELECT COUNT(*) FROM meals")->fetchColumn();
            }
        } catch (Exception $e) {
            // Try recipes table
            if (isset($tables['recipes'])) {
                try {
                    $columns = $pdo->query("SHOW COLUMNS FROM recipes")->fetchAll(PDO::FETCH_COLUMN);
                    $columnMap = array_flip($columns);
                    
                    if (isset($columnMap['user_id'])) {
                        $stmt = $pdo->prepare("SELECT COUNT(*) FROM recipes WHERE user_id = ?");
                        $stmt->execute([$user_id]);
                        $stats['total_meals'] = $stmt->fetchColumn();
                    } else {
                        $stats['total_meals'] = $pdo->query("SELECT COUNT(*) FROM recipes")->fetchColumn();
                    }
                } catch (Exception $e2) {
                    $stats['total_meals'] = 0;
                }
            }
        }
    }
    
    // Total ingredients - user-bound
    if (isset($tables['ingredients'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM ingredients")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            if (isset($columnMap['user_id'])) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM ingredients WHERE user_id = ?");
                $stmt->execute([$user_id]);
                $stats['total_ingredients'] = $stmt->fetchColumn();
            } else {
                $stats['total_ingredients'] = $pdo->query("SELECT COUNT(*) FROM ingredients")->fetchColumn();
            }
        } catch (Exception $e) {
            $stats['total_ingredients'] = 0;
        }
    } else {
        $stats['total_ingredients'] = 0;
    }
    
    // Recent activity count (last 7 days) - user-bound
    $recentActivity = ['recent_costings' => 0, 'recent_meals' => 0];
    
    // Recent costings count
    if (isset($tables['recipe_costings'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM recipe_costings")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            $query = "SELECT COUNT(*) FROM recipe_costings WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
            if (isset($columnMap['user_id'])) {
                $query .= " AND user_id = ?";
                $stmt = $pdo->prepare($query);
                $stmt->execute([$user_id]);
                $recentActivity['recent_costings'] = $stmt->fetchColumn();
            } else {
                $recentActivity['recent_costings'] = $pdo->query($query)->fetchColumn();
            }
        } catch (Exception $e) {
            // Ignore error
        }
    }
    
    // Recent meals count
    if (isset($tables['meals'])) {
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM meals")->fetchAll(PDO::FETCH_COLUMN);
            $columnMap = array_flip($columns);
            
            $query = "SELECT COUNT(*) FROM meals WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
            if (isset($columnMap['user_id'])) {
                $query .= " AND user_id = ?";
                $stmt = $pdo->prepare($query);
                $stmt->execute([$user_id]);
                $recentActivity['recent_meals'] = $stmt->fetchColumn();
            } else {
                $recentActivity['recent_meals'] = $pdo->query($query)->fetchColumn();
            }
        } catch (Exception $e) {
            // Try recipes table
            if (isset($tables['recipes'])) {
                try {
                    $columns = $pdo->query("SHOW COLUMNS FROM recipes")->fetchAll(PDO::FETCH_COLUMN);
                    $columnMap = array_flip($columns);
                    
                    $query = "SELECT COUNT(*) FROM recipes WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
                    if (isset($columnMap['user_id'])) {
                        $query .= " AND user_id = ?";
                        $stmt = $pdo->prepare($query);
                        $stmt->execute([$user_id]);
                        $recentActivity['recent_meals'] = $stmt->fetchColumn();
                    } else {
                        $recentActivity['recent_meals'] = $pdo->query($query)->fetchColumn();
                    }
                } catch (Exception $e2) {
                    // Ignore error
                }
            }
        }
    }
    
    $stats['recent_activity'] = $recentActivity;
    
    // Most recent costing - user-bound
    $latestCosting = ['recipe_name' => 'No costings yet', 'created_at' => null];
    if (!empty($recentCostings)) {
        $latestCosting = $recentCostings[0];
    }
    $stats['latest_costing'] = $latestCosting;
    
    // Most recent meal - user-bound
    $latestMeal = ['meal_name' => 'No meals yet', 'created_at' => null];
    if (!empty($recentMeals)) {
        $latestMeal = $recentMeals[0];
    }
    $stats['latest_meal'] = $latestMeal;
    
    // Check if we have any data at all
    $stats['has_data'] = ($stats['total_meals_costed'] > 0 || $stats['total_meals'] > 0);
    
} catch (Throwable $t) {
    die("Error: " . $t->getMessage());
}

// Check for includes
$hasNavbar = is_file(__DIR__ . '/../includes/navbar.php');
$hasFooter = is_file(__DIR__ . '/../includes/footer.php');

// Logo path - adjust based on where you uploaded the logo
$logoPath = '../assets/images/serve-smart-logo.png';
$logoExists = file_exists(__DIR__ . '/' . $logoPath);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Serve Pro - Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/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; 
            padding-top: 0;
        }
        .card { 
            border-radius: 10px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border: none;
            transition: transform 0.2s ease-in-out;
        }
        .card:hover {
            transform: translateY(-2px);
        }
        .metric-value { 
            font-size: 2rem; 
            font-weight: bold; 
        }
        .btn-custom {
            background-color: #8B0000;
            color: white;
            border: none;
        }
        .btn-custom:hover {
            background-color: #600000;
            color: white;
        }
        .btn-outline-custom {
            border-color: #8B0000;
            color: #8B0000;
        }
        .btn-outline-custom:hover {
            background-color: #8B0000;
            color: white;
        }
        .recent-item {
            border-left: 4px solid #8B0000;
            padding: 12px 15px;
            margin-bottom: 10px;
            background: white;
            border-radius: 5px;
            transition: all 0.2s ease;
            cursor: pointer;
        }
        .recent-item:hover {
            background: #f8f9fa;
            transform: translateX(5px);
        }
        .recent-item a {
            text-decoration: none;
            color: inherit;
            display: block;
        }
        .stat-card {
            background: linear-gradient(135deg, #8B0000, #600000);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        .activity-badge {
            background: rgba(255,255,255,0.2);
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            margin: 5px;
        }
        .welcome-card {
            background: linear-gradient(135deg, #8B0000 0%, #600000 100%);
            color: white;
            position: relative;
            overflow: hidden;
        }
        .welcome-logo {
            max-height: 80px;
            margin-bottom: 15px;
        }
        .welcome-content {
            position: relative;
            z-index: 2;
        }
        .welcome-background {
            position: absolute;
            top: 20px;
            right: 20px;
            opacity: 0.1;
            max-height: 120px;
            z-index: 1;
        }
    </style>
</head>
<body>
    <?php if ($hasNavbar) include __DIR__ . '/../includes/navbar.php'; ?>

    <main class="rcp-main">
        <div class="container mt-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>My Dashboard</h1>
                <span class="text-muted">Welcome, <?= htmlspecialchars($user['user_full_name'] ?? $user['user_email']) ?></span>
            </div>

            <!-- WELCOME & QUICK STATS -->
            <div class="row mb-4">
                <div class="col-md-8 mb-3">
                    <div class="card welcome-card h-100">
                        <!-- Background Logo -->
                        <?php if ($logoExists): ?>
                            <img src="<?= $logoPath ?>" alt="Serve Smart Logo" class="welcome-background">
                        <?php endif; ?>
                        
                        <div class="card-body welcome-content">
                            <!-- Main Logo -->
                            <?php if ($logoExists): ?>
                                <img src="<?= $logoPath ?>" alt="Serve Smart Logo" class="welcome-logo">
                            <?php endif; ?>
                            
                            <h3 class="card-title">Welcome to Smart Serve Pro</h3>
                            <p class="card-text">
                                <?php if ($stats['has_data']): ?>
                                    You have <strong><?= $stats['total_meals_costed'] ?></strong> costed meals and 
                                    <strong><?= $stats['total_meals'] ?></strong> meals in your account.
                                    <?php if ($stats['recent_activity']['recent_costings'] > 0 || $stats['recent_activity']['recent_meals'] > 0): ?>
                                        <br>Great work! You've been active recently.
                                    <?php endif; ?>
                                <?php else: ?>
                                    Get started by creating your first meal and costing sheet!
                                <?php endif; ?>
                            </p>
                            <div class="d-flex gap-2 flex-wrap">
                                <span class="activity-badge">
                                    <i class="fas fa-calculator"></i> <?= $stats['total_meals_costed'] ?> Costings
                                </span>
                                <span class="activity-badge">
                                    <i class="fas fa-utensils"></i> <?= $stats['total_meals'] ?> Meals
                                </span>
                                <span class="activity-badge">
                                    <i class="fas fa-carrot"></i> <?= $stats['total_ingredients'] ?> Ingredients
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="card h-100">
                        <div class="card-body text-center">
                            <i class="fas fa-chart-line fa-3x text-primary mb-3"></i>
                            <h4>My Recent Activity</h4>
                            <div class="row text-center">
                                <div class="col-6">
                                    <div class="metric-value text-success"><?= $stats['recent_activity']['recent_costings'] ?></div>
                                    <small>Costings (7 days)</small>
                                </div>
                                <div class="col-6">
                                    <div class="metric-value text-warning"><?= $stats['recent_activity']['recent_meals'] ?></div>
                                    <small>Meals (7 days)</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- RECENT ACTIVITY -->
            <div class="row mb-4">
                <!-- Recent Costings -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-calculator text-warning"></i>
                                My Recent Costings
                            </h5>
                            <span class="badge bg-custom"><?= count($recentCostings) ?></span>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($recentCostings)): ?>
                                <?php foreach ($recentCostings as $costing): ?>
                                    <div class="recent-item">
                                        <a href="costing.php?action=view&id=<?= $costing['id'] ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <strong><?= htmlspecialchars($costing['recipe_name'] ?? 'Unnamed Costing') ?></strong>
                                                    <br>
                                                    <small class="text-muted">
                                                        Created <?= date('M j, Y', strtotime($costing['created_at'])) ?>
                                                    </small>
                                                </div>
                                                <i class="fas fa-chevron-right text-muted"></i>
                                            </div>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                                <div class="text-center mt-3">
                                    <a href="costing.php" class="btn btn-outline-custom btn-sm">View All My Costings</a>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-calculator"></i>
                                    <p>No costings yet</p>
                                    <a href="costing.php" class="btn btn-custom btn-sm">Create First Costing</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Recent Meals -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-utensils text-success"></i>
                                My Recent Meals
                            </h5>
                            <span class="badge bg-custom"><?= count($recentMeals) ?></span>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($recentMeals)): ?>
                                <?php foreach ($recentMeals as $meal): ?>
                                    <div class="recent-item">
                                        <a href="meals.php?action=view&id=<?= $meal['id'] ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <strong><?= htmlspecialchars($meal['meal_name'] ?? 'Unnamed Meal') ?></strong>
                                                    <br>
                                                    <small class="text-muted">
                                                        Created <?= date('M j, Y', strtotime($meal['created_at'])) ?>
                                                    </small>
                                                </div>
                                                <i class="fas fa-chevron-right text-muted"></i>
                                            </div>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                                <div class="text-center mt-3">
                                    <a href="meals.php" class="btn btn-outline-custom btn-sm">View All My Meals</a>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-utensils"></i>
                                    <p>No meals yet</p>
                                    <a href="meals.php" class="btn btn-custom btn-sm">Create First Meal</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Recent Schedules & Quick Stats -->
                <div class="col-md-4 mb-4">
                    <!-- Recent Production Schedules -->
                    <div class="card mb-4">
                        <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-calendar-alt text-info"></i>
                                My Recent Schedules
                            </h5>
                            <span class="badge bg-custom"><?= count($recentSchedules) ?></span>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($recentSchedules)): ?>
                                <?php foreach ($recentSchedules as $schedule): ?>
                                    <div class="recent-item">
                                        <a href="schedules.php?action=view&id=<?= $schedule['id'] ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <strong><?= htmlspecialchars($schedule['schedule_name']) ?></strong>
                                                    <br>
                                                    <small class="text-muted">
                                                        <?= htmlspecialchars($schedule['unit_name']) ?>
                                                    </small>
                                                </div>
                                                <i class="fas fa-chevron-right text-muted"></i>
                                            </div>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                                <div class="text-center mt-3">
                                    <a href="schedules.php" class="btn btn-outline-custom btn-sm">View All My Schedules</a>
                                </div>
                            <?php else: ?>
                                <div class="empty-state" style="padding: 20px 10px;">
                                    <i class="fas fa-calendar-alt"></i>
                                    <p>No schedules yet</p>
                                    <a href="schedules.php" class="btn btn-custom btn-sm">Create First Schedule</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Latest Activity -->
                    <div class="card">
                        <div class="card-header bg-white border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-clock text-primary"></i>
                                My Latest Activity
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if ($stats['has_data']): ?>
                                <div class="mb-3">
                                    <small class="text-muted">Latest Costing</small>
                                    <div class="fw-bold"><?= htmlspecialchars($stats['latest_costing']['recipe_name'] ?? 'No costings yet') ?></div>
                                    <?php if ($stats['latest_costing']['created_at']): ?>
                                        <small class="text-muted"><?= date('M j, g:i A', strtotime($stats['latest_costing']['created_at'])) ?></small>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <small class="text-muted">Latest Meal</small>
                                    <div class="fw-bold"><?= htmlspecialchars($stats['latest_meal']['meal_name'] ?? 'No meals yet') ?></div>
                                    <?php if ($stats['latest_meal']['created_at']): ?>
                                        <small class="text-muted"><?= date('M j, g:i A', strtotime($stats['latest_meal']['created_at'])) ?></small>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="text-center text-muted py-2">
                                    <i class="fas fa-inbox fa-2x mb-2"></i>
                                    <p>No activity yet</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <?php if ($hasFooter) include __DIR__ . '/../includes/footer.php'; ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Add interactivity
        document.addEventListener('DOMContentLoaded', function() {
            // Make recent items clickable
            const recentItems = document.querySelectorAll('.recent-item');
            recentItems.forEach(item => {
                item.addEventListener('click', function() {
                    const link = this.querySelector('a');
                    if (link) {
                        window.location.href = link.href;
                    }
                });
            });
            
            // Add loading animation
            const cards = document.querySelectorAll('.card');
            cards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(20px)';
                setTimeout(() => {
                    card.style.transition = 'all 0.5s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 100);
            });
        });
    </script>
</body>
</html>