<?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 href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css?v=<?= time() ?>">
</head>
<body style="background: #050505;">
    <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" style="color: var(--danger); font-size: 0.9rem; text-decoration: none; font-weight: 600;">Logout</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <header style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 3rem;">
                <div>
                    <h1 style="font-size: 2rem; font-weight: 900;">Dashboard Overview</h1>
                    <p style="color: var(--text-secondary);">Welcome back, <?= htmlspecialchars($_SESSION['user_name']) ?></p>
                </div>
                <div style="display: flex; gap: 1rem;">
                    <a href="index.php" class="btn-auth">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 style="display: grid; grid-template-columns: 2fr 1fr; gap: 2rem;">
                <!-- Recent Listings -->
                <div class="glass" style="padding: 2rem;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                        <h3 style="font-weight: 800;">Recent Car Listings</h3>
                        <a href="admin_cars.php" style="color: var(--primary-color); text-decoration: none; font-size: 0.85rem; font-weight: 600;">View All</a>
                    </div>
                    <div class="table-container" style="overflow-x: auto;">
                        <table style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>Car</th>
                                    <th>Owner</th>
                                    <th>Price</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentCars as $car): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 600;"><?= htmlspecialchars($car['brand'] . ' ' . $car['model']) ?></div>
                                        <div style="font-size: 0.8rem; color: var(--text-secondary);"><?= $car['year'] ?></div>
                                    </td>
                                    <td><?= htmlspecialchars($car['owner_name']) ?></td>
                                    <td style="color: var(--primary-color); font-weight: 700;">$<?= number_format($car['price']) ?></td>
                                    <td>
                                        <span class="badge badge-<?= $car['status'] === 'approved' ? 'success' : ($car['status'] === 'pending' ? 'warning' : 'danger') ?>">
                                            <?= ucfirst($car['status']) ?>
                                        </span>
                                    </td>
                                    <td><a href="car_detail.php?id=<?= $car['id'] ?>" style="color: var(--info); text-decoration: none; font-weight: 600; font-size: 0.85rem;">View</a></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Recent Messages -->
                <div class="glass" style="padding: 2rem;">
                    <h3 style="font-weight: 800; margin-bottom: 1.5rem;">Recent Messages</h3>
                    <?php if (empty($recentMessages)): ?>
                        <p style="color: var(--text-secondary); font-size: 0.9rem;">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 style="font-weight: 700; font-size: 0.9rem;"><?= htmlspecialchars($msg['name']) ?></span>
                                    <span style="font-size: 0.7rem; color: var(--text-secondary);"><?= date('M d', strtotime($msg['created_at'])) ?></span>
                                </div>
                                <p style="font-size: 0.85rem; color: var(--text-secondary); line-height: 1.4;">
                                    <?= htmlspecialchars(substr($msg['message'] ?? '', 0, 80)) ?>...
                                </p>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</body>
</html>