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

$reportData = [];
$chartData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reportType = $_POST['report_type'];
    $month = $_POST['month'] ?? date('Y-m');
    $vehicleId = $_POST['vehicle_id'] ?? '';
    
    switch ($reportType) {
        case 'monthly':
            $stmt = $pdo->prepare("
                SELECT 
                    v.name as vehicle_name,
                    COUNT(r.id) as refuel_count,
                    SUM(r.fuel_amount) as total_fuel,
                    SUM(r.cost) as total_cost,
                    AVG(r.fuel_amount) as avg_fuel
                FROM refuels r
                LEFT JOIN vehicles v ON r.vehicle_id = v.id
                WHERE DATE_FORMAT(r.refuel_date, '%Y-%m') = ?
                GROUP BY r.vehicle_id
                ORDER BY total_fuel DESC
            ");
            $stmt->execute([$month]);
            $reportData = $stmt->fetchAll();
            
            // Данные для графика
            $chartStmt = $pdo->prepare("
                SELECT 
                    v.name,
                    SUM(r.fuel_amount) as fuel
                FROM refuels r
                LEFT JOIN vehicles v ON r.vehicle_id = v.id
                WHERE DATE_FORMAT(r.refuel_date, '%Y-%m') = ?
                GROUP BY r.vehicle_id
                ORDER BY fuel DESC
                LIMIT 10
            ");
            $chartStmt->execute([$month]);
            $chartData = $chartStmt->fetchAll();
            break;
            
        case 'vehicle':
            if ($vehicleId) {
                $stmt = $pdo->prepare("
                    SELECT 
                        DATE_FORMAT(r.refuel_date, '%Y-%m') as month,
                        COUNT(r.id) as refuel_count,
                        SUM(r.fuel_amount) as total_fuel,
                        SUM(r.cost) as total_cost,
                        AVG(r.fuel_amount) as avg_fuel
                    FROM refuels r
                    WHERE r.vehicle_id = ?
                    GROUP BY DATE_FORMAT(r.refuel_date, '%Y-%m')
                    ORDER BY month DESC
                ");
                $stmt->execute([$vehicleId]);
                $reportData = $stmt->fetchAll();
            }
            break;
            
        case 'custom':
            $dateFrom = $_POST['date_from'];
            $dateTo = $_POST['date_to'];
            
            $stmt = $pdo->prepare("
                SELECT 
                    v.name as vehicle_name,
                    COUNT(r.id) as refuel_count,
                    SUM(r.fuel_amount) as total_fuel,
                    SUM(r.cost) as total_cost,
                    AVG(r.fuel_amount) as avg_fuel
                FROM refuels r
                LEFT JOIN vehicles v ON r.vehicle_id = v.id
                WHERE DATE(r.refuel_date) BETWEEN ? AND ?
                GROUP BY r.vehicle_id
                ORDER BY total_fuel DESC
            ");
            $stmt->execute([$dateFrom, $dateTo]);
            $reportData = $stmt->fetchAll();
            break;
    }
}

$vehicles = $pdo->query("SELECT id, name FROM vehicles 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="dashboard">
        <?php include 'sidebar.php'; ?>
        
        <main class="content">
            <header class="content-header">
                <h1>📈 Отчеты по топливу</h1>
            </header>
            
            <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="report_type" id="reportType" required>
                                        <option value="monthly" <?php echo ($_POST['report_type'] ?? '') == 'monthly' ? 'selected' : ''; ?>>📅 Ежемесячный отчет</option>
                                        <option value="vehicle" <?php echo ($_POST['report_type'] ?? '') == 'vehicle' ? 'selected' : ''; ?>>🚜 Отчет по технике</option>
                                        <option value="custom" <?php echo ($_POST['report_type'] ?? '') == 'custom' ? 'selected' : ''; ?>>📋 Произвольный период</option>
                                    </select>
                                </div>
                                
                                <div class="form-group" id="monthField" style="display: <?php echo ($_POST['report_type'] ?? 'monthly') == 'monthly' ? 'block' : 'none'; ?>">
                                    <label>📅 Месяц</label>
                                    <input type="month" name="month" value="<?php echo $_POST['month'] ?? date('Y-m'); ?>">
                                </div>
                                
                                <div class="form-group" id="vehicleField" style="display: <?php echo ($_POST['report_type'] ?? '') == 'vehicle' ? 'block' : 'none'; ?>">
                                    <label>🚜 Техника</label>
                                    <select name="vehicle_id">
                                        <option value="">Выберите технику</option>
                                        <?php foreach($vehicles as $vehicle): ?>
                                            <option value="<?php echo $vehicle['id']; ?>" <?php echo ($_POST['vehicle_id'] ?? '') == $vehicle['id'] ? 'selected' : ''; ?>>
                                                <?php echo $vehicle['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="form-row" id="customFields" style="display: <?php echo ($_POST['report_type'] ?? '') == 'custom' ? 'flex' : 'none'; ?>">
                                    <div class="form-group">
                                        <label>📅 Дата с</label>
                                        <input type="date" name="date_from" value="<?php echo $_POST['date_from'] ?? date('Y-m-01'); ?>">
                                    </div>
                                    <div class="form-group">
                                        <label>📅 Дата по</label>
                                        <input type="date" name="date_to" value="<?php echo $_POST['date_to'] ?? date('Y-m-d'); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="submit" class="btn btn-primary">📊 Сформировать отчет</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if(!empty($reportData)): ?>
                <div class="card">
                    <div class="card-header">
                        <h3>📋 Результаты отчета</h3>
                        <button onclick="window.print()" class="btn btn-secondary">🖨️ Печать</button>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table>
                                <thead>
                                    <tr>
                                        <?php if($_POST['report_type'] == 'monthly' || $_POST['report_type'] == 'custom'): ?>
                                            <th>Техника</th>
                                        <?php elseif($_POST['report_type'] == 'vehicle'): ?>
                                            <th>Месяц</th>
                                        <?php endif; ?>
                                        <th>Кол-во заправок</th>
                                        <th>Всего топлива (л)</th>
                                        <th>Средний расход (л)</th>
                                        <th>Общая стоимость</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($reportData as $row): ?>
                                    <tr>
                                        <?php if($_POST['report_type'] == 'monthly' || $_POST['report_type'] == 'custom'): ?>
                                            <td><?php echo $row['vehicle_name']; ?></td>
                                        <?php elseif($_POST['report_type'] == 'vehicle'): ?>
                                            <td><?php echo $row['month']; ?></td>
                                        <?php endif; ?>
                                        <td><?php echo $row['refuel_count']; ?></td>
                                        <td><?php echo number_format($row['total_fuel'], 2); ?> л</td>
                                        <td><?php echo number_format($row['avg_fuel'], 2); ?> л</td>
                                        <td><?php echo $row['total_cost'] ? number_format($row['total_cost'], 2) . ' руб.' : '-'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <?php if(!empty($chartData) && $_POST['report_type'] == 'monthly'): ?>
                        <div class="chart-container">
                            <canvas id="fuelChart" width="400" height="200"></canvas>
                        </div>
                        <script>
                            const ctx = document.getElementById('fuelChart').getContext('2d');
                            const fuelChart = new Chart(ctx, {
                                type: 'bar',
                                data: {
                                    labels: [<?php echo implode(',', array_map(function($item) { return "'" . $item['name'] . "'"; }, $chartData)); ?>],
                                    datasets: [{
                                        label: 'Расход топлива (л)',
                                        data: [<?php echo implode(',', array_column($chartData, 'fuel')); ?>],
                                        backgroundColor: [
                                            '#2ecc71', '#3498db', '#9b59b6', '#f1c40f', 
                                            '#e67e22', '#e74c3c', '#1abc9c', '#34495e',
                                            '#d35400', '#c0392b'
                                        ],
                                        borderWidth: 1
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    plugins: {
                                        title: {
                                            display: true,
                                            text: 'Топ-10 техники по расходу топлива'
                                        }
                                    },
                                    scales: {
                                        y: {
                                            beginAtZero: true,
                                            title: {
                                                display: true,
                                                text: 'Литры'
                                            }
                                        }
                                    }
                                }
                            });
                        </script>
                        <?php endif; ?>
                    </div>
                </div>
                <?php elseif($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
                <div class="card">
                    <div class="card-body">
                        <p class="no-data">😴 Нет данных для отчета</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
    
    <script src="js/script.js"></script>
    <script>
        document.getElementById('reportType').addEventListener('change', function() {
            const type = this.value;
            document.getElementById('monthField').style.display = type === 'monthly' ? 'block' : 'none';
            document.getElementById('vehicleField').style.display = type === 'vehicle' ? 'block' : 'none';
            document.getElementById('customFields').style.display = type === 'custom' ? 'flex' : 'none';
        });
    </script>
</body>
</html>