<?php
declare(strict_types=1);

namespace App\Controllers;

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

class DashboardController extends Controller
{
    public function index(): 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));
        $totMes = DB::pdo()->prepare("SELECT COUNT(*) AS qtde, COALESCE(SUM(valor),0) AS total FROM notas WHERE tenant_id = ? AND data_emissao BETWEEN ? AND ?");
        $totMes->execute([$tenantId, $inicio, $fim]);
        $resMes = $totMes->fetch() ?: ['qtde' => 0, 'total' => 0];
        $empresaCnpjStmt = DB::pdo()->prepare("SELECT cnpj FROM tenants WHERE id = ?");
        $empresaCnpjStmt->execute([$tenantId]);
        $empresaCnpj = preg_replace('/\D+/', '', (string)($empresaCnpjStmt->fetch()['cnpj'] ?? ''));
        $entradasStmt = DB::pdo()->prepare("SELECT COUNT(*) AS qtde FROM notas WHERE tenant_id = ? AND data_emissao BETWEEN ? AND ? AND emitente_cnpj <> ?");
        $entradasStmt->execute([$tenantId, $inicio, $fim, $empresaCnpj]);
        $entradas = (int)($entradasStmt->fetch()['qtde'] ?? 0);
        $saidasStmt = DB::pdo()->prepare("SELECT COUNT(*) AS qtde FROM notas WHERE tenant_id = ? AND data_emissao BETWEEN ? AND ? AND emitente_cnpj = ?");
        $saidasStmt->execute([$tenantId, $inicio, $fim, $empresaCnpj]);
        $saidas = (int)($saidasStmt->fetch()['qtde'] ?? 0);
        $lastConsulta = DB::pdo()->prepare("SELECT created_at, status_code FROM sefaz_logs WHERE tenant_id = ? AND operation = 'distribuicao' ORDER BY id DESC LIMIT 1");
        $lastConsulta->execute([$tenantId]);
        $ultima = $lastConsulta->fetch() ?: null;
        $naoManifestadas = DB::pdo()->prepare("SELECT COUNT(*) AS qtde FROM xml_notas WHERE empresa_id = ? AND manifestado = 'nao'");
        try {
            $naoManifestadas->execute([$tenantId]);
        } catch (\Throwable $e) {
            $naoManifestadas = DB::pdo()->prepare("SELECT COUNT(*) AS qtde FROM notas n LEFT JOIN tenants t ON t.id = n.tenant_id LEFT JOIN manifestacoes m ON m.tenant_id = n.tenant_id AND m.chave = n.chave_acesso WHERE n.tenant_id = ? AND m.status IS NULL");
            $naoManifestadas->execute([$tenantId]);
        }
        $alertas = (int)($naoManifestadas->fetch()['qtde'] ?? 0);
        $payInfo = DB::pdo()->prepare("SELECT t.status AS empresa_status, p.name AS plano, p.limit_notas FROM tenants t LEFT JOIN plans p ON p.id = t.plan_id WHERE t.id = ?");
        $payInfo->execute([$tenantId]);
        $plano = $payInfo->fetch() ?: null;
        $this->view('dashboard/index', [
            'mes' => $mes,
            'resMes' => $resMes,
            'entradas' => $entradas,
            'saidas' => $saidas,
            'ultima' => $ultima,
            'alertas' => $alertas,
            'plano' => $plano,
        ]);
    }
}
