<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;

class NotasController extends Controller
{
    public function painel(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        if (!$tenantId) {
            header('Location: /login');
            return;
        }
        $mes = $_GET['mes'] ?? date('Y-m');
        $inicio = $mes . '-01 00:00:00';
        $fim = date('Y-m-t 23:59:59', strtotime($inicio));
        $stmt = DB::pdo()->prepare("SELECT * FROM notas WHERE tenant_id = ? AND data_emissao BETWEEN ? AND ? ORDER BY data_emissao DESC");
        $stmt->execute([$tenantId, $inicio, $fim]);
        $notas = $stmt->fetchAll();
        $totais = DB::pdo()->prepare("SELECT COUNT(*) AS qtde, COALESCE(SUM(valor),0) AS total FROM notas WHERE tenant_id = ? AND data_emissao BETWEEN ? AND ?");
        $totais->execute([$tenantId, $inicio, $fim]);
        $resumo = $totais->fetch() ?: ['qtde' => 0, 'total' => 0];
        $mesesStmt = DB::pdo()->prepare("SELECT DISTINCT DATE_FORMAT(data_emissao, '%Y-%m') AS m FROM notas WHERE tenant_id = ? ORDER BY m DESC");
        try {
            $mesesStmt->execute([$tenantId]);
        } catch (\Throwable $e) {
            $mesesStmt = DB::pdo()->prepare("SELECT DISTINCT strftime('%Y-%m', data_emissao) AS m FROM notas WHERE tenant_id = ? ORDER BY m DESC");
            $mesesStmt->execute([$tenantId]);
        }
        $meses = $mesesStmt->fetchAll();
        $this->view('notas/painel', [
            'notas' => $notas,
            'resumo' => $resumo,
            'mesAtual' => $mes,
            'meses' => $meses,
        ]);
    }

    public function verXml(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $id = (int)($_GET['id'] ?? 0);
        $stmt = DB::pdo()->prepare("SELECT caminho_xml FROM notas WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $tenantId]);
        $nota = $stmt->fetch();
        if (!$nota || empty($nota['caminho_xml']) || !is_file($nota['caminho_xml'])) {
            http_response_code(404);
            echo 'XML não encontrado';
            return;
        }
        header('Content-Type: text/html; charset=utf-8');
        echo '<!doctype html><html><head><meta charset="utf-8"><title>XML NF-e</title></head><body><pre>';
        echo htmlspecialchars(file_get_contents($nota['caminho_xml']), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        echo '</pre></body></html>';
    }

    public function downloadXml(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $id = (int)($_GET['id'] ?? 0);
        $stmt = DB::pdo()->prepare("SELECT chave_acesso, caminho_xml FROM notas WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $tenantId]);
        $nota = $stmt->fetch();
        if (!$nota || empty($nota['caminho_xml']) || !is_file($nota['caminho_xml'])) {
            http_response_code(404);
            echo 'XML não encontrado';
            return;
        }
        $nome = $nota['chave_acesso'] ?: ('nfe_' . $id);
        header('Content-Type: application/xml');
        header('Content-Disposition: attachment; filename="' . $nome . '.xml"');
        readfile($nota['caminho_xml']);
    }
}
