<?php

namespace Modules\SPED\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\SPED\Services\SPEDContabilService;

class SPEDContabilController {
    public function gerar(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];

            $ano = (int)($body['ano'] ?? date('Y'));
            $mes = (int)($body['mes'] ?? date('n'));
            $opcoes = $body['opcoes'] ?? [];

            $service = new SPEDContabilService($tenantId);
            $resultado = $service->gerar($ano, $mes, $opcoes);

            return Response::json(['data' => $resultado], 201);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function validar(Request $req): Response {
        try {
            // TODO: Implementar validação específica de SPED Contábil
            return Response::json(['data' => ['valido' => true, 'message' => 'Validação em desenvolvimento']]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function listArquivos(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
            
            $where = ['tenant_id = ?', 'tipo = "contabil"'];
            $params = [$tenantId];

            if (!empty($req->query['ano'])) {
                $where[] = 'ano = ?';
                $params[] = $req->query['ano'];
            }

            $whereSql = implode(' AND ', $where);
            $sql = "SELECT * FROM sped_arquivos WHERE {$whereSql} ORDER BY created_at DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $arquivos = $stmt->fetchAll(\PDO::FETCH_ASSOC);

            return Response::json(['data' => $arquivos]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

