<?php
// admin/newsletter-campaigns.php

$pageTitle = 'Campanhas de Newsletter';
$pageHeader = 'Gerenciar Campanhas de Email';
$currentPage = 'newsletter-campaigns';
$useRichEditor = true;

// Define BASE_PATH se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Requer autenticação
if (!$auth->isLoggedIn()) {
    redirect('admin/login.php');
    exit;
}

// Processamento de ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create_campaign') {
        try {
            $title = trim($_POST['title']);
            $subject = trim($_POST['subject']);
            $content = trim($_POST['content']);
            $status = 'draft';
            
            if (empty($title) || empty($subject) || empty($content)) {
                throw new Exception('Todos os campos são obrigatórios.');
            }
            
            $db->query("INSERT INTO newsletter_campaigns (title, subject, content, status, created_by) 
                       VALUES (:title, :subject, :content, :status, :created_by)");
            $db->bind(':title', $title);
            $db->bind(':subject', $subject);
            $db->bind(':content', $content);
            $db->bind(':status', $status);
            $db->bind(':created_by', $_SESSION['admin_id']);
            $db->execute();
            
            setAlert('Campanha criada com sucesso!', ALERT_SUCCESS);
        } catch (Exception $e) {
            setAlert('Erro ao criar campanha: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    if ($action === 'send_campaign') {
        try {
            $campaignId = intval($_POST['campaign_id']);
            
            // Buscar campanha
            $db->query("SELECT * FROM newsletter_campaigns WHERE id = :id AND status = 'draft'");
            $db->bind(':id', $campaignId);
            $campaign = $db->single();
            
            if (!$campaign) {
                throw new Exception('Campanha não encontrada ou já foi enviada.');
            }
            
            // Buscar inscritos ativos
            $db->query("SELECT id, email, name, unsubscribe_token FROM newsletter_subscribers WHERE status = 'active'");
            $subscribers = $db->resultSet();
            
            if (empty($subscribers)) {
                throw new Exception('Nenhum inscrito ativo encontrado.');
            }
            
            $sentCount = 0;
            $errors = [];
            
            foreach ($subscribers as $subscriber) {
                try {
                    $success = sendCampaignEmail($campaign, $subscriber);
                    if ($success) {
                        $sentCount++;
                        
                        // Registrar tracking
                        $db->query("INSERT INTO newsletter_tracking (campaign_id, subscriber_id, action) 
                                   VALUES (:campaign_id, :subscriber_id, 'sent')");
                        $db->bind(':campaign_id', $campaignId);
                        $db->bind(':subscriber_id', $subscriber['id']);
                        $db->execute();
                        
                        // Atualizar contador do subscriber
                        $db->query("UPDATE newsletter_subscribers SET 
                                   email_count = email_count + 1, 
                                   last_email_sent = NOW() 
                                   WHERE id = :id");
                        $db->bind(':id', $subscriber['id']);
                        $db->execute();
                    }
                } catch (Exception $e) {
                    $errors[] = "Erro ao enviar para {$subscriber['email']}: " . $e->getMessage();
                }
            }
            
            // Atualizar status da campanha
            $db->query("UPDATE newsletter_campaigns SET 
                       status = 'sent', 
                       sent_at = NOW(), 
                       recipients_count = :count 
                       WHERE id = :id");
            $db->bind(':count', $sentCount);
            $db->bind(':id', $campaignId);
            $db->execute();
            
            if ($sentCount > 0) {
                setAlert("Campanha enviada com sucesso para $sentCount inscritos!", ALERT_SUCCESS);
            }
            
            if (!empty($errors)) {
                logError("Erros no envio da campanha $campaignId: " . implode('; ', $errors));
            }
            
        } catch (Exception $e) {
            setAlert('Erro ao enviar campanha: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    if ($action === 'delete_campaign') {
        try {
            $campaignId = intval($_POST['campaign_id']);
            
            $db->query("DELETE FROM newsletter_campaigns WHERE id = :id");
            $db->bind(':id', $campaignId);
            $db->execute();
            
            setAlert('Campanha removida com sucesso!', ALERT_SUCCESS);
        } catch (Exception $e) {
            setAlert('Erro ao remover campanha: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    redirect('newsletter-campaigns.php');
}

// Buscar campanhas
$db->query("SELECT c.*, a.username as created_by_name 
           FROM newsletter_campaigns c 
           LEFT JOIN admins a ON c.created_by = a.id 
           ORDER BY c.created_at DESC");
$campaigns = $db->resultSet();

// Estatísticas
$db->query("SELECT 
           COUNT(*) as total_campaigns,
           SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent_campaigns,
           SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) as draft_campaigns,
           SUM(recipients_count) as total_emails_sent
           FROM newsletter_campaigns");
$stats = $db->single();

require_once 'inc/header.php';

// Função para enviar email da campanha
function sendCampaignEmail($campaign, $subscriber) {
    $subject = $campaign['subject'];
    $unsubscribeUrl = SITE_URL . "/newsletter/unsubscribe.php?token=" . $subscriber['unsubscribe_token'];
    
    // Substituir placeholders no conteúdo
    $content = str_replace([
        '{name}',
        '{email}',
        '{unsubscribe_url}',
        '{site_name}',
        '{site_url}'
    ], [
        $subscriber['name'] ?: 'Amigo',
        $subscriber['email'],
        $unsubscribeUrl,
        SITE_NAME,
        SITE_URL
    ], $campaign['content']);
    
    // Template do email
    $emailContent = "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>$subject</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #4F46E5, #7C3AED); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
            .content { background: #f9f9f9; padding: 30px; }
            .footer { background: #333; color: white; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; font-size: 12px; }
            .footer a { color: #ccc; }
            .btn { display: inline-block; padding: 12px 25px; background: #4F46E5; color: white; text-decoration: none; border-radius: 5px; margin: 10px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>" . SITE_NAME . "</h1>
            </div>
            <div class='content'>
                $content
            </div>
            <div class='footer'>
                <p>Si no quieres recibir más emails, puedes <a href='$unsubscribeUrl'>darte de baja aquí</a></p>
                <p>&copy; " . date('Y') . " " . SITE_NAME . ". Todos los derechos reservados.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: " . SITE_NAME . " <noreply@" . parse_url(SITE_URL, PHP_URL_HOST) . ">" . "\r\n";
    
    return mail($subscriber['email'], $subject, $emailContent, $headers);
}
?>

<div class="container-fluid px-4">
    <!-- Cabeçalho -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h3 mb-3"><?php echo $pageHeader; ?></h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="newsletter-subscribers.php">Newsletter</a></li>
                    <li class="breadcrumb-item active">Campanhas</li>
                </ol>
            </nav>
        </div>
        <div class="col-md-4 text-md-end">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createCampaignModal">
                <i class="fas fa-plus me-2"></i>Nova Campanha
            </button>
        </div>
    </div>

    <!-- Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-primary"><?php echo number_format($stats['total_campaigns'] ?? 0); ?></h3>
                    <p class="text-muted mb-0">Total de Campanhas</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-success"><?php echo number_format($stats['sent_campaigns'] ?? 0); ?></h3>
                    <p class="text-muted mb-0">Campanhas Enviadas</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?php echo number_format($stats['draft_campaigns'] ?? 0); ?></h3>
                    <p class="text-muted mb-0">Rascunhos</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-info"><?php echo number_format($stats['total_emails_sent'] ?? 0); ?></h3>
                    <p class="text-muted mb-0">Emails Enviados</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Lista de campanhas -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">
            <h5 class="mb-0">Campanhas de Email</h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($campaigns)): ?>
            <div class="text-center py-5">
                <i class="fas fa-bullhorn fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">Nenhuma campanha criada</h5>
                <p class="text-muted">Crie sua primeira campanha de email para se comunicar com seus inscritos.</p>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createCampaignModal">
                    <i class="fas fa-plus me-2"></i>Criar Primeira Campanha
                </button>
            </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Título</th>
                            <th>Assunto</th>
                            <th>Status</th>
                            <th>Destinatários</th>
                            <th>Criado por</th>
                            <th>Data</th>
                            <th width="120">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($campaigns as $campaign): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($campaign['title']); ?></strong>
                            </td>
                            <td><?php echo htmlspecialchars($campaign['subject']); ?></td>
                            <td>
                                <?php
                                $statusClass = [
                                    'draft' => 'warning',
                                    'sent' => 'success',
                                    'scheduled' => 'info'
                                ][$campaign['status']] ?? 'secondary';
                                
                                $statusText = [
                                    'draft' => 'Rascunho',
                                    'sent' => 'Enviada',
                                    'scheduled' => 'Agendada'
                                ][$campaign['status']] ?? $campaign['status'];
                                ?>
                                <span class="badge bg-<?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                            </td>
                            <td>
                                <?php if ($campaign['status'] === 'sent'): ?>
                                    <span class="text-success"><?php echo number_format($campaign['recipients_count']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($campaign['created_by_name'] ?? 'N/A'); ?></td>
                            <td>
                                <?php if ($campaign['sent_at']): ?>
                                    Enviada: <?php echo formatDate($campaign['sent_at']); ?>
                                <?php else: ?>
                                    Criada: <?php echo formatDate($campaign['created_at']); ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        Ações
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a class="dropdown-item" href="#" data-bs-toggle="modal" 
                                               data-bs-target="#previewCampaignModal"
                                               data-title="<?php echo htmlspecialchars($campaign['title']); ?>"
                                               data-subject="<?php echo htmlspecialchars($campaign['subject']); ?>"
                                               data-content="<?php echo htmlspecialchars($campaign['content']); ?>">
                                                <i class="fas fa-eye me-2"></i>Visualizar
                                            </a>
                                        </li>
                                        <?php if ($campaign['status'] === 'draft'): ?>
                                        <li>
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja enviar esta campanha? Esta ação não pode ser desfeita.')">
                                                <input type="hidden" name="action" value="send_campaign">
                                                <input type="hidden" name="campaign_id" value="<?php echo $campaign['id']; ?>">
                                                <button type="submit" class="dropdown-item text-success">
                                                    <i class="fas fa-paper-plane me-2"></i>Enviar Agora
                                                </button>
                                            </form>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <?php endif; ?>
                                        <?php if ($campaign['status'] === 'sent'): ?>
                                        <li>
                                            <a class="dropdown-item" href="newsletter-reports.php?campaign=<?php echo $campaign['id']; ?>">
                                                <i class="fas fa-chart-bar me-2"></i>Relatório
                                            </a>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <?php endif; ?>
                                        <li>
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir esta campanha?')">
                                                <input type="hidden" name="action" value="delete_campaign">
                                                <input type="hidden" name="campaign_id" value="<?php echo $campaign['id']; ?>">
                                                <button type="submit" class="dropdown-item text-danger">
                                                    <i class="fas fa-trash me-2"></i>Excluir
                                                </button>
                                            </form>
                                        </li>
                                    </ul>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal para criar campanha -->
<div class="modal fade" id="createCampaignModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Nova Campanha de Email</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="create_campaign">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="title" class="form-label">Título da Campanha <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" required 
                               placeholder="Ex: Newsletter de Janeiro 2024">
                        <div class="form-text">Nome interno para identificar a campanha.</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="subject" class="form-label">Assunto do Email <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="subject" name="subject" required 
                               placeholder="Ex: 🎯 Novos cursos gratuitos disponíveis!">
                        <div class="form-text">Este será o assunto que os destinatários verão.</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="content" class="form-label">Conteúdo do Email <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="campaign-editor" name="content" rows="10" required></textarea>
                        <div class="form-text">
                            Você pode usar as seguintes variáveis: <code>{name}</code>, <code>{email}</code>, <code>{site_name}</code>, <code>{site_url}</code>
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Dica:</strong> A campanha será criada como rascunho. Você poderá visualizar e enviar posteriormente.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Criar Campanha</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para visualizar campanha -->
<div class="modal fade" id="previewCampaignModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Visualizar Campanha</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <strong>Título:</strong>
                    <div id="preview_title" class="text-muted"></div>
                </div>
                <div class="mb-3">
                    <strong>Assunto:</strong>
                    <div id="preview_subject" class="text-muted"></div>
                </div>
                <div class="mb-3">
                    <strong>Conteúdo:</strong>
                    <div id="preview_content" class="border rounded p-3" style="max-height: 400px; overflow-y: auto;"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
            </div>
        </div>
    </div>
</div>

<!-- Importar CKEditor -->
<script src="https://cdn.ckeditor.com/ckeditor5/38.1.0/classic/ckeditor.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Inicializar CKEditor
    ClassicEditor
        .create(document.querySelector('#campaign-editor'), {
            toolbar: [
                'heading', '|',
                'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|',
                'outdent', 'indent', '|',
                'blockQuote', 'insertTable', 'undo', 'redo'
            ]
        })
        .then(editor => {
            console.log('Editor de campanha inicializado', editor);
        })
        .catch(error => {
            console.error('Erro ao inicializar editor:', error);
        });
    
    // Modal de preview
    const previewModal = document.getElementById('previewCampaignModal');
    previewModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const title = button.getAttribute('data-title');
        const subject = button.getAttribute('data-subject');
        const content = button.getAttribute('data-content');
        
        document.getElementById('preview_title').textContent = title;
        document.getElementById('preview_subject').textContent = subject;
        document.getElementById('preview_content').innerHTML = content;
    });
});
</script>

<?php require_once 'inc/footer.php'; ?>