<?php
// frota_relatorio.php — Relatório do Veículo
$pageActive = 'frota';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$usuario = usuarioLogado();
$isAdmin = $usuario['perfil'] === 'ADMIN';

$veiculoId = (int)($_GET['veiculo_id'] ?? 0);
$mes = (int)($_GET['mes'] ?? date('m'));
$ano = (int)($_GET['ano'] ?? date('Y'));

// Buscar veículo
if ($isAdmin) {
    $stmt = pdo()->prepare("SELECT * FROM frota_veiculos WHERE id = ? AND ativo = 1");
    $stmt->execute([$veiculoId]);
} else {
    $stmt = pdo()->prepare("SELECT * FROM frota_veiculos WHERE id = ? AND responsavel_id = ? AND ativo = 1");
    $stmt->execute([$veiculoId, $usuario['id']]);
}
$veiculo = $stmt->fetch();

if (!$veiculo) {
    header('Location: frota.php');
    exit;
}

// Totais do mês
$stmtTot = pdo()->prepare("
    SELECT 
        COUNT(*) AS qtd_abastecimentos,
        SUM(litros) AS total_litros,
        SUM(valor_total) AS total_valor,
        AVG(litros) AS media_litros,
        AVG(valor_total) AS media_valor,
        MIN(km_atual) AS km_inicial,
        MAX(km_atual) AS km_final
    FROM frota_abastecimentos 
    WHERE veiculo_id = ? 
    AND MONTH(data) = ? AND YEAR(data) = ?
");
$stmtTot->execute([$veiculoId, $mes, $ano]);
$totais = $stmtTot->fetch();

// Lista de abastecimentos do mês
$stmtAb = pdo()->prepare("SELECT * FROM frota_abastecimentos WHERE veiculo_id = ? AND MONTH(data) = ? AND YEAR(data) = ? ORDER BY data ASC");
$stmtAb->execute([$veiculoId, $mes, $ano]);
$abastecimentos = $stmtAb->fetchAll();

// Média de km/l
$kmRodados = (int)($totais['km_final'] ?? 0) - (int)($totais['km_inicial'] ?? 0);
$totalLitros = (float)($totais['total_litros'] ?? 0);
$mediaKmL = $totalLitros > 0 ? $kmRodados / $totalLitros : 0;

$pageTitle = 'Relatório - ' . $veiculo['placa'];

$meses = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];

require_once __DIR__ . '/includes/header.php';
?>

<style>
.relatorio-header {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px 20px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}

.relatorio-stats {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;
    margin-bottom: 14px;
}

.relatorio-stat {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px;
    text-align: center;
}

.relatorio-stat-valor {
    font-size: 20px;
    font-weight: 800;
    font-family: var(--mono);
}

.relatorio-stat-label {
    font-size: 9px;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .5px;
    margin-top: 4px;
}

