<?php

namespace Modules\SPED\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;

class SPEDViewsController {
    public function dashboard(Request $req): Response {
        return new Response(200, [], '<h1>Dashboard SPED</h1><p>Interface em desenvolvimento...</p>');
    }

    public function fiscal(Request $req): Response {
        return new Response(200, [], '<h1>SPED Fiscal (EFD-ICMS/IPI)</h1><p>Interface em desenvolvimento...</p>');
    }

    public function contribuicoes(Request $req): Response {
        return new Response(200, [], '<h1>SPED Contribuições (EFD-Contribuições)</h1><p>Interface em desenvolvimento...</p>');
    }

    public function contabil(Request $req): Response {
        return new Response(200, [], '<h1>SPED Contábil (ECD)</h1><p>Interface em desenvolvimento...</p>');
    }

    public function getConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            
            $stmt = $pdo->prepare('SELECT * FROM sped_config WHERE tenant_id = ?');
            $stmt->execute([$tenantId]);
            $config = $stmt->fetch(\PDO::FETCH_ASSOC);

            if (!$config) {
                // Criar configuração padrão
                $stmt = $pdo->prepare('
                    INSERT INTO sped_config (tenant_id) VALUES (?)
                ');
                $stmt->execute([$tenantId]);
                $config = [
                    'versao_layout' => '017',
                    'perfil' => 'A',
                    'ind_ativ' => 1,
                    'cod_fin' => 0,
                ];
            }

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

    public function updateConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $body = is_array($req->body) ? $req->body : [];

            // Verificar se existe
            $stmt = $pdo->prepare('SELECT id FROM sped_config WHERE tenant_id = ?');
            $stmt->execute([$tenantId]);
            $exists = $stmt->fetch();

            $allowedFields = [
                'versao_layout', 'perfil', 'ind_ativ', 'cod_fin',
                'geracao_automatica', 'dia_geracao', 'validacao_automatica', 'envio_automatico',
                'notificar_geracao', 'notificar_validacao', 'notificar_envio', 'email_notificacao'
            ];

            if ($exists) {
                // Atualizar
                $updates = [];
                $params = [];
                foreach ($allowedFields as $field) {
                    if (isset($body[$field])) {
                        $updates[] = "{$field} = ?";
                        $params[] = $body[$field];
                    }
                }
                if (!empty($updates)) {
                    $params[] = $tenantId;
                    $sql = 'UPDATE sped_config SET ' . implode(', ', $updates) . ' WHERE tenant_id = ?';
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }
            } else {
                // Criar
                $fields = [];
                $values = [];
                $params = [];
                foreach ($allowedFields as $field) {
                    if (isset($body[$field])) {
                        $fields[] = $field;
                        $values[] = '?';
                        $params[] = $body[$field];
                    }
                }
                if (!empty($fields)) {
                    $params[] = $tenantId;
                    $sql = 'INSERT INTO sped_config (tenant_id, ' . implode(', ', $fields) . ') VALUES (?, ' . implode(', ', $values) . ')';
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }
            }

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

