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

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

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tank_id = intval($_POST['tank_id']);
    $receipt_date = $_POST['receipt_date'] ?: date('Y-m-d H:i:s');
    $fuel_type = $_POST['fuel_type'];
    $fuel_amount = floatval($_POST['fuel_amount']);
    $supplier = sanitizeInput($_POST['supplier']);
    $driver_name = sanitizeInput($_POST['driver_name']);
    $vehicle_number = sanitizeInput($_POST['vehicle_number']);
    $document_number = sanitizeInput($_POST['document_number']);
    $quality_check = isset($_POST['quality_check']) ? 1 : 0;
    $notes = sanitizeInput($_POST['notes']);
    
    // Проверяем, не превысит ли добавление топлива вместимость резервуара
    $stmt = $pdo->prepare("SELECT capacity, current_level, fuel_type FROM fuel_tanks WHERE id = ?");
    $stmt->execute([$tank_id]);
    $tank = $stmt->fetch();
    
    if ($tank) {
        // Проверяем соответствие типа топлива
        if ($tank['fuel_type'] != $fuel_type) {
            $message = "❌ Ошибка: Тип топлива в резервуаре ({$tank['fuel_type']}) и в приёмке ({$fuel_type}) не совпадает!";
        } else {
            $newLevel = $tank['current_level'] + $fuel_amount;
            
            if ($newLevel > $tank['capacity']) {
                $message = "❌ Ошибка: При добавлении топлива резервуар будет переполнен! Максимум можно добавить: " . ($tank['capacity'] - $tank['current_level']) . " л";
            } else {
                try {
                    $pdo->beginTransaction();
                    
                    // Добавляем приёмку топлива
                    $stmt = $pdo->prepare("INSERT INTO fuel_receipts (tank_id, receipt_date, fuel_type, fuel_amount, supplier, driver_name, vehicle_number, document_number, quality_check, notes, received_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$tank_id, $receipt_date, $fuel_type, $fuel_amount, $supplier, $driver_name, $vehicle_number, $document_number, $quality_check, $notes, $_SESSION['user_id']]);
                    
                    // Обновляем уровень в резервуаре
                    $stmt = $pdo->prepare("UPDATE fuel_tanks SET current_level = ? WHERE id = ?");
                    $stmt->execute([$newLevel, $tank_id]);
                    
                    $pdo->commit();
                    $message = "✅ Топливо успешно принято!";
                    
                    // Очищаем форму
                    $_POST = [];
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $message = "❌ Ошибка при приёмке топлива: " . $e->getMessage();
                }
            }
        }
    } else {
        $message = "❌ Ошибка: Резервуар не найден!";
    }
}

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

