-- Database Schema for AFG_CARS Enterprise System
SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `installments`;
DROP TABLE IF EXISTS `sales`;
DROP TABLE IF EXISTS `inquiries`;
DROP TABLE IF EXISTS `cars`;
DROP TABLE IF EXISTS `branches`;
DROP TABLE IF EXISTS `users`;

-- Users Table
CREATE TABLE `users` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL,
    `email` VARCHAR(100) NOT NULL UNIQUE,
    `password` VARCHAR(255) NOT NULL,
    `role` ENUM('admin', 'user') DEFAULT 'user',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Branches Table
CREATE TABLE `branches` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL,
    `city` VARCHAR(50) NOT NULL,
    `address` TEXT,
    `phone` VARCHAR(20)
);

-- Cars Table
CREATE TABLE `cars` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `branch_id` INT,
    `brand` VARCHAR(50) NOT NULL,
    `model` VARCHAR(50) NOT NULL,
    `year` INT NOT NULL,
    `price` DECIMAL(10, 2) NOT NULL,
    `mileage` INT DEFAULT 0,
    `fuel_type` VARCHAR(20) DEFAULT 'Petrol',
    `transmission` VARCHAR(20) DEFAULT 'Automatic',
    `description` TEXT,
    `image_path` VARCHAR(255),
    `status` ENUM('available', 'sold') DEFAULT 'available',
    `is_featured` BOOLEAN DEFAULT 0,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (`branch_id`) REFERENCES `branches`(`id`) ON DELETE SET NULL
);

-- Sales Table
CREATE TABLE `sales` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `car_id` INT NOT NULL,
    `user_id` INT NOT NULL,
    `sale_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `sale_price` DECIMAL(10, 2) NOT NULL,
    FOREIGN KEY (`car_id`) REFERENCES `cars`(`id`),
    FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
);

-- Installments Table
CREATE TABLE `installments` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `car_id` INT NOT NULL,
    `user_id` INT NOT NULL,
    `total_amount` DECIMAL(10, 2) NOT NULL,
    `monthly_payment` DECIMAL(10, 2) NOT NULL,
    `months` INT NOT NULL,
    `status` ENUM('pending', 'approved', 'rejected', 'completed') DEFAULT 'pending',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (`car_id`) REFERENCES `cars`(`id`),
    FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
);

-- Inquiries/Contact Table
CREATE TABLE `inquiries` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `car_id` INT DEFAULT NULL,
    `user_id` INT DEFAULT NULL,
    `name` VARCHAR(100),
    `email` VARCHAR(100),
    `message` TEXT,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (`car_id`) REFERENCES `cars`(`id`) ON DELETE SET NULL
);

SET FOREIGN_KEY_CHECKS=1;
