<?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: 900px;">
    <div class="box" style="padding: 4rem;">
        <h1 style="margin-bottom: 1rem; font-size: 2.5rem; font-weight: 900;">List Your Vehicle</h1>
        <p style="color: var(--text-secondary); margin-bottom: 3rem;">Provide details about your car and yourself. Our team will review and approve your listing.</p>
        
        <?php if ($success): ?>
            <div class="glass" style="padding: 2rem; border-color: var(--success); background: rgba(46, 213, 115, 0.05); color: var(--success); margin-bottom: 3rem; text-align: center; border-radius: 16px;">
                <h3 style="margin-bottom: 0.5rem;">🎉 Listing Submitted!</h3>
                <p>Your car and seller information have been sent for approval. You can track its status in your dashboard.</p>
                <div style="margin-top: 1.5rem;">
                    <a href="dashboard.php" class="btn btn-primary btn-sm">Go to Dashboard</a>
                </div>
            </div>
        <?php endif; ?>

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

        <form method="POST" enctype="multipart/form-data">
            <h3 style="margin-bottom: 1.5rem; color: var(--primary-color);">1. Vehicle Details</h3>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <div class="form-group">
                    <label>Brand</label>
                    <input type="text" name="brand" class="form-control" required placeholder="e.g. Toyota">
                </div>
                <div class="form-group">
                    <label>Model</label>
                    <input type="text" name="model" class="form-control" required placeholder="e.g. Land Cruiser">
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <div class="form-group">
                    <label>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>Price (USD)</label>
                    <input type="number" name="price" class="form-control" required placeholder="55000">
                </div>
            </div>

            <div class="form-group">
                <label>City</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 Photo</label>
                <div class="glass" style="padding: 2rem; text-align: center; border: 2px dashed var(--glass-border); border-radius: 12px;">
                    <input type="file" name="car_image" id="car_image" style="display: none;" accept="image/*">
                    <label for="car_image" style="cursor: pointer;">
                        <div style="font-size: 2.5rem; margin-bottom: 1rem;">📸</div>
                        <div style="font-weight: 700; color: var(--primary-color);">Click to upload photo</div>
                        <div style="font-size: 0.85rem; color: var(--text-secondary); margin-top: 0.5rem;">JPG, PNG or WEBP (Max 5MB)</div>
                    </label>
                    <div id="file-name" style="margin-top: 1rem; font-weight: 600; color: var(--success); display: none;"></div>
                </div>
                <div style="margin-top: 1rem;">
                    <label>Or Image URL</label>
                    <input type="url" name="image_url" class="form-control" placeholder="https://example.com/car.jpg">
                </div>
            </div>

            <div class="form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="4" required placeholder="Describe the condition, features..."></textarea>
            </div>

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

            <h3 style="margin-bottom: 1.5rem; color: var(--primary-color);">2. Seller Information</h3>
            <div class="form-group">
                <label>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>Location/Address</label>
                <textarea name="address" class="form-control" rows="2" required placeholder="Detailed address for vehicle inspection..."><?= htmlspecialchars($user_info['address'] ?? '') ?></textarea>
            </div>

            <div style="margin-top: 3rem; display: flex; gap: 1.5rem;">
                <button type="submit" class="btn btn-primary" style="flex: 2; padding: 1.2rem; font-size: 1.1rem; font-weight: 700;">Submit for Approval</button>
                <a href="dashboard.php" class="btn btn-outline" style="flex: 1; text-align: center; padding: 1.2rem;">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: ' + this.files[0].name;
        fileName.style.display = 'block';
    }
};
</script>

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