<?php
include 'config.php';
checkAuth();

if (!hasPermission('engineer')) {
    header('Location: vehicles.php');
    exit();
}

$editMode = false;
$vehicleData = [];
$message = '';

if (isset($_GET['edit'])) {
    $editMode = true;
    $stmt = $pdo->prepare("SELECT * FROM vehicles WHERE id = ?");
    $stmt->execute([intval($_GET['edit'])]);
    $vehicleData = $stmt->fetch();
    
    if (!$vehicleData) {
        header('Location: vehicles.php');
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitizeInput($_POST['name']);
    $type = sanitizeInput($_POST['type']);
    $description = sanitizeInput($_POST['description']);
    $tank_capacity = floatval($_POST['tank_capacity']);
    $fuel_type = $_POST['fuel_type'];
    $status = $_POST['status'];
    $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
    $license_plate = sanitizeInput($_POST['license_plate'] ?? '');
    
    // Обработка загрузки изображения
    $image = $vehicleData['image'] ?? '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileExtension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $fileName = uniqid() . '.' . $fileExtension;
        $uploadFile = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
            $image = $fileName;
        }
    }
    
    if ($editMode) {
        $stmt = $pdo->prepare("UPDATE vehicles SET name = ?, type = ?, description = ?, tank_capacity = ?, fuel_type = ?, status = ?, image = ?, category_id = ?, license_plate = ? WHERE id = ?");
        $stmt->execute([$name, $type, $description, $tank_capacity, $fuel_type, $status, $image, $category_id, $license_plate, $vehicleData['id']]);
        $message = "✅ Техника успешно обновлена!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO vehicles (name, type, description, tank_capacity, fuel_type, status, image, category_id, license_plate, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $type, $description, $tank_capacity, $fuel_type, $status, $image, $category_id, $license_plate, $_SESSION['user_id']]);
        $message = "✅ Техника успешно добавлена!";
    }
    
    $vehicleData = $_POST;
    $vehicleData['image'] = $image;
}

// Получаем категории техники
$categories = $pdo->query("SELECT * FROM vehicle_categories ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $editMode ? '✏️ Редактирование' : '➕ Добавление'; ?> техники - Агротопливо</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <h1><?php echo $editMode ? '✏️ Редактирование техники' : '➕ Добавление техники'; ?></h1>
                <a href="vehicles.php" class="btn btn-secondary">← Назад к списку</a>
            </header>
            
            <?php if($message): ?>
                <div class="alert success"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data" class="form">
                        <div class="form-row">
                            <div class="form-group">
                                <label>🏷️ Название техники *</label>
                                <input type="text" name="name" value="<?php echo $vehicleData['name'] ?? ''; ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label>🔧 Тип техники</label>
                                <input type="text" name="type" value="<?php echo $vehicleData['type'] ?? ''; ?>" placeholder="Например: Трактор, Комбайн">
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label>🚗 Гос номер</label>
                                <input type="text" name="license_plate" value="<?php echo $vehicleData['license_plate'] ?? ''; ?>" placeholder="Например: А123БВ77">
                            </div>
                            
                            <div class="form-group">
                                <label>📊 Категория</label>
                                <select name="category_id">
                                    <option value="">Выберите категорию</option>
                                    <?php foreach($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>" <?php echo ($vehicleData['category_id'] ?? '') == $category['id'] ? 'selected' : ''; ?>>
                                            <?php echo $category['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label>⛽ Тип топлива</label>
                                <select name="fuel_type">
                                    <option value="diesel" <?php echo ($vehicleData['fuel_type'] ?? '') == 'diesel' ? 'selected' : ''; ?>>⛽ Дизель</option>
                                    <option value="petrol" <?php echo ($vehicleData['fuel_type'] ?? '') == 'petrol' ? 'selected' : ''; ?>>🔥 Бензин</option>
                                    <option value="gas" <?php echo ($vehicleData['fuel_type'] ?? '') == 'gas' ? 'selected' : ''; ?>>💨 Газ</option>
                                    <option value="electric" <?php echo ($vehicleData['fuel_type'] ?? '') == 'electric' ? 'selected' : ''; ?>>⚡ Электричество</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>📦 Объем бака (л) *</label>
                                <input type="number" name="tank_capacity" step="0.01" value="<?php echo $vehicleData['tank_capacity'] ?? ''; ?>" required>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>📝 Описание</label>
                            <textarea name="description" rows="3"><?php echo $vehicleData['description'] ?? ''; ?></textarea>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label>📊 Статус</label>
                                <select name="status">
                                    <option value="active" <?php echo ($vehicleData['status'] ?? '') == 'active' ? 'selected' : ''; ?>>✅ Активна</option>
                                    <option value="maintenance" <?php echo ($vehicleData['status'] ?? '') == 'maintenance' ? 'selected' : ''; ?>>🔧 На обслуживании</option>
                                    <option value="inactive" <?php echo ($vehicleData['status'] ?? '') == 'inactive' ? 'selected' : ''; ?>>⛔ Неактивна</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>🖼️ Изображение техники</label>
                                <input type="file" name="image" accept="image/*">
                                <?php if($editMode && $vehicleData['image']): ?>
                                    <div class="current-image">
                                        <img src="uploads/<?php echo $vehicleData['image']; ?>" alt="Текущее изображение" style="max-width: 200px; margin-top: 10px;">
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <?php echo $editMode ? '💾 Сохранить изменения' : '➕ Добавить технику'; ?>
                            </button>
                            <a href="vehicles.php" class="btn btn-secondary">Отмена</a>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>