<?php
// O arquivo conexao.php deve conter a conexão com o banco de dados.
require 'conexao.php';

// Locale para mês em português
setlocale(LC_TIME, 'pt_PT.UTF-8', 'pt_PT', 'pt_BR.UTF-8', 'portuguese');

// Define o mês e ano atual
$mesAtual = date('m');
$anoAtual = date('Y');

// Mês por extenso (capitalizado)
$dataReferencia = "$anoAtual-$mesAtual-01";
$mes_extenso = ucfirst(strftime('%B', strtotime($dataReferencia)));

// Busca dados do mês atual
$movimentos = $conn->query("SELECT tipo, SUM(valor) as total FROM movimentos_diarios 
                            WHERE MONTH(data) = $mesAtual AND YEAR(data) = $anoAtual
                            GROUP BY tipo");

$receitas = 0;
$despesas = 0;

while ($m = $movimentos->fetch_assoc()) {
    if (strtolower($m['tipo']) == 'entrada') {
        $receitas += $m['total'];
    } else {
        $despesas += $m['total'];
    }
}

// Busca saldo anterior
$saldoAnteriorQuery = $conn->query("SELECT SUM(CASE WHEN LOWER(tipo) = 'entrada' THEN valor ELSE -valor END) as saldo
                                     FROM movimentos_diarios 
                                     WHERE (MONTH(data) < $mesAtual AND YEAR(data) = $anoAtual)
                                        OR (YEAR(data) < $anoAtual)");
$saldoAnterior = $saldoAnteriorQuery->fetch_assoc()['saldo'] ?? 0;

$saldoAtual = $saldoAnterior + $receitas - $despesas;
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relatório Financeiro</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;
            --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: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        .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;
        }
        .report-title {
            text-align: center;
            margin: 20px 0;
        }
        .report-title h2 {
            font-size: 20px;
            color: var(--primary-color);
            margin: 0;
        }
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
            margin-top: 20px;
        }
        th, td {
            border-bottom: 1px solid #dee2e6;
            padding: 12px 15px;
            text-align: left;
        }
        th {
            background-color: var(--dark-color);
            color: #fff;
            font-weight: 600;
        }
        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);
        }
        .assinatura {
            margin-top: 50px;
            text-align: center;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }
        .assinatura div {
            flex-basis: 45%; /* Lado a lado em telas maiores */
            margin-bottom: 20px;
        }
        .assinatura div p {
            margin: 0;
            margin-top: 5px;
        }
        .assinatura div:first-child {
            text-align: left;
        }
        .assinatura div:last-child {
            text-align: right;
        }
        .assinatura-line {
            display: block;
            width: 100%;
            border-top: 1px solid #000;
            margin: 10px 0;
        }
        .date-info {
            text-align: right;
            margin-top: 20px;
            width: 100%;
        }
        .print-btn {
            display: block;
            margin: 20px auto;
            padding: 10px 20px;
            font-size: 16px;
            background-color: var(--primary-color);
            color: #fff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .print-btn:hover {
            background-color: #0056b3;
        }
        @media print {
            body { padding: 0; }
            .container {
                border: none;
                box-shadow: none;
                padding: 0;
            }
            .print-btn {
                display: none;
            }
            .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="report-title">
        <h2>RESUMO FINANCEIRO MENSAL - <?= strtoupper($mes_extenso) ?> de <?= $anoAtual ?></h2>
    </div>

    <table>
        <thead>
            <tr><th colspan="2">RESUMO DE CONTAS</th></tr>
        </thead>
        <tbody>
            <tr>
                <td><strong>Saldo Anterior</strong></td>
                <td><?= number_format($saldoAnterior, 2, ',', '.') ?> KZ</td>
            </tr>
            <tr>
                <td><strong>Total de Receitas</strong></td>
                <td><?= number_format($receitas, 2, ',', '.') ?> KZ</td>
            </tr>
            <tr>
                <td><strong>Total de Despesas</strong></td>
                <td><?= number_format($despesas, 2, ',', '.') ?> KZ</td>
            </tr>
            <tr class="total-row">
                <td><strong>Saldo Atual</strong></td>
                <td><strong><?= number_format($saldoAtual, 2, ',', '.') ?> KZ</strong></td>
            </tr>
        </tbody>
    </table>

    <div class="assinatura">
        <div style="flex-basis: 40%; text-align: center;">
            <p>____________________________</p>
            <p>O(A) GESTOR(A) DA INSTITUIÇÃO</p>
        </div>
        <div style="flex-basis: 40%; text-align: center;">
            <p>____________________________</p>
            <p>O(A) SUBDIRECTOR(A) ADMINISTRATIVO(A)</p>
        </div>
    </div>
    <div class="date-info">
        <p>Catumbela, aos <?= date('d') ?> de <?= $mes_extenso ?> de <?= $anoAtual ?></p>
    </div>
</div>

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

</body>
</html>