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

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

$message = '';
if (isset($_GET['delete'])) {
    $tankId = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM fuel_tanks WHERE id = ?")->execute([$tankId]);
    $message = "✅ Резервуар успешно удален!";
}

$tanks = $pdo->query("SELECT * FROM fuel_tanks ORDER BY name")->fetchAll();

// Получаем общую статистику
$totalCapacity = $pdo->query("SELECT SUM(capacity) FROM fuel_tanks")->fetchColumn();
$totalCurrent = $pdo->query("SELECT SUM(current_level) FROM fuel_tanks")->fetchColumn();
$totalPercentage = $totalCapacity > 0 ? ($totalCurrent / $totalCapacity) * 100 : 0;
?>
<!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">
                    <a href="add_fuel_tank.php" class="btn btn-primary">➕ Добавить резервуар</a>
                </div>
            </header>
            
            <?php if($message): ?>
                <div class="alert success"><?php echo $message; ?></div>
            <?php endif; ?>
            
            <!-- Общая статистика -->
            <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 count($tanks); ?></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 number_format($totalCapacity, 0); ?> л</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($totalCurrent, 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 number_format($totalPercentage, 1); ?>%</span>
                    </div>
                </div>
            </div>
            
            <!-- Общий индикатор -->
            <div class="card">
                <div class="card-header">
                    <h3>📊 Общее состояние резервуаров</h3>
                </div>
                <div class="card-body">
                    <div class="overall-gauge">
                        <div class="gauge-background large">
                            <div class="gauge-fill gauge-success" style="width: <?php echo $totalPercentage; ?>%"></div>
                        </div>
                        <div class="gauge-text large">
                            <span>0 л</span>
                            <span><?php echo number_format($totalCurrent, 0); ?> л (<?php echo number_format($totalPercentage, 1); ?>%)</span>
                            <span><?php echo number_format($totalCapacity, 0); ?> л</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Сетка резервуаров -->
            <div class="tanks-grid">
                <?php foreach($tanks as $tank): ?>
                <div class="tank-card">
                    <div class="tank-header">
                        <div class="tank-title">
                            <h3><?php echo $tank['name']; ?></h3>
                            <span class="tank-location">📍 <?php echo $tank['location']; ?></span>
                        </div>
                        <div class="tank-status">
                            <span class="status-badge status-<?php echo $tank['status']; ?>">
                                <?php 
                                $statusIcons = [
                                    'active' => '✅ Активен',
                                    'maintenance' => '🔧 Обслуживание',
                                    'empty' => '⛔ Пустой'
                                ];
                                echo $statusIcons[$tank['status']];
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <div class="tank-content">
                        <div class="tank-fuel-info">
                            <div class="fuel-type">
                                <?php 
                                $fuelTypes = [
                                    'diesel' => '⛽ Дизельное топливо',
                                    'petrol' => '🔥 Бензин',
                                    'gas' => '💨 Сжиженный газ',
                                    'electric' => '⚡ Электричество'
                                ];
                                echo $fuelTypes[$tank['fuel_type']];
                                ?>
                            </div>
                            
                            <div class="tank-capacity-info">
                                <div class="capacity-item">
                                    <span class="label">Вместимость:</span>
                                    <span class="value"><?php echo number_format($tank['capacity'], 0); ?> л</span>
                                </div>
                                <div class="capacity-item">
                                    <span class="label">Текущий уровень:</span>
                                    <span class="value highlight"><?php echo number_format($tank['current_level'], 0); ?> л</span>
                                </div>
                                <div class="capacity-item">
                                    <span class="label">Минимальный уровень:</span>
                                    <span class="value warning"><?php echo number_format($tank['min_level'], 0); ?> л</span>
                                </div>
                                <div class="capacity-item">
                                    <span class="label">Доступно:</span>
                                    <span class="value success"><?php echo number_format($tank['capacity'] - $tank['current_level'], 0); ?> л</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="tank-gauge-section">
                            <?php 
                            $fillPercentage = $tank['capacity'] > 0 ? ($tank['current_level'] / $tank['capacity']) * 100 : 0;
                            $fillPercentage = min(100, $fillPercentage);
                            $gaugeColor = $fillPercentage < 20 ? 'danger' : ($fillPercentage < 50 ? 'warning' : 'success');
                            $isLow = $tank['current_level'] <= $tank['min_level'];
                            ?>
                            <div class="fuel-gauge large">
                                <div class="gauge-background">
                                    <div class="gauge-fill gauge-<?php echo $gaugeColor; ?>" style="width: <?php echo $fillPercentage; ?>%"></div>
                                    <?php if($isLow): ?>
                                        <div class="low-fuel-warning">⚠️</div>
                                    <?php endif; ?>
                                </div>
                                <div class="gauge-text">
                                    <span><?php echo number_format($fillPercentage, 1); ?>%</span>
                                    <span><?php echo number_format($tank['current_level'], 0); ?> / <?php echo number_format($tank['capacity'], 0); ?> л</span>
                                </div>
                            </div>
                            
                            <?php if($isLow): ?>
                                <div class="alert warning">
                                    ⚠️ Низкий уровень топлива! Требуется пополнение.
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if($tank['notes']): ?>
                        <div class="tank-notes">
                            <strong>📝 Примечания:</strong>
                            <p><?php echo $tank['notes']; ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="tank-actions">
                        <a href="add_fuel_tank.php?edit=<?php echo $tank['id']; ?>" class="btn btn-sm btn-warning">✏️ Редактировать</a>
                        <a href="fuel_receipts.php?tank=<?php echo $tank['id']; ?>" class="btn btn-sm btn-primary">⛽ Пополнить</a>
                        <a href="fuel_tanks.php?delete=<?php echo $tank['id']; ?>" 
                           class="btn btn-sm btn-danger" 
                           onclick="return confirm('Удалить резервуар? Все связанные данные будут потеряны!')">🗑️ Удалить</a>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php if(empty($tanks)): ?>
                <div class="empty-state">
                    <div class="empty-icon">🏭</div>
                    <h3>Резервуары не добавлены</h3>
                    <p>Добавьте первый резервуар для хранения топлива</p>
                    <a href="add_fuel_tank.php" class="btn btn-primary">➕ Добавить резервуар</a>
                </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
</body>
</html>