.relatorio-tabela {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.relatorio-tabela th {
    background: var(--card2);
    padding: 10px 12px;
    text-align: left;
    font-size: 9px;
    text-transform: uppercase;
    letter-spacing: .5px;
    color: var(--muted);
    border-bottom: 2px solid var(--border);
}

.relatorio-tabela td {
    padding: 10px 12px;
    border-bottom: 1px solid var(--border);
}

.relatorio-filtro {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
}

.relatorio-filtro select {
    padding: 6px 10px;
    background: var(--card2);
    border: 1px solid var(--border);
    border-radius: 6px;
    color: var(--text);
    font-family: var(--ui);
    font-size: 12px;
}

.relatorio-filtro button {
    padding: 6px 12px;
    background: var(--cyan);
    color: #000;
    border: none;
    border-radius: 6px;
    font-weight: 700;
    cursor: pointer;
    font-size: 11px;
}

@media (max-width: 767px) {
    .relatorio-stats {
        grid-template-columns: 1fr 1fr;
    }
}
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
    <div>
        <div class="page-title"> Relatório</div>
        <div class="page-sub"><?= e($veiculo['placa']) ?> - <?= e($veiculo['modelo'] ?: '—') ?></div>
    </div>
    <div class="topbar-actions">
        <a href="frota.php" class="btn btn-ghost"> Frota</a>
    </div>
</div>

<div class="content">
    <!-- Filtro de mês/ano -->
    <div class="relatorio-header">
        <div>
            <div style="font-size:11px;font-weight:700;color:var(--text);margin-bottom:6px">
                 Período
            </div>
            <div class="relatorio-filtro">
                <select id="filtro-mes" onchange="filtrar()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?= $m ?>" <?= $m == $mes ? 'selected' : '' ?>><?= $meses[$m-1] ?></option>
                    <?php endfor; ?>
                </select>
                <select id="filtro-ano" onchange="filtrar()">
                    <?php for ($a = date('Y'); $a >= 2020; $a--): ?>
                    <option value="<?= $a ?>" <?= $a == $ano ? 'selected' : '' ?>><?= $a ?></option>
                    <?php endfor; ?>
                </select>
            </div>
        </div>
        <div style="text-align:right">
            <div style="font-size:20px;font-weight:800;font-family:var(--mono);color:var(--green)">
                R$ <?= number_format((float)($totais['total_valor'] ?? 0), 2, ',', '.') ?>
            </div>
            <div style="font-size:9px;color:var(--muted)">Total no período</div>
        </div>
    </div>

    <!-- Estatísticas -->
    <div class="relatorio-stats">
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--cyan)"><?= (int)($totais['qtd_abastecimentos'] ?? 0) ?></div>
            <div class="relatorio-stat-label">Abastecimentos</div>
        </div>
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--green)"><?= number_format($totalLitros, 1, ',', '.') ?> L</div>
            <div class="relatorio-stat-label">Total Litros</div>
        </div>
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--amber)"><?= number_format($mediaKmL, 1, ',', '.') ?></div>
            <div class="relatorio-stat-label">Média KM/L</div>
        </div>
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--purple)"><?= number_format($kmRodados, 0, ',', '.') ?></div>
            <div class="relatorio-stat-label">KM Rodados</div>
        </div>
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--pink)">R$ <?= number_format((float)($totais['media_valor'] ?? 0), 2, ',', '.') ?></div>
            <div class="relatorio-stat-label">Média R$/Abast.</div>
        </div>
        <div class="relatorio-stat">
            <div class="relatorio-stat-valor" style="color:var(--cyan)">R$ <?= number_format($totalLitros > 0 ? (float)($totais['total_valor'] ?? 0) / $totalLitros : 0, 2, ',', '.') ?></div>
            <div class="relatorio-stat-label">Preço Médio/L</div>
        </div>
    </div>

    <!-- Tabela de abastecimentos -->
    <?php if (empty($abastecimentos)): ?>
    <div style="text-align:center;padding:40px;color:var(--muted);background:var(--card);border-radius:var(--radius);border:1px solid var(--border)">
        <div style="font-size:36px;margin-bottom:8px"></div>
        <div style="font-size:13px">Nenhum abastecimento neste período</div>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;background:var(--card);border-radius:var(--radius);border:1px solid var(--border)">
        <table class="relatorio-tabela">
            <thead>
                <tr>
                    <th>Data</th>
                    <th>KM</th>
                    <th>Litros</th>
                    <th>Valor</th>
                    <th>R$/L</th>
                    <th>Obs</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $kmAnterior = null;
                foreach ($abastecimentos as $a): 
                    $precoLitro = (float)$a['litros'] > 0 ? (float)$a['valor_total'] / (float)$a['litros'] : 0;
                    $kmDif = $kmAnterior !== null ? (int)$a['km_atual'] - $kmAnterior : null;
                    $kmAnterior = (int)$a['km_atual'];
                ?>
                <tr>
                    <td><b><?= date('d/m', strtotime($a['data'])) ?></b></td>
                    <td style="font-family:var(--mono)">
                        <?= number_format((int)$a['km_atual'], 0, ',', '.') ?>
                        <?php if ($kmDif !== null): ?>
                        <span style="font-size:9px;color:var(--muted)">(+<?= $kmDif ?>)</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-family:var(--mono)"><?= number_format((float)$a['litros'], 1, ',', '.') ?> L</td>
                    <td style="font-family:var(--mono);color:var(--green);font-weight:700">R$ <?= number_format((float)$a['valor_total'], 2, ',', '.') ?></td>
                    <td style="font-family:var(--mono)">R$ <?= number_format($precoLitro, 2, ',', '.') ?></td>
                    <td style="font-size:10px;color:var(--muted);max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                        <?= e($a['observacoes'] ?: '—') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
function filtrar() {
    const mes = document.getElementById('filtro-mes').value;
    const ano = document.getElementById('filtro-ano').value;
    window.location.href = 'frota_relatorio.php?veiculo_id=<?= $veiculoId ?>&mes=' + mes + '&ano=' + ano;
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>