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

$message = '';
if (isset($_GET['delete']) && hasPermission('engineer')) {
    $refuelId = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM refuels WHERE id = ?")->execute([$refuelId]);
    $message = "✅ Заправка успешно удалена!";
}

// Фильтры
$filterVehicle = $_GET['vehicle'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$filterTank = $_GET['tank'] ?? '';

$query = "
    SELECT r.*, v.name as vehicle_name, v.license_plate, u.full_name, ft.name as tank_name
    FROM refuels r 
    LEFT JOIN vehicles v ON r.vehicle_id = v.id 
    LEFT JOIN users u ON r.user_id = u.id 
    LEFT JOIN fuel_tanks ft ON r.tank_id = ft.id
    WHERE 1=1
";

$params = [];

if ($filterVehicle) {
    $query .= " AND r.vehicle_id = ?";
    $params[] = $filterVehicle;
}

if ($filterTank) {
    $query .= " AND r.tank_id = ?";
    $params[] = $filterTank;
}

if ($filterDateFrom) {
    $query .= " AND DATE(r.refuel_date) >= ?";
    $params[] = $filterDateFrom;
}

if ($filterDateTo) {
    $query .= " AND DATE(r.refuel_date) <= ?";
    $params[] = $filterDateTo;
}

$query .= " ORDER BY r.refuel_date DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$refuels = $stmt->fetchAll();

// Список техники для фильтра
$vehicles = $pdo->query("SELECT id, name, license_plate FROM vehicles ORDER BY name")->fetchAll();

// Список резервуаров для фильтра
$tanks = $pdo->query("SELECT id, name FROM fuel_tanks 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>⛽ Учет заправок - Агротопливо</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="theme-color" content="#27ae60">
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <h1>⛽ Учет заправок</h1>
                <div class="header-actions">
                    <a href="add_refuel.php" class="btn btn-primary">➕ Новая заправка</a>
                </div>
            </header>
            
            <?php if($message): ?>
                <div class="alert success"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-header">
                    <h3>🔍 Фильтры</h3>
                </div>
                <div class="card-body">
                    <form method="GET" class="filter-form">
                        <div class="form-row">
                            <div class="form-group">
                                <label>🚜 Техника</label>
                                <select name="vehicle">
                                    <option value="">Все</option>
                                    <?php foreach($vehicles as $v): ?>
                                        <option value="<?php echo $v['id']; ?>" <?php echo $filterVehicle == $v['id'] ? 'selected' : ''; ?>>
                                            <?php echo $v['name']; ?>
                                            <?php if(!empty($v['license_plate'])): ?>
                                                [<?php echo $v['license_plate']; ?>]
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>🏭 Резервуар</label>
                                <select name="tank">
                                    <option value="">Все</option>
                                    <?php foreach($tanks as $t): ?>
                                        <option value="<?php echo $t['id']; ?>" <?php echo $filterTank == $t['id'] ? 'selected' : ''; ?>>
                                            <?php echo $t['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>📅 Дата с</label>
                                <input type="date" name="date_from" value="<?php echo $filterDateFrom; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>📅 Дата по</label>
                                <input type="date" name="date_to" value="<?php echo $filterDateTo; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="submit" class="btn btn-primary">🔍 Применить</button>
                                <a href="refuels.php" class="btn btn-secondary">🔄 Сбросить</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h3>📋 Список заправок</h3>
                    <div class="header-info">
                        <span class="total-count">Всего заправок: <?php echo count($refuels); ?></span>
                    </div>
                </div>
                <div class="card-body">
                    <?php if($refuels): ?>
                        <div class="table-responsive">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Дата</th>
                                        <th>Техника</th>
                                        <th>Гос номер</th>
                                        <th>Резервуар</th>
                                        <th>Количество (л)</th>
                                        <th>Тип топлива</th>
                                        <th>Оператор</th>
                                        <th>Примечания</th>
                                        <?php if(hasPermission('engineer')): ?>
                                            <th>Действия</th>
                                        <?php endif; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($refuels as $refuel): ?>
                                    <tr>
                                        <td>
                                            <div class="datetime-cell">
                                                <span class="date"><?php echo date('d.m.Y', strtotime($refuel['refuel_date'])); ?></span>
                                                <span class="time"><?php echo date('H:i', strtotime($refuel['refuel_date'])); ?></span>
                                            </div>
                                        </td>
                                        <td>
                                            <a href="vehicle_details.php?id=<?php echo $refuel['vehicle_id']; ?>" class="vehicle-link">
                                                🚜 <?php echo $refuel['vehicle_name']; ?>
                                            </a>
                                        </td>
                                        <td>
                                            <?php if(!empty($refuel['license_plate'])): ?>
                                                <span class="license-plate"><?php echo $refuel['license_plate']; ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="tank-badge">
                                                🏭 <?php echo $refuel['tank_name']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="fuel-amount">
                                                <?php echo $refuel['fuel_amount']; ?> л
                                            </span>
                                        </td>
                                        <td>
                                            <span class="fuel-type-badge">
                                                <?php 
                                                $fuelIcons = [
                                                    'diesel' => 'Дизель ⛽',
                                                    'petrol' => 'Бензин 🔥',
                                                    'gas' => '💨',
                                                    'electric' => '⚡'
                                                ];
                                                echo $fuelIcons[$refuel['fuel_type']] ?? $refuel['fuel_type'];
                                                ?>
                                            </span>
                                        </td>
                                        <td><?php echo $refuel['full_name']; ?></td>
                                        <td>
                                            <span class="notes-text">
                                                <?php echo $refuel['notes'] ?: '-'; ?>
                                            </span>
                                        </td>
                                        <?php if(hasPermission('engineer')): ?>
                                            <td>
                                                <div class="action-buttons">
                                                    <a href="refuels.php?delete=<?php echo $refuel['id']; ?>" 
                                                       class="btn btn-sm btn-danger" 
                                                       onclick="return confirm('Удалить заправку?')"
                                                       title="Удалить заправку">
                                                       🗑️
                                                    </a>
                                                </div>
                                            </td>
                                        <?php endif; ?>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-icon">⛽</div>
                            <h3>Заправки не найдены</h3>
                            <p>По выбранным фильтрам не найдено ни одной заправки</p>
                            <a href="refuels.php" class="btn btn-secondary">🔄 Сбросить фильтры</a>
                            <a href="add_refuel.php" class="btn btn-primary">➕ Добавить заправку</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>