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

// Mês e Ano atual por padrão
$mes = $_GET['mes'] ?? date('m');
$ano = $_GET['ano'] ?? date('Y');
$data_inicio = "$ano-$mes-01";
$data_fim = date("Y-m-t", strtotime($data_inicio));

// Nome do mês em português
setlocale(LC_TIME, 'pt_PT.UTF-8', 'pt_PT', 'Portuguese_Portugal');
$nome_mes = ucfirst(strftime('%B', mktime(0, 0, 0, $mes, 10)));

// Inicializar arrays de receitas e despesas
$receitas = [];
$despesas = [];
$total_receitas = 0;
$total_despesas = 0;

// Consulta otimizada para buscar apenas subcategorias com movimentos no período
$sql_movimentos = $conn->prepare("
    SELECT TRIM(m.subcategoria) AS subcategoria_nome, m.tipo, SUM(m.valor) AS total_valor
    FROM movimentos_diarios m
    WHERE m.data BETWEEN ? AND ?
    GROUP BY m.subcategoria, m.tipo
    HAVING SUM(m.valor) > 0
");
$sql_movimentos->bind_param("ss", $data_inicio, $data_fim);
$sql_movimentos->execute();
$movimentos = $sql_movimentos->get_result()->fetch_all(MYSQLI_ASSOC);
$sql_movimentos->close();

foreach ($movimentos as $movimento) {
    $sub_nome = $movimento['subcategoria_nome'];
    $tipo = $movimento['tipo'];
    $valor = $movimento['total_valor'];

    if ($tipo === 'Entrada') {
        $receitas[$sub_nome] = $valor;
        $total_receitas += $valor;
    } elseif ($tipo === 'Saída') {
        $despesas[$sub_nome] = $valor;
        $total_despesas += $valor;
    }
}

$saldo_final = $total_receitas - $total_despesas;
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Resumo Geral</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #007bff;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--light-color);
            color: var(--dark-color);
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background-color: #fff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header h2, .header h3, .header h4 {
            margin: 0;
            padding: 5px 0;
        }
        .header h2 {
            font-size: 24px;
            color: var(--primary-color);
        }
        .header h3 {
            font-size: 18px;
            color: var(--secondary-color);
        }
        .filter-form {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        .filter-form label {
            font-weight: 600;
        }
        .filter-form input, .filter-form button {
            padding: 8px 12px;
            border-radius: 6px;
            border: 1px solid #ccc;
            font-family: inherit;
        }
        .filter-form button {
            background-color: var(--primary-color);
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .filter-form button:hover {
            background-color: #0056b3;
        }
        .print-btn-container {
            text-align: right;
            margin-bottom: 20px;
        }
        .print-btn {
            padding: 10px 20px;
            font-size: 16px;
            background-color: var(--success-color);
            color: #fff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .print-btn:hover {
            background-color: #218838;
        }
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 20px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }
        th {
            background-color: var(--dark-color);
            color: #fff;
            font-weight: 600;
        }
        tbody tr:last-child td {
            border-bottom: none;
        }
        .total-row {
            font-weight: 600;
            background-color: #e9ecef;
        }
        .total-row td {
            border-top: 2px solid var(--dark-color);
        }
        .total-receitas-valor {
            color: var(--success-color);
        }
        .total-despesas-valor {
            color: var(--danger-color);
        }
        .saldo-final-valor {
            font-size: 1.2em;
            color: #000;
        }
        .assinatura-area {
            margin-top: 50px;
            text-align: center;
        }
        .assinatura-area p {
            margin: 0;
        }
        .assinatura-line {
            display: inline-block;
            width: 250px;
            border-top: 1px solid #000;
            margin: 10px 0;
        }
        .section-title {
            background-color: #f1f1f1;
            font-weight: bold;
            padding: 8px 15px;
            border-bottom: 1px solid #dee2e6;
        }
        /* Estilos do cabeçalho institucional */
        .institutional-header {
            text-align: center;
            margin-bottom: 20px;
            font-size: 14px;
            line-height: 1.2;
        }
        .institutional-header img {
            width: 80px;
            margin-bottom: 10px;
        }
        .institutional-header h3, .institutional-header p {
            margin: 0;
        }
        .institutional-header h3 {
            font-weight: 600;
        }
        @media print {
            body { background-color: #fff; padding: 0; }
            .container { box-shadow: none; border-radius: 0; padding: 0; }
            .filter-form, .print-btn-container { display: none; }
            table { border: 1px solid #000; }
            th, td { border: 1px solid #000; }
            .total-row td { border-top: 1px solid #000; }
            .header h2, .header h3, .header h4 { color: #000; }
            .section-title {
                background-color: #e9ecef;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .total-receitas-valor, .total-despesas-valor, .saldo-final-valor {
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .institutional-header { display: block !important; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="institutional-header">
        <img src="insignia/insignia.png" alt="Insígnia" />
        <h3>REPÚBLICA DE ANGOLA</h3>
        <p>Governo Provincial de Benguela</p>
        <p>Gabinete Provincial da Educação</p>
        <h3>COMPLEXO ESCOLAR BG0026 PADRE EMIL FRICK - CATUMBELA</h3>
    </div>

    <div class="header">
        <h2>RESUMO DE CONTAS</h2>
        <h3>Mês: <?= $nome_mes ?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Ano: <?= $ano ?></h3>
    </div>

    <div class="filter-form">
        <form method="GET">
            <label>Mês: <input type="number" name="mes" value="<?= $mes ?>" min="1" max="12"></label>
            <label>Ano: <input type="number" name="ano" value="<?= $ano ?>"></label>
            <button type="submit">Ver</button>
        </form>
    </div>

    <div class="print-btn-container">
        <button class="print-btn" onclick="window.print()">🖨️ Imprimir</button>
    </div>

    <table>
        <thead>
            <tr>
                <th>DESIGNAÇÃO</th>
                <th>MOVIMENTO MENSAL</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="section-title" colspan="2">1 - Receitas</td>
            </tr>
            <?php foreach ($receitas as $sub => $valor): ?>
                <tr>
                    <td><?= htmlspecialchars($sub) ?></td>
                    <td><?= number_format($valor, 2, ',', '.') ?></td>
                </tr>
            <?php endforeach; ?>
            <tr class="total-row">
                <td><strong>1. TOTAL DAS RECEITAS - R</strong></td>
                <td class="total-receitas-valor"><strong><?= number_format($total_receitas, 2, ',', '.') ?></strong></td>
            </tr>

            <tr>
                <td class="section-title" colspan="2">2 - Despesas</td>
            </tr>
            <?php foreach ($despesas as $sub => $valor): ?>
                <tr>
                    <td><?= htmlspecialchars($sub) ?></td>
                    <td><?= number_format($valor, 2, ',', '.') ?></td>
                </tr>
            <?php endforeach; ?>
            <tr class="total-row">
                <td><strong>2. TOTAL DAS DESPESAS - D</strong></td>
                <td class="total-despesas-valor"><strong><?= number_format($total_despesas, 2, ',', '.') ?></strong></td>
            </tr>

            <tr class="total-row">
                <td><strong>3 - Saldo Administrativo (SA + R - D)</strong></td>
                <td class="saldo-final-valor"><strong><?= number_format($saldo_final, 2, ',', '.') ?></strong></td>
            </tr>
        </tbody>
    </table>

    <div class="assinatura-area">
        <p>O Subdirector Administrativo</p>
        <span class="assinatura-line"></span>
        <p>Data: _____/<?= $mes ?>/<?= $ano ?></p>
    </div>
</div>

</body>
</html>