<?php
declare(strict_types=1);

namespace App\Controllers;

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

class SefazController extends Controller
{
    public function teste(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $stmt = DB::pdo()->prepare("SELECT cnpj FROM tenants WHERE id = ?");
        $stmt->execute([$tenantId]);
        $tenant = $stmt->fetch();
        $cnpj = $tenant['cnpj'] ?? '';
        $resultado = NFePhpService::testarAcesso($tenantId);
        $this->view('sefaz/teste', [
            'cnpj' => $cnpj,
            'resultado' => $resultado,
        ]);
    }

    public function consultar(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $stmt = DB::pdo()->prepare("SELECT cnpj, nsu FROM tenants WHERE id = ?");
        $stmt->execute([$tenantId]);
        $tenant = $stmt->fetch();
        $cnpj = $tenant['cnpj'] ?? '';
        $nsu = $tenant['nsu'] ?? '000000';
        $beforeStmt = DB::pdo()->prepare("SELECT COUNT(*) AS c FROM notas WHERE tenant_id = ?");
        $beforeStmt->execute([$tenantId]);
        $before = (int)($beforeStmt->fetch()['c'] ?? 0);
        NFePhpService::baixarNotasDestinadas($tenantId);
        $afterStmt = DB::pdo()->prepare("SELECT COUNT(*) AS c FROM notas WHERE tenant_id = ?");
        $afterStmt->execute([$tenantId]);
        $after = (int)($afterStmt->fetch()['c'] ?? 0);
        $downloaded = max(0, $after - $before);
        $logStmt = DB::pdo()->prepare("SELECT status_code, created_at FROM sefaz_logs WHERE tenant_id = ? AND operation = 'distribuicao' ORDER BY id DESC LIMIT 1");
        $logStmt->execute([$tenantId]);
        $lastLog = $logStmt->fetch() ?: null;
        $this->view('sefaz/resultado', [
            'downloaded' => $downloaded,
            'total' => $after,
            'lastLog' => $lastLog,
            'cnpj' => $cnpj,
            'nsu' => $nsu,
        ]);
    }
}
