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

function ensure_db_setup() {
    $flagFile = __DIR__ . '/../db/setup_done.flag';
    if (file_exists($flagFile)) {
        return;
    }

    try {
        $db = db();
        
        // Schema Creation (IF NOT EXISTS to be safe)
        $db->exec("SET FOREIGN_KEY_CHECKS = 0");
        
        // Branches
        $db->exec("CREATE TABLE IF NOT EXISTS 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)
        )");

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

        // Cars
        $db->exec("CREATE TABLE IF NOT EXISTS 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,
            dealer_id INT DEFAULT NULL,
            installment_available BOOLEAN DEFAULT 0,
            is_featured BOOLEAN DEFAULT 0,
            image_url VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (branch_id) REFERENCES branches(id),
            FOREIGN KEY (dealer_id) REFERENCES users(id)
        )");

        // Car Images
        $db->exec("CREATE TABLE IF NOT EXISTS car_images (
            id INT AUTO_INCREMENT PRIMARY KEY,
            car_id INT NOT NULL,
            image_path VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (car_id) REFERENCES cars(id) ON DELETE CASCADE
        )");

        // Reviews
        $db->exec("CREATE TABLE IF NOT EXISTS reviews (
            id INT AUTO_INCREMENT PRIMARY KEY,
            car_id INT NOT NULL,
            user_id INT NOT NULL,
            rating INT NOT NULL CHECK (rating >= 1 AND rating <= 5),
            comment TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (car_id) REFERENCES cars(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");

        // Sales
        $db->exec("CREATE TABLE IF NOT EXISTS sales (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            car_id INT NOT NULL,
            amount DECIMAL(15, 2) NOT NULL,
            sale_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            status ENUM('Pending', 'Completed', 'Cancelled') DEFAULT 'Pending',
            FOREIGN KEY (user_id) REFERENCES users(id),
            FOREIGN KEY (car_id) REFERENCES cars(id)
        )");

        // Installments
        $db->exec("CREATE TABLE IF NOT EXISTS installments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            sale_id INT NOT NULL,
            total_amount DECIMAL(15, 2) NOT NULL,
            paid_amount DECIMAL(15, 2) DEFAULT 0,
            monthly_payment DECIMAL(15, 2) NOT NULL,
            status ENUM('Active', 'Completed', 'Overdue') DEFAULT 'Active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (sale_id) REFERENCES sales(id) ON DELETE CASCADE
        )");

        // Activity Logs
        $db->exec("CREATE TABLE IF NOT EXISTS activity_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT,
            action VARCHAR(255) NOT NULL,
            ip_address VARCHAR(50),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
        )");

        // Notifications
        $db->exec("CREATE TABLE IF NOT EXISTS notifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            message TEXT NOT NULL,
            is_read BOOLEAN DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");

        $db->exec("SET FOREIGN_KEY_CHECKS = 1");

        // Seeding (Only if empty)
        $stmt = $db->query("SELECT COUNT(*) FROM branches");
        if ($stmt->fetchColumn() == 0) {
            $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);
            }
        }

        $stmt = $db->query("SELECT COUNT(*) FROM cars");
        if ($stmt->fetchColumn() == 0) {
            $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, installment_available) 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; 
                $installment_available = rand(0, 1);
                $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, $installment_available
                ]);
            }
        }

        $stmt = $db->query("SELECT COUNT(*) FROM users");
        if ($stmt->fetchColumn() == 0) {
            $stmt = $db->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
            $stmt->execute(['admin', password_hash('admin123', PASSWORD_DEFAULT), 'Super Admin']);
        }

        // Create flag file to prevent re-running on every request
        file_put_contents($flagFile, date('Y-m-d H:i:s'));

    } catch (Exception $e) {
        error_log("DB Setup Failed: " . $e->getMessage());
    }
}
?>