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

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

$error = '';
$success = false;
$pdo = db();

// Fetch current user details to pre-fill
$stmt = $pdo->prepare("SELECT phone, address FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user_info = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $brand = $_POST['brand'] ?? '';
    $model = $_POST['model'] ?? '';
    $year = $_POST['year'] ?? '';
    $price = $_POST['price'] ?? '';
    $city = $_POST['city'] ?? '';
    $description = $_POST['description'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $address = $_POST['address'] ?? '';
    
    // Update user info if provided
    if ($phone || $address) {
        $stmt = $pdo->prepare("UPDATE users SET phone = ?, address = ? WHERE id = ?");
        $stmt->execute([$phone, $address, $_SESSION['user_id']]);
    }

    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("INSERT INTO cars (user_id, brand, model, year, price, city, description, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')");
        $stmt->execute([$_SESSION['user_id'], $brand, $model, $year, $price, $city, $description]);
        $carId = $pdo->lastInsertId();
        
        // Handle Image Upload
        if (isset($_FILES['car_image']) && $_FILES['car_image']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['car_image']['tmp_name'];
            $fileName = $_FILES['car_image']['name'];
            $fileSize = $_FILES['car_image']['size'];
            $fileType = $_FILES['car_image']['type'];
            $fileNameCmps = explode(".", $fileName);
            $fileExtension = strtolower(end($fileNameCmps));
            
            $allowedfileExtensions = array('jpg', 'gif', 'png', 'jpeg', 'webp');
            if (in_array($fileExtension, $allowedfileExtensions)) {
                $uploadFileDir = './assets/images/uploads/';
                $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
                $dest_path = $uploadFileDir . $newFileName;
                
                if(move_uploaded_file($fileTmpPath, $dest_path)) {
                    $imagePath = 'assets/images/uploads/' . $newFileName;
                    $stmt = $pdo->prepare("INSERT INTO car_images (car_id, image_path, is_main) VALUES (?, ?, 1)");
                    $stmt->execute([$carId, $imagePath]);
                } else {
                    throw new Exception("There was an error moving the uploaded file.");
                }
            } else {
                throw new Exception("Upload failed. Allowed file types: " . implode(',', $allowedfileExtensions));
            }
        } else if (!empty($_POST['image_url'])) {
            $stmt = $pdo->prepare("INSERT INTO car_images (car_id, image_path, is_main) VALUES (?, ?, 1)");
            $stmt->execute([$carId, $_POST['image_url']]);
        }
        
        $pdo->commit();
        $success = true;
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Failed to list car: " . $e->getMessage();
    }
}

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

<div class="container" style="max-width: 1000px; padding: 4rem 0;">
    <div class="box" style="padding: 4.5rem;">
        <h1 class="fw-black mb-1" style="font-size: 3rem; color: #fff;">List Your Vehicle</h1>
        <p class="text-secondary mb-3" style="font-size: 1.15rem; font-weight: 500;">Provide all details about your car and yourself. Our team will review and approve your listing shortly.</p>
        
        <?php if ($success): ?>
            <div class="glass text-center" style="padding: 3rem; border-color: var(--success); background: rgba(46, 213, 115, 0.05); color: var(--success); margin-bottom: 4rem; border-radius: 24px;">
                <h3 class="fw-black mb-1" style="font-size: 2rem;">🎉 Listing Successfully Submitted!</h3>
                <p class="text-secondary mb-2" style="font-size: 1.1rem; font-weight: 700;">Your vehicle and seller documentation are now under review. Check your dashboard for status updates.</p>
                <div class="mt-2">
                    <a href="dashboard.php" class="btn btn-primary btn-lg">Return to My Dashboard</a>
                </div>
            </div>
        <?php endif; ?>

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

        <form method="POST" enctype="multipart/form-data">
            <h3 class="fw-black text-gold mb-2" style="font-size: 1.3rem; text-transform: uppercase; letter-spacing: 1px;">1. Vehicle Details</h3>
            <div class="grid grid-2 mb-2">
                <div class="form-group">
                    <label>Vehicle Brand</label>
                    <input type="text" name="brand" class="form-control" required placeholder="e.g. Toyota">
                </div>
                <div class="form-group">
                    <label>Vehicle Model</label>
                    <input type="text" name="model" class="form-control" required placeholder="e.g. Land Cruiser">
                </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" required placeholder="2024" min="1990" max="<?= date('Y') + 1 ?>">
                </div>
                <div class="form-group">
                    <label>Asking Price (USD)</label>
                    <input type="number" name="price" class="form-control" required placeholder="55000">
                </div>
            </div>

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

            <div class="form-group">
                <label>Vehicle Photography</label>
                <div class="glass text-center" style="padding: 3rem; border: 3px dashed var(--glass-border); border-radius: 20px; background: rgba(0,0,0,0.1);">
                    <input type="file" name="car_image" id="car_image" style="display: none;" accept="image/*">
                    <label for="car_image" style="cursor: pointer; display: block;">
                        <div style="font-size: 3.5rem; margin-bottom: 1.5rem; filter: drop-shadow(0 5px 15px rgba(0,0,0,0.3));">📸</div>
                        <div class="fw-black text-gold" style="font-size: 1.2rem; text-transform: uppercase; letter-spacing: 1px;">Click to Choose Image</div>
                        <div class="text-secondary text-sm mt-1 fw-bold">Professional quality JPG, PNG or WEBP recommended (Max 5MB)</div>
                    </label>
                    <div id="file-name" class="mt-2 fw-black" style="color: var(--success); font-size: 1rem; display: none;"></div>
                </div>
                <div class="mt-2">
                    <label>Or Provide External Image URL</label>
                    <input type="url" name="image_url" class="form-control" placeholder="https://example.com/premium-car-image.jpg">
                </div>
            </div>

            <div class="form-group">
                <label>Vehicle Description & Special Features</label>
                <textarea name="description" class="form-control" rows="5" required placeholder="Enter all details about current condition, special features, and maintenance history..."></textarea>
            </div>

            <hr style="margin: 4rem 0; border: 0; border-top: 1px solid var(--glass-border);">

            <h3 class="fw-black text-gold mb-2" style="font-size: 1.3rem; text-transform: uppercase; letter-spacing: 1px;">2. Verified Seller Documentation</h3>
            <div class="form-group">
                <label>Verified Phone Number</label>
                <input type="text" name="phone" class="form-control" required placeholder="+93 7xx xxx xxx" value="<?= htmlspecialchars($user_info['phone'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Detailed Residential Address / Location</label>
                <textarea name="address" class="form-control" rows="2" required placeholder="Enter your full residential address for identity verification and inspection arrangements..."><?= htmlspecialchars($user_info['address'] ?? '') ?></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;">SUBMIT VEHICLE FOR APPROVAL</button>
                <a href="dashboard.php" class="btn btn-outline btn-lg" style="flex: 1; font-weight: 700;">CANCEL</a>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('car_image').onchange = function() {
    if (this.files && this.files[0]) {
        const fileName = document.getElementById('file-name');
        fileName.textContent = '✅ Selected File: ' + this.files[0].name;
        fileName.style.display = 'block';
    }
};
</script>

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