<?php

namespace Modules\Integracoes\WhatsApp\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\WhatsApp\Services\WhatsAppAPIService;

class WhatsAppController {
    public function dashboard(Request $req): Response {
        return new Response(200, [], '<h1>Integração WhatsApp</h1><p>Interface em desenvolvimento...</p>');
    }

    public function getConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new WhatsAppAPIService($tenantId);
            $config = $service->getConfig();

            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();
            $body = is_array($req->body) ? $req->body : [];

            $service = new WhatsAppAPIService($tenantId);
            $service->updateConfig($body);

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

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

            $numero = $body['numero'] ?? '';
            $mensagem = $body['mensagem'] ?? '';
            $templateId = !empty($body['template_id']) ? (int)$body['template_id'] : null;
            $variaveis = $body['variaveis'] ?? null;

            if (empty($numero) || (empty($mensagem) && !$templateId)) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'numero e mensagem/template_id são obrigatórios']]);
            }

            $service = new WhatsAppAPIService($tenantId);
            $resultado = $service->enviarMensagem($numero, $mensagem, $templateId, $variaveis);

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

    public function listMensagens(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $numero = $req->query['numero'] ?? null;
            $clienteId = !empty($req->query['cliente_id']) ? (int)$req->query['cliente_id'] : null;
            $limite = (int)($req->query['limite'] ?? 50);

            $service = new WhatsAppAPIService($tenantId);
            $mensagens = $service->listMensagens($numero, $clienteId, $limite);

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

    public function listTemplates(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new WhatsAppAPIService($tenantId);
            $templates = $service->listTemplates();

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

    public function webhook(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            
            // Verificação do webhook (GET)
            if ($req->method === 'GET') {
                $mode = $req->query['hub.mode'] ?? '';
                $token = $req->query['hub.verify_token'] ?? '';
                $challenge = $req->query['hub.challenge'] ?? '';

                // Verificar token
                $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
                $stmt = $pdo->prepare('SELECT webhook_verify_token FROM whatsapp_config WHERE tenant_id = ?');
                $stmt->execute([$tenantId]);
                $config = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($mode === 'subscribe' && $token === ($config['webhook_verify_token'] ?? '')) {
                    return new Response(200, [], $challenge);
                }

                return new Response(403, ['error' => 'Token inválido']);
            }

            // Processar webhook (POST)
            $body = is_array($req->body) ? $req->body : [];
            $service = new WhatsAppAPIService($tenantId);
            $service->processarWebhook($body);

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