// Получаем историю приёмок
$receipts = $pdo->query("
    SELECT fr.*, ft.name as tank_name, u.full_name as received_by_name 
    FROM fuel_receipts fr 
    LEFT JOIN fuel_tanks ft ON fr.tank_id = ft.id 
    LEFT JOIN users u ON fr.received_by = u.id 
    ORDER BY fr.receipt_date DESC 
    LIMIT 50
")->fetchAll();
?>
<!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">
    <style>
        .alert {
            padding: 12px 16px;
            border-radius: 4px;
            margin: 15px 0;
            border: 1px solid transparent;
        }
        
        .alert.success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        
        .alert.error {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        
        .fuel-gauge {
            height: 20px;
            background-color: #eee;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        
        .gauge-background {
            width: 100%;
            height: 100%;
            position: relative;
        }
        
        .gauge-fill {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #8BC34A);
            transition: width 0.3s ease;
            border-radius: 10px;
        }
        
        .preview-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin: 15px 0;
        }
        
        .receipt-preview {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            border: 1px solid #e9ecef;
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <h1>📥 Приёмка топлива</h1>
                <div class="header-actions">
                    <span class="current-date">📅 <?php echo date('d.m.Y'); ?></span>
                </div>
            </header>
            
            <?php if($message): ?>
                <div class="alert <?php echo strpos($message, '❌') !== false ? 'error' : 'success'; ?>"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>➕ Новая приёмка топлива</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" class="form">
                            <div class="form-row">
                                <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-capacity="<?php echo $tank['capacity']; ?>"
                                                    data-current="<?php echo $tank['current_level']; ?>"
                                                    data-fuel-type="<?php echo $tank['fuel_type']; ?>">
                                                <?php echo $tank['name']; ?> (Сейчас: <?php echo $tank['current_level']; ?> л, Вместимость: <?php echo $tank['capacity']; ?> л, Тип: <?php echo $tank['fuel_type']; ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label>📅 Дата приёмки</label>
                                    <input type="datetime-local" name="receipt_date" value="<?php echo $_POST['receipt_date'] ?? date('Y-m-d\TH:i'); ?>">
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label>⛽ Тип топлива *</label>
                                    <select name="fuel_type" id="fuelType" required>
                                        <option value="diesel" <?php echo ($_POST['fuel_type'] ?? '') == 'diesel' ? 'selected' : ''; ?>>⛽ Дизель</option>
                                        <option value="petrol" <?php echo ($_POST['fuel_type'] ?? '') == 'petrol' ? 'selected' : ''; ?>>🔥 Бензин</option>
                                        <option value="gas" <?php echo ($_POST['fuel_type'] ?? '') == 'gas' ? 'selected' : ''; ?>>💨 Газ</option>
                                        <option value="electric" <?php echo ($_POST['fuel_type'] ?? '') == 'electric' ? 'selected' : ''; ?>>⚡ Электричество</option>
                                    </select>
                                </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="capacityHint">Можно добавить максимум: <span id="maxCapacity">0</span> л</small>
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label>🏢 Поставщик *</label>
                                    <input type="text" name="supplier" value="<?php echo $_POST['supplier'] ?? ''; ?>" required>
                                </div>
                                
                                <div class="form-group">
                                    <label>👤 Водитель</label>
                                    <input type="text" name="driver_name" value="<?php echo $_POST['driver_name'] ?? ''; ?>">
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label>🚚 Номер машины</label>
                                    <input type="text" name="vehicle_number" value="<?php echo $_POST['vehicle_number'] ?? ''; ?>">
                                </div>
                                
                                <div class="form-group">
                                    <label>📄 Номер документа</label>
                                    <input type="text" name="document_number" value="<?php echo $_POST['document_number'] ?? ''; ?>">
                                </div>
                            </div>
                            
                            <div class="form-group checkbox">
                                <label>
                                    <input type="checkbox" name="quality_check" <?php echo isset($_POST['quality_check']) ? 'checked' : ''; ?>>
                                    <span class="checkmark"></span>
                                    ✅ Качество топлива проверено
                                </label>
                            </div>
                            
                            <div class="form-group">
                                <label>📝 Примечания</label>
                                <textarea name="notes" rows="3"><?php echo $_POST['notes'] ?? ''; ?></textarea>
                            </div>
                            
                            <div class="receipt-preview" id="receiptPreview" style="display: none;">
                                <h4>📊 Предварительный просмотр:</h4>
                                <div class="preview-info">
                                    <p>Текущий уровень: <span id="currentLevel">0</span> л</p>
                                    <p>После приёмки: <span id="afterReceipt">0</span> л</p>
                                    <p>Заполненность резервуара: <span id="tankFill">0</span>%</p>
                                </div>
                                <div class="fuel-gauge preview">
                                    <div class="gauge-background">
                                        <div class="gauge-fill" id="previewGauge" style="width: 0%"></div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="submit" class="btn btn-primary">📥 Принять топливо</button>
                                <button type="reset" class="btn btn-secondary">Очистить форму</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>📋 История приёмок</h3>
                    </div>
                    <div class="card-body">
                        <?php if($receipts): ?>
                            <div class="table-responsive">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Дата</th>
                                            <th>Резервуар</th>
                                            <th>Тип</th>
                                            <th>Количество</th>
                                            <th>Поставщик</th>
                                            <th>Водитель</th>
                                            <th>Принял</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($receipts as $receipt): ?>
                                        <tr>
                                            <td><?php echo date('d.m.Y H:i', strtotime($receipt['receipt_date'])); ?></td>
                                            <td><?php echo $receipt['tank_name']; ?></td>
                                            <td>
                                                <?php 
                                                $fuelTypes = [
                                                    'diesel' => '⛽',
                                                    'petrol' => '🔥',
                                                    'gas' => '💨',
                                                    'electric' => '⚡'
                                                ];
                                                echo $fuelTypes[$receipt['fuel_type']] ?? $receipt['fuel_type'];
                                                ?>
                                            </td>
                                            <td><?php echo $receipt['fuel_amount']; ?> л</td>
                                            <td><?php echo $receipt['supplier']; ?></td>
                                            <td><?php echo $receipt['driver_name'] ?: '-'; ?></td>
                                            <td><?php echo $receipt['received_by_name']; ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <p class="no-data">😴 Нет данных о приёмках топлива</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const tankSelect = document.getElementById('tankSelect');
            const fuelAmount = document.getElementById('fuelAmount');
            const maxCapacitySpan = document.getElementById('maxCapacity');
            const receiptPreview = document.getElementById('receiptPreview');
            const currentLevelSpan = document.getElementById('currentLevel');
            const afterReceiptSpan = document.getElementById('afterReceipt');
            const tankFillSpan = document.getElementById('tankFill');
            const previewGauge = document.getElementById('previewGauge');
            const fuelTypeSelect = document.getElementById('fuelType');
            
            function updateReceiptInfo() {
                const selectedOption = tankSelect.options[tankSelect.selectedIndex];
                const tankCapacity = parseFloat(selectedOption.getAttribute('data-capacity')) || 0;
                const currentLevel = parseFloat(selectedOption.getAttribute('data-current')) || 0;
                const tankFuelType = selectedOption.getAttribute('data-fuel-type') || '';
                const fuelToAdd = parseFloat(fuelAmount.value) || 0;
                
                const maxCapacity = tankCapacity - currentLevel;
                maxCapacitySpan.textContent = maxCapacity.toFixed(2);
                
                if (tankCapacity > 0 && tankSelect.value) {
                    receiptPreview.style.display = 'block';
                    currentLevelSpan.textContent = currentLevel.toFixed(2);
                    
                    const afterReceipt = currentLevel + fuelToAdd;
                    afterReceiptSpan.textContent = afterReceipt.toFixed(2);
                    
                    const fillPercentage = Math.min(100, (afterReceipt / tankCapacity) * 100);
                    tankFillSpan.textContent = fillPercentage.toFixed(1);
                    previewGauge.style.width = fillPercentage + '%';
                    
                    // Удаляем предыдущие предупреждения об ошибке
                    const existingWarning = document.querySelector('.alert.error');
                    if (existingWarning && existingWarning.parentNode === receiptPreview) {
                        existingWarning.remove();
                    }
                    
                    // Проверка совместимости типов топлива
                    const selectedFuelType = fuelTypeSelect.value;
                    if (tankFuelType && selectedFuelType && tankFuelType !== selectedFuelType) {
                        const warningDiv = document.createElement('div');
                        warningDiv.className = 'alert error';
                        warningDiv.textContent = '❌ Внимание: Тип топлива в резервуаре и приёмке не совпадает!';
                        receiptPreview.appendChild(warningDiv);
                        
                        // Подсветка поля типа топлива
                        fuelTypeSelect.style.borderColor = '#e74c3c';
                    } else {
                        fuelTypeSelect.style.borderColor = '';
                    }
                    
                    // Подсветка предупреждения о переполнении
                    if (fuelToAdd > maxCapacity) {
                        fuelAmount.style.borderColor = '#e74c3c';
                    } else {
                        fuelAmount.style.borderColor = '';
                    }
                } else {
                    receiptPreview.style.display = 'none';
                }
            }
            
            tankSelect.addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const tankFuelType = selectedOption.getAttribute('data-fuel-type');
                
                // Автоматически устанавливаем тип топлива из резервуара
                if (tankFuelType && tankFuelType !== '') {
                    fuelTypeSelect.value = tankFuelType;
                }
                
                updateReceiptInfo();
            });
            
            fuelAmount.addEventListener('input', updateReceiptInfo);
            fuelTypeSelect.addEventListener('change', updateReceiptInfo);
            
            // Инициализация при загрузке
            updateReceiptInfo();
        });
    </script>
</body>
</html>