<?php

namespace Modules\CRMAvancado\Controllers;

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

class EmailMarketingController {
    public function listCampanhas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            
            $page = max(1, (int)($req->query['page'] ?? 1));
            $per = min(100, max(1, (int)($req->query['per_page'] ?? 20)));
            $offset = ($page - 1) * $per;

            $where = ['tenant_id = ?'];
            $params = [$tenantId];

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

            $whereSql = implode(' AND ', $where);

            $sql = "SELECT * FROM email_campaigns
                    WHERE {$whereSql}
                    ORDER BY created_at DESC
                    LIMIT ? OFFSET ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_merge($params, [$per, $offset]));
            $campanhas = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Total
            $countSql = "SELECT COUNT(*) FROM email_campaigns WHERE {$whereSql}";
            $countStmt = $pdo->prepare($countSql);
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            return Response::json([
                'data' => $campanhas,
                'pagination' => [
                    'page' => $page,
                    'per_page' => $per,
                    'total' => $total,
                    'total_pages' => (int)ceil($total / $per)
                ]
            ]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

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

            $stmt = $pdo->prepare('
                INSERT INTO email_campaigns (
                    tenant_id, nome, assunto, conteudo_html, conteudo_texto,
                    segmento_tipo, segmento_filtros_json, status, data_envio,
                    created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $tenantId,
                $body['nome'],
                $body['assunto'],
                $body['conteudo_html'],
                $body['conteudo_texto'] ?? null,
                $body['segmento_tipo'] ?? 'todos',
                !empty($body['segmento_filtros']) ? json_encode($body['segmento_filtros']) : null,
                $body['status'] ?? 'rascunho',
                $body['data_envio'] ?? null,
                $userContext?->userId,
            ]);

            $campanhaId = (int)$pdo->lastInsertId();

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

    public function enviarCampanha(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $campanhaId = (int)($req->get('params')[0] ?? 0);

            if (!$campanhaId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'campanha_id é obrigatório']]);
            }

            $service = new \Modules\CRMAvancado\Services\EmailMarketingService($tenantId);
            $resultado = $service->enviarCampanha($campanhaId);

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

    public function getAnalytics(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $campanhaId = (int)($req->get('params')[0] ?? 0);

            // Buscar campanha
            $stmt = $pdo->prepare('SELECT * FROM email_campaigns WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$campanhaId, $tenantId]);
            $campanha = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$campanha) {
                return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Campanha não encontrada']]);
            }

            // Buscar estatísticas dos destinatários
            $stmt = $pdo->prepare('
                SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN status = "enviado" THEN 1 ELSE 0 END) as enviados,
                    SUM(CASE WHEN status = "entregue" THEN 1 ELSE 0 END) as entregues,
                    SUM(CASE WHEN status = "aberto" THEN 1 ELSE 0 END) as abertos,
                    SUM(CASE WHEN status = "clicado" THEN 1 ELSE 0 END) as cliques,
                    SUM(CASE WHEN status = "rejeitado" THEN 1 ELSE 0 END) as rejeitados
                FROM email_campaign_recipients
                WHERE campaign_id = ? AND tenant_id = ?
            ');
            $stmt->execute([$campanhaId, $tenantId]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);

            $total = (int)($stats['total'] ?? 0);
            $enviados = (int)($stats['enviados'] ?? 0);
            $entregues = (int)($stats['entregues'] ?? 0);
            $abertos = (int)($stats['abertos'] ?? 0);
            $cliques = (int)($stats['cliques'] ?? 0);

            $taxaAbertura = $entregues > 0 ? ($abertos / $entregues) * 100 : 0;
            $taxaClique = $entregues > 0 ? ($cliques / $entregues) * 100 : 0;

            // Calcular taxas atualizadas
            $campanhaStmt = $pdo->prepare('SELECT total_abertos, total_cliques, total_entregues FROM email_campaigns WHERE id = ?');
            $campanhaStmt->execute([$campanhaId]);
            $campanhaStats = $campanhaStmt->fetch(PDO::FETCH_ASSOC);

            $totalEntregues = (int)($campanhaStats['total_entregues'] ?? $entregues);
            $totalAbertos = (int)($campanhaStats['total_abertos'] ?? $abertos);
            $totalCliques = (int)($campanhaStats['total_cliques'] ?? $cliques);

            $taxaAbertura = $totalEntregues > 0 ? ($totalAbertos / $totalEntregues) * 100 : 0;
            $taxaClique = $totalEntregues > 0 ? ($totalCliques / $totalEntregues) * 100 : 0;

            // Atualizar taxas na campanha
            $updateStmt = $pdo->prepare('
                UPDATE email_campaigns
                SET taxa_abertura = ?, taxa_clique = ?
                WHERE id = ?
            ');
            $updateStmt->execute([$taxaAbertura, $taxaClique, $campanhaId]);

            return Response::json([
                'data' => [
                    'total_destinatarios' => $total,
                    'total_enviados' => $enviados,
                    'total_entregues' => $totalEntregues,
                    'total_abertos' => $totalAbertos,
                    'total_cliques' => $totalCliques,
                    'taxa_abertura' => round($taxaAbertura, 2),
                    'taxa_clique' => round($taxaClique, 2)
                ]
            ]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    /**
     * Track abertura de e-mail (pixel transparente)
     */
    public function trackOpen(Request $req): Response {
        try {
            $token = $req->get('params')[0] ?? '';

            if (empty($token)) {
                // Retornar pixel transparente 1x1
                header('Content-Type: image/gif');
                echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
                exit;
            }

            // Extrair tenant_id do token
            $data = base64_decode($token);
            $parts = explode('_', $data);
            $tenantId = $parts[0] ?? '';

            if (empty($tenantId)) {
                header('Content-Type: image/gif');
                echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
                exit;
            }

            $service = new \Modules\CRMAvancado\Services\EmailMarketingService($tenantId);
            $service->registrarAbertura($token);

            // Retornar pixel transparente 1x1
            header('Content-Type: image/gif');
            header('Cache-Control: no-cache, no-store, must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
            exit;
        } catch (\Exception $e) {
            // Retornar pixel mesmo em caso de erro
            header('Content-Type: image/gif');
            echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
            exit;
        }
    }

    /**
     * Track clique em link
     */
    public function trackClick(Request $req): Response {
        try {
            $token = $req->get('params')[0] ?? '';

            if (empty($token)) {
                return new Response(404);
            }

            // Extrair tenant_id do token
            $data = base64_decode($token);
            $parts = explode('_', $data);
            $tenantId = $parts[0] ?? '';

            if (empty($tenantId)) {
                return new Response(404);
            }

            $service = new \Modules\CRMAvancado\Services\EmailMarketingService($tenantId);
            $url = $service->registrarClique($token);

            if ($url) {
                // Redirecionar para URL original
                header('Location: ' . $url);
                exit;
            }

            return new Response(404);
        } catch (\Exception $e) {
            return new Response(404);
        }
    }
}

