<?php
declare(strict_types=1);

namespace App\Controllers;

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

class CronController extends Controller
{
    public function runConsulta(): void
    {
        $rows = DB::pdo()->query("SELECT id FROM tenants WHERE status = 'ativo'")->fetchAll();
        $total = 0;
        foreach ($rows as $t) {
            $tenantId = (int)$t['id'];
            try {
                $novas = \App\Services\NFePhpService::baixarNotasDestinadas($tenantId);
                $total += (int)$novas;
            } catch (\Throwable $e) {
                $stmt = DB::pdo()->prepare("INSERT INTO sefaz_failed (tenant_id, operation, request, status_code, error, next_retry_at, retries, created_at) VALUES (?, 'cron_consulta', '', 0, ?, ?, ?, ?)");
                $stmt->execute([$tenantId, $e->getMessage(), date('Y-m-d H:i:s', time() + 300), 1, date('Y-m-d H:i:s')]);
            }
        }
        echo 'consulta-ok:' . $total;
    }

    public function runManifestacao(): void
    {
        $rows = DB::pdo()->query("SELECT i.tenant_id, i.chave, t.cnpj FROM invoices i JOIN tenants t ON t.id = i.tenant_id WHERE i.status = 'baixado' AND t.status = 'ativo'")->fetchAll();
        foreach ($rows as $r) {
            SefazService::manifestar((int)$r['tenant_id'], $r['cnpj'], $r['chave'], 'ciencia');
            $up = DB::pdo()->prepare("UPDATE invoices SET status = 'ciencia', updated_at = ? WHERE tenant_id = ? AND chave = ?");
            $up->execute([date('Y-m-d H:i:s'), (int)$r['tenant_id'], $r['chave']]);
        }
        echo 'manifestacao-ok';
    }

    public function runManifestacaoNotas(): void
    {
        $auto = getenv('APP_AUTOMANIFEST') ?: 'ciencia';
        $rows = DB::pdo()->query("SELECT n.tenant_id, n.chave_acesso AS chave, t.cnpj FROM notas n JOIN tenants t ON t.id = n.tenant_id WHERE t.status = 'ativo'")->fetchAll();
        foreach ($rows as $r) {
            $tenantId = (int)$r['tenant_id'];
            $cnpj = (string)$r['cnpj'];
            $chave = (string)$r['chave'];
            $list = [];
            if ($auto === 'all') {
                $list = ['ciencia','confirmacao','desconhecimento','operacao_nao_realizada'];
            } else {
                $list = [$auto];
            }
            foreach ($list as $tipo) {
                SefazService::manifestar($tenantId, $cnpj, $chave, $tipo);
            }
        }
        echo 'manifestacao-notas-ok';
    }
}
