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

if (!isset($_GET['id'])) {
    header('Location: vehicles.php');
    exit();
}

$vehicleId = intval($_GET['id']);
$stmt = $pdo->prepare("
    SELECT v.*, vc.name as category_name 
    FROM vehicles v 
    LEFT JOIN vehicle_categories vc ON v.category_id = vc.id 
    WHERE v.id = ?
");
$stmt->execute([$vehicleId]);
$vehicle = $stmt->fetch();

if (!$vehicle) {
    header('Location: vehicles.php');
    exit();
}

// Получаем историю заправок
$stmt = $pdo->prepare("
    SELECT r.*, u.full_name, ft.name as tank_name 
    FROM refuels r 
    LEFT JOIN users u ON r.user_id = u.id 
    LEFT JOIN fuel_tanks ft ON r.tank_id = ft.id 
    WHERE r.vehicle_id = ? 
    ORDER BY r.refuel_date DESC
");
$stmt->execute([$vehicleId]);
$refuels = $stmt->fetchAll();

// Статистика по заправкам
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as total_refuels,
        SUM(fuel_amount) as total_fuel,
        AVG(fuel_amount) as avg_fuel,
        MIN(refuel_date) as first_refuel,
        MAX(refuel_date) as last_refuel
    FROM refuels 
    WHERE vehicle_id = ?
");
$stmt->execute([$vehicleId]);
$stats = $stmt->fetch();

// Статистика за последний месяц
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as monthly_refuels,
        SUM(fuel_amount) as monthly_fuel
    FROM refuels 
    WHERE vehicle_id = ? 
    AND refuel_date >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
");
$stmt->execute([$vehicleId]);
$monthlyStats = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>👀 <?php echo $vehicle['name']; ?> - Агротопливо</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <div class="header-main">
                    <a href="vehicles.php" class="btn btn-secondary">← Назад</a>
                    <h1>👀 <?php echo $vehicle['name']; ?></h1>
                </div>
                <div class="header-actions">
                    <a href="add_refuel.php?vehicle=<?php echo $vehicle['id']; ?>" class="btn btn-primary">⛽ Заправить</a>
                    <?php if(hasPermission('engineer')): ?>
                        <a href="add_vehicle.php?edit=<?php echo $vehicle['id']; ?>" class="btn btn-warning">✏️ Редактировать</a>
                    <?php endif; ?>
                </div>
            </header>
            
            <div class="content-grid">
                <div class="card">
                    <div class="card-header">
                        <h3>📊 Информация о технике</h3>
                    </div>
                    <div class="card-body">
                        <div class="vehicle-detail">
                            <div class="detail-image">
                                <?php if($vehicle['image']): ?>
                                    <img src="uploads/<?php echo $vehicle['image']; ?>" alt="<?php echo $vehicle['name']; ?>">
                                <?php else: ?>
                                    <div class="vehicle-placeholder large">🚜</div>
                                <?php endif; ?>
                            </div>
                            <div class="detail-info">
                                <div class="detail-row">
                                    <span class="detail-label">Название:</span>
                                    <span class="detail-value"><?php echo $vehicle['name']; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Тип:</span>
                                    <span class="detail-value"><?php echo $vehicle['type'] ?? 'Не указан'; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Модель:</span>
                                    <span class="detail-value"><?php echo $vehicle['model'] ?? 'Не указана'; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Год выпуска:</span>
                                    <span class="detail-value"><?php echo $vehicle['year'] ?? 'Не указан'; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Госномер:</span>
                                    <span class="detail-value"><?php echo $vehicle['license_plate'] ?? 'Не указан'; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Категория:</span>
                                    <span class="detail-value"><?php echo $vehicle['category_name'] ?? 'Не указана'; ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Объем бака:</span>
                                    <span class="detail-value"><?php echo $vehicle['tank_capacity']; ?> л</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Тип топлива:</span>
                                    <span class="detail-value">
                                        <?php 
                                        $fuelTypes = [
                                            'diesel' => '⛽ Дизель',
                                            'petrol' => '🔥 Бензин',
                                            'gas' => '💨 Газ',
                                            'electric' => '⚡ Электричество'
                                        ];
                                        echo $fuelTypes[$vehicle['fuel_type']];
                                        ?>
                                    </span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Пробег:</span>
                                    <span class="detail-value"><?php echo number_format($vehicle['mileage'], 2); ?> км</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Описание:</span>
                                    <span class="detail-value"><?php echo $vehicle['description'] ?? 'Нет описания'; ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3>📈 Статистика заправок</h3>
                    </div>
                    <div class="card-body">
                        <div class="stats-grid mini">
                            <div class="stat-card mini">
                                <div class="stat-icon">⛽</div>
                                <div class="stat-info">
                                    <h3>Всего заправок</h3>
                                    <span class="stat-number"><?php echo $stats['total_refuels'] ?? 0; ?></span>
                                </div>
                            </div>
                            <div class="stat-card mini">
                                <div class="stat-icon">🔥</div>
                                <div class="stat-info">
                                    <h3>Всего топлива</h3>
                                    <span class="stat-number"><?php echo number_format($stats['total_fuel'] ?? 0, 2); ?> л</span>
                                </div>
                            </div>
                            <div class="stat-card mini">
                                <div class="stat-icon">📅</div>
                                <div class="stat-info">
                                    <h3>Средний расход</h3>
                                    <span class="stat-number">
                                        <?php 
                                        $avg = $stats['avg_fuel'] ?? 0;
                                        echo number_format($avg, 2); 
                                        ?> л/заправка
                                    </span>
                                </div>
                            </div>
                            <div class="stat-card mini">
                                <div class="stat-icon">📊</div>
                                <div class="stat-info">
                                    <h3>За 30 дней</h3>
                                    <span class="stat-number">
                                        <?php echo number_format($monthlyStats['monthly_fuel'] ?? 0, 2); ?> л
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <?php if($stats['first_refuel']): ?>
                        <div class="timeline-info">
                            <div class="timeline-item">
                                <span class="timeline-label">Первая заправка:</span>
                                <span class="timeline-value"><?php echo date('d.m.Y', strtotime($stats['first_refuel'])); ?></span>
                            </div>
                            <div class="timeline-item">
                                <span class="timeline-label">Последняя заправка:</span>
                                <span class="timeline-value"><?php echo date('d.m.Y', strtotime($stats['last_refuel'])); ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h3>🕒 История заправок</h3>
                </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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($refuels as $refuel): ?>
                                    <tr>
                                        <td><?php echo date('d.m.Y H:i', strtotime($refuel['refuel_date'])); ?></td>
                                        <td><?php echo $refuel['tank_name']; ?></td>
                                        <td><?php echo $refuel['fuel_amount']; ?> л</td>
                                        <td>
                                            <?php 
                                            $fuelIcons = [
                                                'diesel' => '⛽',
                                                'petrol' => '🔥',
                                                'gas' => '💨',
                                                'electric' => '⚡'
                                            ];
                                            echo $fuelIcons[$refuel['fuel_type']] ?? $refuel['fuel_type'];
                                            ?>
                                        </td>
                                        <td><?php echo $refuel['full_name']; ?></td>
                                        <td><?php echo $refuel['notes'] ?? '-'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-icon">⛽</div>
                            <h3>Заправок не найдено</h3>
                            <p>У этой техники еще не было заправок</p>
                            <a href="add_refuel.php?vehicle=<?php echo $vehicle['id']; ?>" class="btn btn-primary">⛽ Добавить первую заправку</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>