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

$message = '';
$vehicleId = $_GET['vehicle'] ?? ($_POST['vehicle_id'] ?? '');

// Получаем список техники
$vehicles = $pdo->query("SELECT * FROM vehicles WHERE status = 'active' ORDER BY name")->fetchAll();

// Получаем список резервуаров с достаточным количеством топлива
$tanks = $pdo->query("SELECT * FROM fuel_tanks WHERE status = 'active' AND current_level > 0 ORDER BY name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vehicle_id = intval($_POST['vehicle_id'] ?? 0);
    $tank_id = intval($_POST['tank_id'] ?? 0);
    $fuel_amount = floatval($_POST['fuel_amount'] ?? 0);
    $notes = sanitizeInput($_POST['notes'] ?? '');
    $refuel_date = $_POST['refuel_date'] ?? date('Y-m-d H:i:s');
    
    // Валидация обязательных полей
    if ($vehicle_id <= 0 || $tank_id <= 0 || $fuel_amount <= 0) {
        $message = "❌ Ошибка: Заполните все обязательные поля!";
    } else {
        // Проверяем объем бака техники
        $stmt = $pdo->prepare("SELECT tank_capacity, fuel_type FROM vehicles WHERE id = ?");
        $stmt->execute([$vehicle_id]);
        $vehicle = $stmt->fetch();
        
        // Проверяем уровень топлива в резервуаре
        $stmt = $pdo->prepare("SELECT current_level, fuel_type FROM fuel_tanks WHERE id = ?");
        $stmt->execute([$tank_id]);
        $tank = $stmt->fetch();
        
        if ($vehicle && $tank) {
            if ($fuel_amount > $vehicle['tank_capacity']) {
                $message = "❌ Ошибка: Нельзя заправить больше объема бака! Максимум: " . $vehicle['tank_capacity'] . " л";
            } elseif ($fuel_amount > $tank['current_level']) {
                $message = "❌ Ошибка: В резервуаре недостаточно топлива! Доступно: " . $tank['current_level'] . " л";
            } elseif ($vehicle['fuel_type'] !== $tank['fuel_type']) {
                $message = "❌ Ошибка: Тип топлива в технике и резервуаре не совпадает!";
            } else {
                try {
                    $pdo->beginTransaction();
                    
                    // Добавляем заправку
                    $stmt = $pdo->prepare("INSERT INTO refuels (vehicle_id, tank_id, user_id, fuel_amount, fuel_type, refuel_date, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$vehicle_id, $tank_id, $_SESSION['user_id'], $fuel_amount, $vehicle['fuel_type'], $refuel_date, $notes]);
                    
                    // Обновляем уровень в резервуаре (отнимаем заправленное количество)
                    $stmt = $pdo->prepare("UPDATE fuel_tanks SET current_level = current_level - ? WHERE id = ?");
                    $stmt->execute([$fuel_amount, $tank_id]);
                    
                    $pdo->commit();
                    $message = "✅ Заправка успешно добавлена!";
                    
                    // Очищаем форму
                    $_POST = [];
                    $vehicleId = '';
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $message = "❌ Ошибка при добавлении заправки: " . $e->getMessage();
                }
            }
        } else {
            $message = "❌ Ошибка: Техника или резервуар не найдены!";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>⛽ Добавление заправки - Агротопливо</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>⛽ Добавление заправки</h1>
                <a href="refuels.php" class="btn btn-secondary">← Назад к списку</a>
            </header>
            
            <?php if($message): ?>
                <div class="alert <?php echo strpos($message, '❌') !== false ? 'error' : 'success'; ?>"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body">
                    <form method="POST" class="form">
                        <div class="form-row">
                            <div class="form-group">
                                <label>🚜 Техника *</label>
                                <select name="vehicle_id" id="vehicleSelect" required>
                                    <option value="">Выберите технику</option>
                                    <?php foreach($vehicles as $vehicle): ?>
                                        <option value="<?php echo $vehicle['id']; ?>" 
                                                data-capacity="<?php echo $vehicle['tank_capacity']; ?>"
                                                data-fuel-type="<?php echo $vehicle['fuel_type']; ?>"
                                                <?php echo ($vehicleId == $vehicle['id'] || ($_POST['vehicle_id'] ?? '') == $vehicle['id']) ? 'selected' : ''; ?>>
                                            <?php echo $vehicle['name']; ?> 
                                            <?php if(!empty($vehicle['license_plate'])): ?>
                                                [<?php echo $vehicle['license_plate']; ?>]
                                            <?php endif; ?>
                                            (Бак: <?php echo $vehicle['tank_capacity']; ?> л, 
                                            <?php 
                                            $fuelTypes = [
                                                'diesel' => '⛽ Дизель',
                                                'petrol' => '🔥 Бензин',
                                                'gas' => '💨 Газ',
                                                'electric' => '⚡ Электричество'
                                            ];
                                            echo $fuelTypes[$vehicle['fuel_type']];
                                            ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>🏭 Резервуар *</label>
                                <select name="tank_id" id="tankSelect" required>
                                    <option value="">Выберите резервуар</option>
                                    <?php foreach($tanks as $tank): ?>
                                        <option value="<?php echo $tank['id']; ?>" 
                                                data-current-level="<?php echo $tank['current_level']; ?>"
                                                data-fuel-type="<?php echo $tank['fuel_type']; ?>"
                                                <?php echo ($_POST['tank_id'] ?? '') == $tank['id'] ? 'selected' : ''; ?>>
                                            <?php echo $tank['name']; ?> (Осталось: <?php echo $tank['current_level']; ?> л, 
                                            <?php 
                                            echo $fuelTypes[$tank['fuel_type']];
                                            ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label>📅 Дата заправки</label>
                                <input type="datetime-local" name="refuel_date" value="<?php echo $_POST['refuel_date'] ?? date('Y-m-d\TH:i'); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>⛽ Количество топлива (л) *</label>
                                <input type="number" name="fuel_amount" id="fuelAmount" step="0.01" value="<?php echo $_POST['fuel_amount'] ?? ''; ?>" required>
                                <small id="fuelHint">Максимально можно заправить: <span id="maxFuel">0</span> л</small>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>📝 Примечания</label>
                            <textarea name="notes" rows="3"><?php echo $_POST['notes'] ?? ''; ?></textarea>
                        </div>
                        
                        <div class="refuel-preview" id="refuelPreview" style="display: none;">
                            <h4>📊 Предварительный просмотр:</h4>
                            <div class="preview-info">
                                <div class="preview-item">
                                    <span>Объем бака техники:</span>
                                    <strong id="tankCapacity">0</strong> л
                                </div>
                                <div class="preview-item">
                                    <span>Доступно в резервуаре:</span>
                                    <strong id="tankAvailable">0</strong> л
                                </div>
                                <div class="preview-item">
                                    <span>Можно заправить:</span>
                                    <strong id="maxPossible" class="success">0</strong> л
                                </div>
                                <div class="preview-item" id="fuelTypeCheck" style="display: none;">
                                    <span>Совместимость топлива:</span>
                                    <strong id="compatibilityStatus" class="error">❌ Не совпадает</strong>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">⛽ Добавить заправку</button>
                            <a href="refuels.php" class="btn btn-secondary">Отмена</a>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const vehicleSelect = document.getElementById('vehicleSelect');
            const tankSelect = document.getElementById('tankSelect');
            const fuelAmount = document.getElementById('fuelAmount');
            const maxFuelSpan = document.getElementById('maxFuel');
            const refuelPreview = document.getElementById('refuelPreview');
            const tankCapacitySpan = document.getElementById('tankCapacity');
            const tankAvailableSpan = document.getElementById('tankAvailable');
            const maxPossibleSpan = document.getElementById('maxPossible');
            const fuelTypeCheck = document.getElementById('fuelTypeCheck');
            const compatibilityStatus = document.getElementById('compatibilityStatus');
            
            function updateRefuelInfo() {
                const selectedVehicle = vehicleSelect.options[vehicleSelect.selectedIndex];
                const selectedTank = tankSelect.options[tankSelect.selectedIndex];
                
                const vehicleCapacity = parseFloat(selectedVehicle.getAttribute('data-capacity')) || 0;
                const vehicleFuelType = selectedVehicle.getAttribute('data-fuel-type') || '';
                const tankCurrentLevel = parseFloat(selectedTank.getAttribute('data-current-level')) || 0;
                const tankFuelType = selectedTank.getAttribute('data-fuel-type') || '';
                
                const fuelToAdd = parseFloat(fuelAmount.value) || 0;
                
                if (vehicleCapacity > 0 && tankCurrentLevel > 0) {
                    refuelPreview.style.display = 'block';
                    tankCapacitySpan.textContent = vehicleCapacity.toFixed(2);
                    tankAvailableSpan.textContent = tankCurrentLevel.toFixed(2);
                    
                    const maxPossible = Math.min(vehicleCapacity, tankCurrentLevel);
                    maxPossibleSpan.textContent = maxPossible.toFixed(2);
                    maxFuelSpan.textContent = maxPossible.toFixed(2);
                    
                    // Проверка совместимости типов топлива
                    if (vehicleFuelType && tankFuelType) {
                        fuelTypeCheck.style.display = 'block';
                        if (vehicleFuelType === tankFuelType) {
                            compatibilityStatus.textContent = '✅ Совместимо';
                            compatibilityStatus.className = 'success';
                        } else {
                            compatibilityStatus.textContent = '❌ Не совпадает';
                            compatibilityStatus.className = 'error';
                        }
                    } else {
                        fuelTypeCheck.style.display = 'none';
                    }
                    
                    // Подсветка предупреждения
                    if (fuelToAdd > maxPossible) {
                        fuelAmount.style.borderColor = '#e74c3c';
                    } else {
                        fuelAmount.style.borderColor = '';
                    }
                } else {
                    refuelPreview.style.display = 'none';
                }
            }
            
            vehicleSelect.addEventListener('change', updateRefuelInfo);
            tankSelect.addEventListener('change', updateRefuelInfo);
            fuelAmount.addEventListener('input', updateRefuelInfo);
            
            // Инициализация при загрузке
            updateRefuelInfo();
        });
    </script>
</body>
</html>