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

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

$pdo = db();
$message = '';

if (isset($_POST['action']) && isset($_POST['car_id'])) {
    $car_id = $_POST['car_id'];
    $action = $_POST['action'];
    $status = ($action === 'approve') ? 'approved' : 'rejected';
    
    $stmt = $pdo->prepare("UPDATE cars SET status = ? WHERE id = ?");
    if ($stmt->execute([$status, $car_id])) {
        $message = "Car listing " . ($status === 'approved' ? 'approved' : 'rejected') . " successfully.";
    }
}

if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("UPDATE cars SET deleted_at = NOW() WHERE id = ?");
    if ($stmt->execute([$id])) {
        $message = "Car deleted successfully.";
    }
}

// Fetch all cars with user and image info
$stmt = $pdo->query("
    SELECT c.*, u.name as seller_name, u.phone as seller_phone, ci.image_path
    FROM cars c
    JOIN users u ON c.user_id = u.id
    LEFT JOIN car_images ci ON c.id = ci.car_id AND ci.is_main = 1
    WHERE c.deleted_at IS NULL
    ORDER BY c.created_at DESC
");
$cars = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Inventory | Admin</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"><span>Dashboard</span></a></li>
                <li><a href="admin_cars.php" class="active"><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;">Inventory Management</h1>
                    <p class="text-secondary">Review, approve, and manage all vehicle listings across the platform.</p>
                </div>
                <div class="nav-actions">
                    <a href="admin_purchases.php" class="btn btn-primary">Purchase Requests</a>
                </div>
            </header>

            <?php if ($message): ?>
                <div class="alert alert-success">
                    <span class="text-gold">✓</span> <?= $message ?>
                </div>
            <?php endif; ?>

            <div class="glass" style="padding: 2.5rem;">
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Vehicle Details</th>
                                <th>Seller Info</th>
                                <th>Price & City</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cars as $car): ?>
                            <tr>
                                <td>
                                    <div style="display: flex; align-items: center; gap: 1.2rem;">
                                        <img src="<?= htmlspecialchars($car['image_path'] ?: 'assets/images/placeholder-car.jpg') ?>" style="width: 110px; height: 70px; object-fit: cover; border-radius: 12px; border: 1px solid var(--glass-border);">
                                        <div>
                                            <div class="fw-bold"><?= htmlspecialchars($car['brand'] . ' ' . $car['model']) ?></div>
                                            <div class="text-sm text-secondary"><?= $car['year'] ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="fw-bold text-sm"><?= htmlspecialchars($car['seller_name']) ?></div>
                                    <div class="text-sm text-secondary"><?= htmlspecialchars($car['seller_phone']) ?></div>
                                </td>
                                <td>
                                    <div class="text-gold fw-bold">$<?= number_format($car['price']) ?></div>
                                    <div class="text-sm text-secondary"><?= htmlspecialchars($car['city']) ?></div>
                                </td>
                                <td>
                                    <span class="badge badge-<?= $car['status'] === 'approved' ? 'success' : ($car['status'] === 'sold' ? 'info' : ($car['status'] === 'rejected' ? 'danger' : 'warning')) ?>">
                                        <?= ucfirst($car['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 1rem; align-items: center;">
                                        <?php if ($car['status'] === 'pending'): ?>
                                            <form method="POST" style="display: inline;">
                                                <input type="hidden" name="car_id" value="<?= $car['id'] ?>">
                                                <button type="submit" name="action" value="approve" class="text-gold text-sm fw-bold btn-sm" style="background: none; border: none; cursor: pointer; padding: 0;">Approve</button>
                                            </form>
                                            <form method="POST" style="display: inline;">
                                                <input type="hidden" name="car_id" value="<?= $car['id'] ?>">
                                                <button type="submit" name="action" value="reject" class="text-sm fw-bold btn-sm" style="background: none; border: none; cursor: pointer; padding: 0; color: var(--danger);">Reject</button>
                                            </form>
                                        <?php endif; ?>
                                        <a href="edit_car.php?id=<?= $car['id'] ?>" class="text-sm fw-bold text-secondary" style="text-decoration: none;">Edit</a>
                                        <a href="?delete=<?= $car['id'] ?>" class="text-sm fw-bold" style="color: var(--danger); text-decoration: none;" onclick="return confirm('Delete this vehicle?')">Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>
</body>
</html>