<?php
require_once __DIR__ . '/includes/header.php';

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

$pdo = db();
$id = $_GET['id'] ?? 0;
$userId = $_SESSION['user_id'];

// Check ownership or admin role
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
if ($isAdmin) {
    $stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ? AND deleted_at IS NULL");
    $stmt->execute([$id]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ? AND user_id = ? AND deleted_at IS NULL");
    $stmt->execute([$id, $userId]);
}
$car = $stmt->fetch();

if (!$car) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $brand = $_POST['brand'] ?? '';
    $model = $_POST['model'] ?? '';
    $year = $_POST['year'] ?? '';
    $price = $_POST['price'] ?? '';
    $city = $_POST['city'] ?? '';
    $description = $_POST['description'] ?? '';
    
    try {
        $stmt = $pdo->prepare("UPDATE cars SET brand = ?, model = ?, year = ?, price = ?, city = ?, description = ?, status = 'pending' WHERE id = ?");
        $stmt->execute([$brand, $model, $year, $price, $city, $description, $id]);
        $success = true;
        // Refresh car data
        $car['brand'] = $brand;
        $car['model'] = $model;
        $car['year'] = $year;
        $car['price'] = $price;
        $car['city'] = $city;
        $car['description'] = $description;
    } catch (Exception $e) {
        $error = "Update failed: " . $e->getMessage();
    }
}

$cities = ['Kabul', 'Herat', 'Mazar-i-Sharif', 'Kandahar', 'Jalalabad', 'Kunduz', 'Ghazni', 'Balkh'];
?>

<div class="container" style="max-width: 900px; padding: 4rem 0;">
    <div class="box" style="padding: 4.5rem;">
        <h1 class="fw-black mb-1" style="font-size: 3rem; color: #fff;">Edit Vehicle Listing</h1>
        <p class="text-secondary mb-3" style="font-size: 1.15rem; font-weight: 500;">Update your vehicle specifications. Note: making changes will reset the approval status to 'pending'.</p>
        
        <?php if ($success): ?>
            <div class="glass text-center mb-4" style="padding: 3rem; border-color: var(--success); background: rgba(46, 213, 115, 0.05); color: var(--success); border-radius: 24px;">
                <h3 class="fw-black mb-1" style="font-size: 2rem;">✨ Vehicle Updated Successfully!</h3>
                <p class="text-secondary mb-2" style="font-size: 1.1rem; font-weight: 700;">Your changes have been saved and the listing is awaiting re-approval by our administrators.</p>
                <div class="mt-2">
                    <a href="<?= $isAdmin ? 'admin_cars.php' : 'dashboard.php' ?>" class="btn btn-primary btn-lg">Back to Management Console</a>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-error mb-2"><?= $error ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="grid grid-2 mb-2">
                <div class="form-group">
                    <label>Vehicle Brand</label>
                    <input type="text" name="brand" class="form-control" value="<?= htmlspecialchars($car['brand']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Vehicle Model</label>
                    <input type="text" name="model" class="form-control" value="<?= htmlspecialchars($car['model']) ?>" required>
                </div>
            </div>
            
            <div class="grid grid-2 mb-2">
                <div class="form-group">
                    <label>Manufacturing Year</label>
                    <input type="number" name="year" class="form-control" value="<?= htmlspecialchars($car['year']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Asking Price (USD)</label>
                    <input type="number" name="price" class="form-control" value="<?= htmlspecialchars($car['price']) ?>" required>
                </div>
            </div>

            <div class="form-group">
                <label>Current Location (City)</label>
                <select name="city" class="form-control" required>
                    <?php foreach ($cities as $c): ?>
                        <option value="<?= $c ?>" <?= $car['city'] === $c ? 'selected' : '' ?>><?= $c ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Vehicle Description & Details</label>
                <textarea name="description" class="form-control" rows="6" required placeholder="Describe the current condition, maintenance history, and features..."><?= htmlspecialchars($car['description']) ?></textarea>
            </div>

            <div class="mt-3 flex gap-1 align-center">
                <button type="submit" class="btn btn-primary btn-lg" style="flex: 2; font-weight: 900; letter-spacing: 1px;">SAVE DOCUMENTED CHANGES</button>
                <a href="<?= $isAdmin ? 'admin_cars.php' : 'dashboard.php' ?>" class="btn btn-outline btn-lg" style="flex: 1; font-weight: 700;">DISCARD & EXIT</a>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>