<?php
session_start();
require_once __DIR__ . '/db/config.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: login.php');
    exit;
}

$pdo = db();

// Fetch Stats
$totalCars = $pdo->query("SELECT COUNT(*) FROM cars WHERE deleted_at IS NULL")->fetchColumn();
$pendingCars = $pdo->query("SELECT COUNT(*) FROM cars WHERE status = 'pending' AND deleted_at IS NULL")->fetchColumn();
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users WHERE deleted_at IS NULL")->fetchColumn();
$totalPurchases = $pdo->query("SELECT COUNT(*) FROM purchases WHERE status = 'pending'")->fetchColumn();

// Fetch Recent Cars
$recentCars = $pdo->query("
    SELECT c.*, u.name as owner_name 
    FROM cars c 
    JOIN users u ON c.user_id = u.id 
    WHERE c.deleted_at IS NULL 
    ORDER BY c.created_at DESC 
    LIMIT 5
")->fetchAll();

// Fetch Recent Messages
$recentMessages = $pdo->query("SELECT * FROM contact_messages ORDER BY created_at DESC LIMIT 5")->fetchAll();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | AfgCars</title>
    <link rel="stylesheet" href="assets/css/fonts.css">
    <link rel="stylesheet" href="assets/css/style.css?v=<?= time() ?>">
</head>
<body>
    <div class="dashboard-container">
        <!-- Sidebar -->
        <aside class="sidebar">
            <a href="index.php" class="sidebar-brand">AFGCARS</a>
            <ul class="sidebar-menu">
                <li><a href="admin_dashboard.php" class="active"><span>Dashboard</span></a></li>
                <li><a href="admin_cars.php"><span>Manage Cars</span></a></li>
                <li><a href="admin_purchases.php"><span>Purchase Requests</span></a></li>
                <li><a href="admin_users.php"><span>Users</span></a></li>
                <li><a href="admin_messages.php"><span>Messages</span></a></li>
            </ul>
            <div class="sidebar-footer">
                <a href="logout.php" class="btn btn-danger btn-sm" style="width: 100%;">Logout</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <header class="mb-3" style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <h1 class="fw-bold" style="font-size: 2.5rem;">Dashboard Overview</h1>
                    <p class="text-secondary">Welcome back, <?= htmlspecialchars($_SESSION['user_name']) ?></p>
                </div>
                <div class="nav-actions">
                    <a href="index.php" class="btn btn-outline">View Site</a>
                </div>
            </header>

            <!-- Stats Grid -->
            <div class="stats-grid">
                <div class="stat-card glass">
                    <span class="stat-label">Total Listings</span>
                    <span class="stat-value"><?= $totalCars ?></span>
                </div>
                <div class="stat-card glass" style="border-left: 4px solid var(--warning);">
                    <span class="stat-label">Listing Requests</span>
                    <span class="stat-value"><?= $pendingCars ?></span>
                </div>
                <div class="stat-card glass">
                    <span class="stat-label">Total Users</span>
                    <span class="stat-value"><?= $totalUsers ?></span>
                </div>
                <div class="stat-card glass" style="border-left: 4px solid var(--success); cursor: pointer;" onclick="window.location.href='admin_purchases.php'">
                    <span class="stat-label">Pending Purchases</span>
                    <span class="stat-value"><?= $totalPurchases ?></span>
                </div>
            </div>

            <div class="grid grid-2">
                <!-- Recent Listings -->
                <div class="glass" style="padding: 2.5rem; grid-column: span 1;">
                    <div class="mb-2" style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 class="fw-bold">Recent Car Listings</h3>
                        <a href="admin_cars.php" class="text-gold text-sm fw-bold" style="text-decoration: none;">View All</a>
                    </div>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>Car</th>
                                    <th>Owner</th>
                                    <th>Price</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentCars as $car): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= htmlspecialchars($car['brand'] . ' ' . $car['model']) ?></div>
                                        <div class="text-sm"><?= $car['year'] ?></div>
                                    </td>
                                    <td><?= htmlspecialchars($car['owner_name']) ?></td>
                                    <td class="text-gold fw-bold">$<?= number_format($car['price']) ?></td>
                                    <td><a href="car_detail.php?id=<?= $car['id'] ?>" class="btn-auth text-sm" style="padding: 0.4rem 0.8rem;">View</a></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Recent Messages -->
                <div class="glass" style="padding: 2.5rem;">
                    <div class="mb-2" style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 class="fw-bold">Recent Messages</h3>
                        <a href="admin_messages.php" class="text-gold text-sm fw-bold" style="text-decoration: none;">All Messages</a>
                    </div>
                    <?php if (empty($recentMessages)): ?>
                        <p class="text-secondary text-sm">No new messages.</p>
                    <?php else: ?>
                        <div style="display: flex; flex-direction: column; gap: 1.5rem;">
                            <?php foreach ($recentMessages as $msg): ?>
                            <div style="border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 1rem;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.3rem;">
                                    <span class="fw-bold text-sm"><?= htmlspecialchars($msg['name']) ?></span>
                                    <span class="text-sm text-secondary"><?= date('M d', strtotime($msg['created_at'])) ?></span>
                                </div>
                                <p class="text-sm text-secondary" style="line-height: 1.4;">
                                    <?= htmlspecialchars(substr($msg['message'] ?? '', 0, 80)) ?>...
                                </p>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</body>
</html>