<?php
session_start();

// Настройки базы данных
$host = 'localhost';
$db   = 'fuel_management';
$user = 'root';
$pass = '4321';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    die("Ошибка подключения: " . $e->getMessage());
}

// Функции безопасности
function checkAuth() {
    if (!isset($_SESSION['user_id']) && !isset($_COOKIE['remember_token'])) {
        header('Location: index.php');
        exit();
    }
}

function hasPermission($requiredRole) {
    $userRole = $_SESSION['role'] ?? '';
    $rolesHierarchy = ['admin' => 3, 'engineer' => 2, 'refueler' => 1];
    
    return ($rolesHierarchy[$userRole] ?? 0) >= ($rolesHierarchy[$requiredRole] ?? 0);
}

function sanitizeInput($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

// Создание таблиц если их нет
function createTables($pdo) {
    $queries = [
        "CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) UNIQUE NOT NULL,
            password VARCHAR(255) NOT NULL,
            role ENUM('admin', 'engineer', 'refueler') NOT NULL,
            full_name VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )",
        
        "CREATE TABLE IF NOT EXISTS vehicle_categories (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            description TEXT,
            icon VARCHAR(50) DEFAULT '🚜',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )",
        
        "CREATE TABLE IF NOT EXISTS vehicles (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            model VARCHAR(100),
            year YEAR,
            license_plate VARCHAR(20),
            type VARCHAR(50),
            category_id INT,
            description TEXT,
            image VARCHAR(255),
            tank_capacity DECIMAL(10,2) NOT NULL,
            fuel_type ENUM('diesel', 'petrol', 'gas', 'electric') DEFAULT 'diesel',
            status ENUM('active', 'maintenance', 'inactive', 'repair') DEFAULT 'active',
            mileage DECIMAL(10,2) DEFAULT 0,
            created_by INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_name (name),
            INDEX idx_status (status),
            INDEX idx_category (category_id),
            FOREIGN KEY (category_id) REFERENCES vehicle_categories(id) ON DELETE SET NULL,
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
        )",
        
        "CREATE TABLE IF NOT EXISTS fuel_tanks (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            location VARCHAR(255),
            capacity DECIMAL(10,2) NOT NULL,
            current_level DECIMAL(10,2) DEFAULT 0,
            fuel_type ENUM('diesel', 'petrol', 'gas', 'electric') DEFAULT 'diesel',
            min_level DECIMAL(10,2) DEFAULT 0,
            status ENUM('active', 'maintenance', 'empty') DEFAULT 'active',
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )",
        
        "CREATE TABLE IF NOT EXISTS fuel_receipts (
            id INT AUTO_INCREMENT PRIMARY KEY,
            tank_id INT NOT NULL,
            receipt_date DATETIME NOT NULL,
            fuel_type ENUM('diesel', 'petrol', 'gas', 'electric') DEFAULT 'diesel',
            fuel_amount DECIMAL(10,2) NOT NULL,
            supplier VARCHAR(255) NOT NULL,
            driver_name VARCHAR(100),
            vehicle_number VARCHAR(20),
            document_number VARCHAR(100),
            quality_check BOOLEAN DEFAULT FALSE,
            notes TEXT,
            received_by INT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_receipt_date (receipt_date),
            INDEX idx_supplier (supplier),
            FOREIGN KEY (tank_id) REFERENCES fuel_tanks(id) ON DELETE CASCADE,
            FOREIGN KEY (received_by) REFERENCES users(id) ON DELETE CASCADE
        )",
        
        "CREATE TABLE IF NOT EXISTS refuels (
            id INT AUTO_INCREMENT PRIMARY KEY,
            vehicle_id INT NOT NULL,
            tank_id INT NOT NULL,
            user_id INT NOT NULL,
            fuel_amount DECIMAL(10,2) NOT NULL,
            fuel_type ENUM('diesel', 'petrol', 'gas', 'electric') DEFAULT 'diesel',
            refuel_date DATETIME NOT NULL,
            odometer_reading DECIMAL(10,2),
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_vehicle_id (vehicle_id),
            INDEX idx_user_id (user_id),
            INDEX idx_refuel_date (refuel_date),
            FOREIGN KEY (vehicle_id) REFERENCES vehicles(id) ON DELETE CASCADE,
            FOREIGN KEY (tank_id) REFERENCES fuel_tanks(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )",
        
        "CREATE TABLE IF NOT EXISTS fuel_reports (
            id INT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL,
            report_type ENUM('monthly', 'vehicle', 'custom', 'yearly', 'weekly', 'receipt') NOT NULL,
            period_start DATE NOT NULL,
            period_end DATE NOT NULL,
            report_data JSON,
            total_fuel DECIMAL(12,2),
            vehicle_count INT,
            refuel_count INT,
            generated_by INT NOT NULL,
            is_archived BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_report_type (report_type),
            INDEX idx_period (period_start, period_end),
            INDEX idx_generated_by (generated_by),
            FOREIGN KEY (generated_by) REFERENCES users(id) ON DELETE CASCADE
        )"
    ];

    foreach ($queries as $query) {
        try {
            $pdo->exec($query);
        } catch (PDOException $e) {
            // Пропускаем ошибки если таблицы уже существуют
        }
    }

    // Создание администратора по умолчанию
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE role = 'admin'");
    $stmt->execute();
    if ($stmt->fetchColumn() == 0) {
        $hashedPassword = password_hash('admin123', PASSWORD_DEFAULT);
        $pdo->prepare("INSERT INTO users (username, password, role, full_name) VALUES (?, ?, ?, ?)")
            ->execute(['admin', $hashedPassword, 'admin', 'Администратор']);
    }
    
    // Создание резервуаров по умолчанию
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM fuel_tanks");
    $stmt->execute();
    if ($stmt->fetchColumn() == 0) {
        $defaultTanks = [
            ['Основной дизельный резервуар', 'Территория предприятия', 20000, 15000, 'diesel'],
            ['Резервный дизельный резервуар', 'Территория предприятия', 10000, 5000, 'diesel'],
            ['Бензиновый резервуар', 'Территория предприятия', 5000, 3000, 'petrol']
        ];
        
        foreach ($defaultTanks as $tank) {
            $pdo->prepare("INSERT INTO fuel_tanks (name, location, capacity, current_level, fuel_type) VALUES (?, ?, ?, ?, ?)")
                ->execute($tank);
        }
    }
}

createTables($pdo);
?>