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

// Получаем статистику для дашборда
$totalVehicles = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE status = 'active'")->fetchColumn();
$monthlyRefuels = $pdo->query("SELECT COUNT(*) FROM refuels WHERE MONTH(refuel_date) = MONTH(CURRENT_DATE())")->fetchColumn();
$totalFuelInTanks = $pdo->query("SELECT SUM(current_level) FROM fuel_tanks")->fetchColumn();
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();

// Получаем последние заправки с изображениями техники
$recentRefuels = $pdo->query("
    SELECT r.*, v.name as vehicle_name, v.image as vehicle_image, 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
    ORDER BY r.refuel_date DESC 
    LIMIT 6
")->fetchAll();

// Получаем резервуары с низким уровнем (< 20%)
$lowFuelTanks = $pdo->query("
    SELECT *, (current_level/capacity)*100 as fill_percentage 
    FROM fuel_tanks 
    WHERE (current_level/capacity)*100 < 20 
    AND status = 'active'
    ORDER BY fill_percentage ASC
    LIMIT 3
")->fetchAll();

// Получаем последние приёмки топлива
$recentReceipts = $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 5
")->fetchAll();

// Получаем технику на обслуживании
$maintenanceVehicles = $pdo->query("
    SELECT * FROM vehicles 
    WHERE status = 'maintenance' 
    ORDER BY created_at DESC 
    LIMIT 3
")->fetchAll();

// Статистика по типам топлива
$fuelTypeStats = $pdo->query("
    SELECT fuel_type, SUM(current_level) as total_fuel, COUNT(*) as tank_count
    FROM fuel_tanks 
    WHERE status = 'active'
    GROUP BY fuel_type
")->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">
</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>
            
            <!-- Верхняя статистика -->
            <div class="stats-grid">
                <div class="stat-card primary">
                    <div class="stat-icon">🚜</div>
                    <div class="stat-info">
                        <h3>Активная техника</h3>
                        <span class="stat-number"><?php echo $totalVehicles; ?></span>
                    </div>
                </div>
                
                <div class="stat-card success">
                    <div class="stat-icon">⛽</div>
                    <div class="stat-info">
                        <h3>Заправки за месяц</h3>
                        <span class="stat-number"><?php echo $monthlyRefuels; ?></span>
                    </div>
                </div>
                
                <div class="stat-card warning">
                    <div class="stat-icon">🏭</div>
                    <div class="stat-info">
                        <h3>Топливо в резервуарах</h3>
                        <span class="stat-number"><?php echo number_format($totalFuelInTanks, 0); ?> л</span>
                    </div>
                </div>
                
                <div class="stat-card info">
                    <div class="stat-icon">👥</div>
                    <div class="stat-info">
                        <h3>Пользователи</h3>
                        <span class="stat-number"><?php echo $totalUsers; ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Основная сетка контента -->
            <div class="content-grid">
                <!-- Левая колонка -->
                <div class="content-column">
                    <div class="card">
                        <div class="card-header">
                            <h3>📋 Последние заправки</h3>
                            <a href="refuels.php" class="btn-link">Все заправки →</a>
                        </div>
                        <div class="card-body">
                            <?php if($recentRefuels): ?>
                                <div class="compact-list">
                                    <?php foreach($recentRefuels as $refuel): ?>
                                    <div class="compact-item">
                                        <div class="compact-image">
                                            <?php if($refuel['vehicle_image']): ?>
                                                <img src="uploads/<?php echo $refuel['vehicle_image']; ?>" alt="<?php echo $refuel['vehicle_name']; ?>" class="vehicle-mini">
                                            <?php else: ?>
                                                <div class="vehicle-mini placeholder">🚜</div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="compact-content">
                                            <div class="compact-title">
                                                <span class="vehicle-name"><?php echo $refuel['vehicle_name']; ?></span>
                                                <span class="fuel-amount"><?php echo $refuel['fuel_amount']; ?> л</span>
                                            </div>
                                            <div class="compact-details">
                                                <span class="tank-name"><?php echo $refuel['tank_name']; ?></span>
                                                <span class="compact-time"><?php echo date('H:i', strtotime($refuel['refuel_date'])); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state mini">
                                    <div class="empty-icon">⛽</div>
                                    <p>Нет данных о заправках</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3>🔧 Техника на обслуживании</h3>
                            <a href="vehicles.php" class="btn-link">Вся техника →</a>
                        </div>
                        <div class="card-body">
                            <?php if($maintenanceVehicles): ?>
                                <div class="compact-list">
                                    <?php foreach($maintenanceVehicles as $vehicle): ?>
                                    <div class="compact-item">
                                        <div class="compact-image">
                                            <?php if($vehicle['image']): ?>
                                                <img src="uploads/<?php echo $vehicle['image']; ?>" alt="<?php echo $vehicle['name']; ?>" class="vehicle-mini">
                                            <?php else: ?>
                                                <div class="vehicle-mini placeholder">🔧</div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="compact-content">
                                            <div class="compact-title">
                                                <span class="vehicle-name"><?php echo $vehicle['name']; ?></span>
                                                <span class="status-badge maintenance">🔧</span>
                                            </div>
                                            <div class="compact-details">
                                                <span class="vehicle-type"><?php echo $vehicle['type'] ?? 'Сельхозтехника'; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="success-state mini">
                                    <div class="success-icon">✅</div>
                                    <p>Вся техника активна</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Правая колонка -->
                <div class="content-column">
                    <div class="card">
                        <div class="card-header">
                            <h3>🏭 Состояние резервуаров</h3>
                            <a href="fuel_tanks.php" class="btn-link">Все резервуары →</a>
                        </div>
                        <div class="card-body">
                            <?php 
                            $tanks = $pdo->query("SELECT * FROM fuel_tanks WHERE status = 'active' ORDER BY current_level DESC LIMIT 4")->fetchAll();
                            if ($tanks): ?>
                                <div class="tanks-mini-grid">
                                    <?php foreach($tanks as $tank): ?>
                                    <div class="tank-mini-card">
                                        <div class="tank-mini-header">
                                            <h4><?php echo $tank['name']; ?></h4>
                                            <span class="fuel-type-icon">
                                                <?php 
                                                $fuelIcons = [
                                                    'diesel' => '⛽',
                                                    'petrol' => '🔥',
                                                    'gas' => '💨',
                                                    'electric' => '⚡'
                                                ];
                                                echo $fuelIcons[$tank['fuel_type']];
                                                ?>
                                            </span>
                                        </div>
                                        <div class="tank-mini-info">
                                            <span class="current-fuel"><?php echo number_format($tank['current_level'], 0); ?> л</span>
                                            <span class="capacity">/ <?php echo number_format($tank['capacity'], 0); ?> л</span>
                                        </div>
                                        <?php 
                                        $fillPercentage = ($tank['current_level'] / $tank['capacity']) * 100;
                                        $gaugeColor = $fillPercentage < 20 ? 'danger' : ($fillPercentage < 50 ? 'warning' : 'success');
                                        ?>
                                        <div class="fuel-gauge mini">
                                            <div class="gauge-background">
                                                <div class="gauge-fill gauge-<?php echo $gaugeColor; ?>" style="width: <?php echo $fillPercentage; ?>%"></div>
                                            </div>
                                        </div>
                                        <div class="tank-mini-percentage">
                                            <?php echo number_format($fillPercentage, 0); ?>%
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state mini">
                                    <div class="empty-icon">🏭</div>
                                    <p>Нет данных о резервуарах</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3>📥 Недавние приёмки</h3>
                            <a href="fuel_receipts.php" class="btn-link">Все приёмки →</a>
                        </div>
                        <div class="card-body">
                            <?php if($recentReceipts): ?>
                                <div class="receipts-list">
                                    <?php foreach($recentReceipts as $receipt): ?>
                                    <div class="receipt-item">
                                        <div class="receipt-icon">
                                            <?php 
                                            $fuelIcons = [
                                                'diesel' => '⛽',
                                                'petrol' => '🔥',
                                                'gas' => '💨',
                                                'electric' => '⚡'
                                            ];
                                            echo $fuelIcons[$receipt['fuel_type']];
                                            ?>
                                        </div>
                                        <div class="receipt-content">
                                            <div class="receipt-main">
                                                <span class="receipt-tank"><?php echo $receipt['tank_name']; ?></span>
                                                <span class="receipt-amount success">+<?php echo $receipt['fuel_amount']; ?> л</span>
                                            </div>
                                            <div class="receipt-details">
                                                <span class="receipt-supplier"><?php echo $receipt['supplier']; ?></span>
                                                <span class="receipt-date"><?php echo date('d.m', strtotime($receipt['receipt_date'])); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state mini">
                                    <div class="empty-icon">📥</div>
                                    <p>Нет данных о приёмках</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3>⚠️ Требуют внимания</h3>
                        </div>
                        <div class="card-body">
                            <div class="alerts-list">
                                <?php if($lowFuelTanks): ?>
                                    <?php foreach($lowFuelTanks as $tank): ?>
                                    <div class="alert-item warning">
                                        <div class="alert-icon">⚠️</div>
                                        <div class="alert-content">
                                            <div class="alert-title">Низкий уровень топлива</div>
                                            <div class="alert-details"><?php echo $tank['name']; ?> - <?php echo number_format($tank['fill_percentage'], 0); ?>%</div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                                
                                <?php if($maintenanceVehicles): ?>
                                    <div class="alert-item info">
                                        <div class="alert-icon">🔧</div>
                                        <div class="alert-content">
                                            <div class="alert-title">Техника на обслуживании</div>
                                            <div class="alert-details"><?php echo count($maintenanceVehicles); ?> единиц</div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if(!$lowFuelTanks && !$maintenanceVehicles): ?>
                                    <div class="success-state mini">
                                        <div class="success-icon">✅</div>
                                        <p>Все системы в норме</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>