<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;
use App\Services\PDFService;

class ReportController extends Controller
{
    public function pdf(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $rows = DB::pdo()->prepare("SELECT chave, emitente, destinatario, valor_total, data_emissao FROM invoices WHERE tenant_id = ? ORDER BY data_emissao DESC LIMIT 100");
        $rows->execute([$tenantId]);
        $list = $rows->fetchAll();
        $lines = [];
        foreach ($list as $r) {
            $lines[] = $r['chave'] . ' | ' . $r['emitente'] . ' | ' . $r['valor_total'];
        }
        $pdf = PDFService::simpleText('Relatório NF-e', $lines);
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="relatorio.pdf"');
        echo $pdf;
    }

    public function csv(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $rows = DB::pdo()->prepare("SELECT chave, emitente, destinatario, valor_total, data_emissao FROM invoices WHERE tenant_id = ? ORDER BY data_emissao DESC");
        $rows->execute([$tenantId]);
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="relatorio.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Chave', 'Emitente', 'Destinatário', 'Valor Total', 'Data Emissão'], ';');
        while ($r = $rows->fetch()) {
            fputcsv($out, [$r['chave'], $r['emitente'], $r['destinatario'], $r['valor_total'], $r['data_emissao']], ';');
        }
        fclose($out);
    }
}
