<?php
session_start();
include 'conexao.php';

$mes = $_GET['mes'] ?? date('m');
$ano = $_GET['ano'] ?? date('Y');
$data_inicio = "$ano-$mes-01";
$data_fim = date("Y-m-t", strtotime($data_inicio));

// SALDO ANTERIOR
$saldo_anterior = 0;

$receitas_anteriores = $conn->query("SELECT SUM(valor) AS total FROM receitas WHERE data < '$data_inicio'")->fetch_assoc()['total'] ?? 0;
$despesas_anteriores = $conn->query("SELECT SUM(valor) AS total FROM despesas WHERE data < '$data_inicio'")->fetch_assoc()['total'] ?? 0;

$saldo_anterior = $receitas_anteriores - $despesas_anteriores;

// RECEITAS DO MÊS
$receitas = $conn->query("SELECT categoria, SUM(valor) AS total FROM receitas WHERE data BETWEEN '$data_inicio' AND '$data_fim' GROUP BY categoria");

// DESPESAS DO MÊS
$despesas = $conn->query("SELECT categoria, SUM(valor) AS total FROM despesas WHERE data BETWEEN '$data_inicio' AND '$data_fim' GROUP BY categoria");

// TOTALIZAÇÃO
$total_receitas = $conn->query("SELECT SUM(valor) AS total FROM receitas WHERE data BETWEEN '$data_inicio' AND '$data_fim'")->fetch_assoc()['total'] ?? 0;
$total_despesas = $conn->query("SELECT SUM(valor) AS total FROM despesas WHERE data BETWEEN '$data_inicio' AND '$data_fim'")->fetch_assoc()['total'] ?? 0;

$saldo_final = $saldo_anterior + $total_receitas - $total_despesas;
?>

<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Relatório Mensal</title>
    <style>
        body { margin: 0; font-family: Arial, sans-serif; }
        .barra-superior {
            background-color: #007bff;
            padding: 15px;
            color: white;
            position: fixed;
            top: 0;
            left: 220px;
            right: 0;
        }
        .barra-lateral {
            width: 220px;
            height: 100vh;
            background-color: #1a1a1a;
            color: white;
            position: fixed;
            top: 0;
            left: 0;
            padding-top: 60px;
        }
        .barra-lateral a {
            display: block;
            padding: 15px;
            color: white;
            text-decoration: none;
            border-bottom: 1px solid #333;
        }
        .barra-lateral a:hover {
            background-color: #007bff;
        }
        .conteudo {
            margin-left: 240px;
            margin-top: 80px;
            padding: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #ccc;
            padding: 8px;
        }
        th {
            background: #f1f1f1;
        }
        .filtros {
            background: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        select, button {
            padding: 6px;
            margin-right: 10px;
        }
        h3 {
            margin-top: 30px;
        }
    </style>
</head>
<body>

<div class="barra-lateral">
    <a href="painel_financeiro.php">🏠 Início</a>
    <a href="ver_movimentos.php">➕ Movimento</a>
    <a href="registrar_receita.php">💰 Receita</a>
    <a href="registrar_despesa.php">💸 Despesa</a>
    <a href="relatorio_mensal.php">📊 Resumo</a>
</div>

<div class="barra-superior">
    <h2>📊 Relatório Mensal</h2>
</div>

<div class="conteudo">
    <form method="GET" class="filtros">
        <label>Mês:</label>
        <select name="mes">
            <?php
            for ($m = 1; $m <= 12; $m++) {
                $value = str_pad($m, 2, "0", STR_PAD_LEFT);
                $selected = ($value == $mes) ? "selected" : "";
                echo "<option value='$value' $selected>$value</option>";
            }
            ?>
        </select>

        <label>Ano:</label>
        <select name="ano">
            <?php
            for ($a = date('Y') - 5; $a <= date('Y') + 1; $a++) {
                $selected = ($a == $ano) ? "selected" : "";
                echo "<option value='$a' $selected>$a</option>";
            }
            ?>
        </select>

        <button type="submit">🔍 Ver Relatório</button>
    </form>

    <h3>🧾 RESUMO DE CONTAS – <?= strtoupper(date('F', strtotime($data_inicio))) ?> / <?= $ano ?></h3>

    <p><strong>Saldo de Caixa Anterior:</strong> <?= number_format($saldo_anterior, 2, ',', '.') ?> Kz</p>

    <table>
        <thead>
            <tr>
                <th colspan="2">RECEITAS</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($r = $receitas->fetch_assoc()): ?>
                <tr>
                    <td><?= $r['categoria'] ?></td>
                    <td><?= number_format($r['total'], 2, ',', '.') ?> Kz</td>
                </tr>
            <?php endwhile; ?>
            <tr style="background: #e6ffe6;">
                <th>Total de Receitas</th>
                <th><?= number_format($total_receitas, 2, ',', '.') ?> Kz</th>
            </tr>
        </tbody>
    </table>

    <table>
        <thead>
            <tr>
                <th colspan="2">DESPESAS</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($d = $despesas->fetch_assoc()): ?>
                <tr>
                    <td><?= $d['categoria'] ?></td>
                    <td><?= number_format($d['total'], 2, ',', '.') ?> Kz</td>
                </tr>
            <?php endwhile; ?>
            <tr style="background: #ffe6e6;">
                <th>Total de Despesas</th>
                <th><?= number_format($total_despesas, 2, ',', '.') ?> Kz</th>
            </tr>
        </tbody>
    </table>

    <p><strong>Saldo Final do Mês:</strong> <?= number_format($saldo_final, 2, ',', '.') ?> Kz</p>
</div>

</body>
</html>
