<?php

namespace Tests\Modules\CRMAvancado;

use Tests\TestCase;

/**
 * Testes para o módulo CRM Avançado
 */
class CRMAvancadoTest extends TestCase {
    
    protected function setUp(): void {
        parent::setUp();
        
        // Criar tabelas do CRM
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS email_campaigns (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                nome VARCHAR(255) NOT NULL,
                assunto VARCHAR(255) NOT NULL,
                conteudo_html TEXT NOT NULL,
                status VARCHAR(20) DEFAULT "rascunho",
                total_enviados INTEGER DEFAULT 0,
                total_abertos INTEGER DEFAULT 0,
                total_cliques INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS email_campaign_recipients (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                campaign_id INTEGER NOT NULL,
                email VARCHAR(255) NOT NULL,
                status VARCHAR(20) DEFAULT "pendente",
                data_envio DATETIME,
                data_abertura DATETIME,
                data_clique DATETIME,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
    }
    
    public function testCreateEmailCampaign(): void {
        // Criar campanha
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaigns (tenant_id, nome, assunto, conteudo_html, status)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            'Test Campaign',
            'Test Subject',
            '<html><body>Test Content</body></html>',
            'rascunho'
        ]);
        $campaignId = (int)$this->pdo->lastInsertId();
        
        // Verificar campanha
        $stmt = $this->pdo->prepare('SELECT * FROM email_campaigns WHERE id = ?');
        $stmt->execute([$campaignId]);
        $campaign = $stmt->fetch();
        
        $this->assertNotFalse($campaign);
        $this->assertEquals('Test Campaign', $campaign['nome']);
        $this->assertEquals('rascunho', $campaign['status']);
    }
    
    public function testAddRecipients(): void {
        // Criar campanha
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaigns (tenant_id, nome, assunto, conteudo_html, status)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            'Test Campaign',
            'Test Subject',
            '<html><body>Test Content</body></html>',
            'rascunho'
        ]);
        $campaignId = (int)$this->pdo->lastInsertId();
        
        // Adicionar destinatários
        $emails = ['email1@example.com', 'email2@example.com', 'email3@example.com'];
        foreach ($emails as $email) {
            $stmt = $this->pdo->prepare('
                INSERT INTO email_campaign_recipients (tenant_id, campaign_id, email, status)
                VALUES (?, ?, ?, ?)
            ');
            $stmt->execute([$this->tenantId, $campaignId, $email, 'pendente']);
        }
        
        // Verificar destinatários
        $stmt = $this->pdo->prepare('SELECT COUNT(*) as count FROM email_campaign_recipients WHERE campaign_id = ?');
        $stmt->execute([$campaignId]);
        $count = $stmt->fetch();
        
        $this->assertEquals(3, $count['count']);
    }
    
    public function testTrackEmailOpen(): void {
        // Criar campanha
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaigns (tenant_id, nome, assunto, conteudo_html, status)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            'Test Campaign',
            'Test Subject',
            '<html><body>Test Content</body></html>',
            'enviada'
        ]);
        $campaignId = (int)$this->pdo->lastInsertId();
        
        // Criar destinatário
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaign_recipients (tenant_id, campaign_id, email, status, data_envio)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, $campaignId, 'test@example.com', 'entregue', date('Y-m-d H:i:s')]);
        $recipientId = (int)$this->pdo->lastInsertId();
        
        // Registrar abertura
        $stmt = $this->pdo->prepare('
            UPDATE email_campaign_recipients
            SET status = "aberto", data_abertura = ?
            WHERE id = ?
        ');
        $stmt->execute([date('Y-m-d H:i:s'), $recipientId]);
        
        // Atualizar estatísticas da campanha
        $stmt = $this->pdo->prepare('
            UPDATE email_campaigns
            SET total_abertos = total_abertos + 1
            WHERE id = ?
        ');
        $stmt->execute([$campaignId]);
        
        // Verificar abertura
        $stmt = $this->pdo->prepare('SELECT * FROM email_campaign_recipients WHERE id = ?');
        $stmt->execute([$recipientId]);
        $recipient = $stmt->fetch();
        
        $this->assertEquals('aberto', $recipient['status']);
        $this->assertNotNull($recipient['data_abertura']);
        
        // Verificar estatísticas
        $stmt = $this->pdo->prepare('SELECT total_abertos FROM email_campaigns WHERE id = ?');
        $stmt->execute([$campaignId]);
        $campaign = $stmt->fetch();
        
        $this->assertEquals(1, $campaign['total_abertos']);
    }
    
    public function testTrackEmailClick(): void {
        // Criar campanha
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaigns (tenant_id, nome, assunto, conteudo_html, status)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            'Test Campaign',
            'Test Subject',
            '<html><body>Test Content</body></html>',
            'enviada'
        ]);
        $campaignId = (int)$this->pdo->lastInsertId();
        
        // Criar destinatário
        $stmt = $this->pdo->prepare('
            INSERT INTO email_campaign_recipients (tenant_id, campaign_id, email, status, data_envio)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, $campaignId, 'test@example.com', 'entregue', date('Y-m-d H:i:s')]);
        $recipientId = (int)$this->pdo->lastInsertId();
        
        // Registrar clique
        $stmt = $this->pdo->prepare('
            UPDATE email_campaign_recipients
            SET status = "clicado", data_clique = ?
            WHERE id = ?
        ');
        $stmt->execute([date('Y-m-d H:i:s'), $recipientId]);
        
        // Atualizar estatísticas da campanha
        $stmt = $this->pdo->prepare('
            UPDATE email_campaigns
            SET total_cliques = total_cliques + 1
            WHERE id = ?
        ');
        $stmt->execute([$campaignId]);
        
        // Verificar clique
        $stmt = $this->pdo->prepare('SELECT * FROM email_campaign_recipients WHERE id = ?');
        $stmt->execute([$recipientId]);
        $recipient = $stmt->fetch();
        
        $this->assertEquals('clicado', $recipient['status']);
        $this->assertNotNull($recipient['data_clique']);
        
        // Verificar estatísticas
        $stmt = $this->pdo->prepare('SELECT total_cliques FROM email_campaigns WHERE id = ?');
        $stmt->execute([$campaignId]);
        $campaign = $stmt->fetch();
        
        $this->assertEquals(1, $campaign['total_cliques']);
    }
}

