<?php
require_once __DIR__ . '/db/config.php';

try {
    $db = db();

    // Drop tables if they exist for a clean re-seed
    $db->exec("SET FOREIGN_KEY_CHECKS = 0");
    $db->exec("DROP TABLE IF EXISTS cars");
    $db->exec("DROP TABLE IF EXISTS branches");
    $db->exec("DROP TABLE IF EXISTS users");
    $db->exec("SET FOREIGN_KEY_CHECKS = 1");

    // Create Branches table
    $db->exec("CREATE TABLE branches (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        city VARCHAR(100) NOT NULL,
        address VARCHAR(255),
        phone VARCHAR(50),
        hours VARCHAR(100)
    )");

    // Create Cars table
    $db->exec("CREATE TABLE cars (
        id INT AUTO_INCREMENT PRIMARY KEY,
        vin VARCHAR(50) UNIQUE NOT NULL,
        brand VARCHAR(100) NOT NULL,
        model VARCHAR(100) NOT NULL,
        year INT NOT NULL,
        price DECIMAL(15, 2) NOT NULL,
        mileage INT NOT NULL,
        transmission VARCHAR(50),
        fuel_type VARCHAR(50),
        status ENUM('Available', 'Reserved', 'Sold') DEFAULT 'Available',
        branch_id INT,
        is_featured BOOLEAN DEFAULT 0,
        image_url VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (branch_id) REFERENCES branches(id)
    )");

    // Create Users table
    $db->exec("CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(100) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        role ENUM('Guest', 'Customer', 'Dealer', 'Employee', 'Manager', 'Admin', 'Super Admin') DEFAULT 'Customer',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    // Seed Branches
    $branches = [
        ['Kabul Main', 'Kabul', 'Shar-e-Naw, Kabul', '+93 700 111 222', '08:00 AM - 06:00 PM'],
        ['Herat Branch', 'Herat', 'Main Road, Herat', '+93 700 333 444', '08:30 AM - 05:30 PM'],
        ['Mazar Center', 'Mazar-i-Sharif', 'Balkh Street, Mazar', '+93 700 555 666', '08:00 AM - 05:00 PM'],
        ['Kandahar Hub', 'Kandahar', 'Airport Road, Kandahar', '+93 700 777 888', '09:00 AM - 04:00 PM']
    ];
    $stmt = $db->prepare("INSERT INTO branches (name, city, address, phone, hours) VALUES (?, ?, ?, ?, ?)");
    foreach ($branches as $branch) {
        $stmt->execute($branch);
    }

    // Seed Cars (Exactly 20 Cars)
    $brands = ['Toyota', 'Lexus', 'Mercedes-Benz', 'BMW', 'Audi', 'Land Rover', 'Porsche', 'Tesla'];
    $models = [
        'Toyota' => ['Camry', 'Land Cruiser', 'Corolla', 'RAV4'],
        'Lexus' => ['LX 600', 'RX 350', 'ES 350'],
        'Mercedes-Benz' => ['S-Class', 'G-Wagon', 'E-Class'],
        'BMW' => ['X7', 'X5', '7 Series'],
        'Audi' => ['Q8', 'A8', 'RS7'],
        'Land Rover' => ['Defender', 'Range Rover'],
        'Porsche' => ['911 Carrera', 'Cayenne'],
        'Tesla' => ['Model S', 'Model X']
    ];
    
    $stmt = $db->prepare("INSERT INTO cars (vin, brand, model, year, price, mileage, transmission, fuel_type, branch_id, is_featured, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    for ($i = 1; $i <= 20; $i++) {
        $brand = $brands[array_rand($brands)];
        $model = $models[$brand][array_rand($models[$brand])];
        $year = rand(2020, 2024);
        $price = rand(45000, 180000);
        $mileage = rand(0, 15000);
        $branch_id = rand(1, 4);
        $is_featured = ($i <= 8) ? 1 : 0; // 8 featured cars
        $image_url = "assets/images/cars/car{$i}.jpg";
        $vin = "VIN" . str_pad((string)$i, 10, "0", STR_PAD_LEFT);
        
        $stmt->execute([
            $vin, $brand, $model, $year, $price, $mileage, 
            'Automatic', rand(0,1) ? 'Gasoline' : 'Hybrid', 
            $branch_id, $is_featured, $image_url
        ]);
    }

    // Seed Admin
    $stmt = $db->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
    $stmt->execute(['admin', password_hash('admin123', PASSWORD_DEFAULT), 'Super Admin']);

    echo "<h1>Setup Successful!</h1>";
    echo "<p>Database recreated and exactly 20 premium cars seeded.</p>";
    echo "<p><strong>Admin Credentials:</strong> admin / admin123</p>";
    echo "<a href='index.php'>Go to Home Page</a>";

} catch (Exception $e) {
    echo "<h1>Setup Failed</h1>";
    echo "<p>" . $e->getMessage() . "</p>";
}
