<?php 
// Start session at the beginning of the file
session_start();
error_reporting(E_ALL & ~E_NOTICE); 
include_once "utils_database.php";
include_once "utils.php";
require_once "session_check.php";

// Extract request variables with prefix
$prefix = "P";
foreach ($_REQUEST as $key => $value) {
    $varname = $prefix . '_' . $key;
    $$varname = $value;
}

$vMaxNroPalabras = 300; 
$vMaxNroPalabrasTitulo = 30; 

// Get user information if logged in
$vAreasUsuario = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 9) : '';
$vTipo = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 2) : '';
$vIdUsr = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 1) : '';

// Verificar si el usuario está logueado
if (!isset($_SESSION['usr'])) {
    // Usuario no logueado, redirigir a la página de login
    header("Location: login.php");
    exit(); // Importante: detener la ejecución después de la redirección
}

// Include database utilities
require_once 'utils_database.php';

// Get available variable lists for template
function getAvailableDatabaseVariables() {
    return [
        'tusuario' => ['id', 'nombre', 'correo', 'usuario','contrasena', 'cod_ciudad', 'avatar'],
        'ttrabajo' => ['id', 'titulo', 'introduccion', 'materiales', 'resultados', 'conclusiones', 'fecha'],
        'ttipo_competicion' => ['id', 'codigo', 'descripcion_esp'],
        'ttipo_presentacion' => ['id', 'codigo', 'descripcion_esp'],
        'tarea' => ['id', 'codigo', 'descripcion']
    ];
}

// Create Email Campaign
function createEmailCampaign($name, $subject, $content, $created_by) {
    $conn = Activarmysql();
    $stmt = $conn->prepare("INSERT INTO email_campaigns (name, subject, content, created_by, created_at, status) VALUES (?, ?, ?, ?, NOW(), 'draft')");
    $stmt->bind_param("sssi", $name, $subject, $content, $created_by);
    $result = $stmt->execute();
    $campaign_id = $result ? $conn->insert_id : 0;
    $stmt->close();
    $conn->close();
    return $campaign_id;
}

// Get All Email Campaigns
function getAllEmailCampaigns() {
    $conn = Activarmysql();
    $campaigns = [];
    
    $query = "SELECT ec.id, ec.name, ec.subject, ec.status, ec.created_at, 
              COUNT(DISTINCT es.evaluator_id) as total_recipients, 
              SUM(CASE WHEN es.action_type = 'sent' THEN 1 ELSE 0 END) as sent_count,
              tu.nombre as created_by_name
              FROM email_campaigns ec
              LEFT JOIN email_campaign_stats es ON ec.id = es.campaign_id
              LEFT JOIN tusuario tu ON ec.created_by = tu.id
              GROUP BY ec.id
              ORDER BY ec.created_at DESC";
    
    $result = $conn->query($query);
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $campaigns[] = $row;
        }
    }
    
    $conn->close();
    return $campaigns;
}

// Get Email Campaign by ID
function getEmailCampaignById($id) {
    $conn = Activarmysql();
    $stmt = $conn->prepare("SELECT * FROM email_campaigns WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $campaign = $result->fetch_assoc();
    $stmt->close();
    $conn->close();
    return $campaign;
}

// Update Email Campaign
function updateEmailCampaign($id, $name, $subject, $content) {
    $conn = Activarmysql();
    $stmt = $conn->prepare("UPDATE email_campaigns SET name = ?, subject = ?, content = ?, updated_at = NOW() WHERE id = ?");
    $stmt->bind_param("sssi", $name, $subject, $content, $id);
    $result = $stmt->execute();
    $stmt->close();
    $conn->close();
    return $result;
}

// Delete Email Campaign
function deleteEmailCampaign($id) {
    $conn = Activarmysql();
    $stmt = $conn->prepare("DELETE FROM email_campaigns WHERE id = ?");
    $stmt->bind_param("i", $id);
    $result = $stmt->execute();
    $stmt->close();
    $conn->close();
    return $result;
}

// Statistics tracking functions
function registerEmailSent($evaluatorId, $campaignId = null) {
    $conn = Activarmysql();
    
    if ($campaignId) {
        $stmt = $conn->prepare("INSERT INTO email_campaign_stats (campaign_id, evaluator_id, action_type, action_date) VALUES (?, ?, 'sent', NOW())");
        $stmt->bind_param("ii", $campaignId, $evaluatorId);
    } else {
        $stmt = $conn->prepare("INSERT INTO email_statistics (evaluator_id, action_type, action_date) VALUES (?, 'sent', NOW())");
        $stmt->bind_param("i", $evaluatorId);
    }
    
    $stmt->execute();
    $stmt->close();
    $conn->close();
}

function getEmailStatistics() {
    $conn = Activarmysql();
    $statistics = [
        'sent' => 0,
        'opened' => 0,
        'rejected' => 0,
        'bounced' => 0
    ];
    
    $query = "SELECT action_type, COUNT(*) as count FROM email_statistics GROUP BY action_type";
    $result = $conn->query($query);
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $statistics[$row['action_type']] = $row['count'];
        }
    }
    
    $conn->close();
    return $statistics;
}

// Get email open rate for campaigns
function getCampaignStatistics($campaignId) {
    $conn = Activarmysql();
    $statistics = [
        'sent' => 0,
        'opened' => 0,
        'rejected' => 0,
        'bounced' => 0
    ];
    
    $stmt = $conn->prepare("SELECT action_type, COUNT(*) as count FROM email_campaign_stats WHERE campaign_id = ? GROUP BY action_type");
    $stmt->bind_param("i", $campaignId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $statistics[$row['action_type']] = $row['count'];
        }
    }
    
    $stmt->close();
    $conn->close();
    return $statistics;
}

// Parse template with variables - Función mejorada
function parseEmailTemplate($template, $evaluatorData) {
    // Verificar si todas las variables de usuario están disponibles
    $requiredUserFields = ['nombre', 'correo', 'usuario', 'contrasena', 'avatar'];
    
    // Buscar variables de tusuario en el template
    preg_match_all('/\$tusuario\.([a-zA-Z0-9_]+)/', $template, $userMatches);
    $userVarsInTemplate = $userMatches[1];
    
    // Obtener datos completos del usuario si faltan campos
    if (count(array_intersect($userVarsInTemplate, $requiredUserFields)) > 0) {
        $missingFields = array_diff($userVarsInTemplate, array_keys($evaluatorData));
        
        if (!empty($missingFields)) {
            // Obtener datos adicionales del usuario si es necesario
            $conn = Activarmysql();
            $userId = $evaluatorData['id'];
            
            if (!isset($userId) && isset($evaluatorData['correo'])) {
                // Buscar por correo electrónico si no tenemos ID
                $stmt = $conn->prepare("SELECT id, nombre, correo, usuario, contrasena, avatar, cod_ciudad FROM tusuario WHERE correo = ?");
                $stmt->bind_param("s", $evaluatorData['correo']);
            } else {
                // Buscar por ID
                $stmt = $conn->prepare("SELECT id, nombre, correo, usuario, contrasena, avatar, cod_ciudad FROM tusuario WHERE id = ?");
                $stmt->bind_param("i", $userId);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($row = $result->fetch_assoc()) {
                // Fusionar los datos obtenidos con los existentes
                $evaluatorData = array_merge($evaluatorData, $row);
            }
            
            $stmt->close();
            $conn->close();
        }
    }
    
    // Replace user variables
    foreach ($evaluatorData as $key => $value) {
        $template = str_replace('$tusuario.'.$key, $value, $template);
    }
    
    // Buscar variables de ttrabajo en el template
    preg_match_all('/\$ttrabajo\.([a-zA-Z0-9_]+)/', $template, $trabajoMatches);
    $trabajoVarsInTemplate = $trabajoMatches[1];
    
    // Si hay variables de trabajo, intentar obtener datos de trabajos
    if (!empty($trabajoVarsInTemplate) && isset($evaluatorData['id'])) {
        $conn = Activarmysql();
        $userId = $evaluatorData['id'];
        
        // Obtener el trabajo más reciente del usuario (puedes ajustar la consulta según tu estructura)
        $stmt = $conn->prepare("SELECT id, titulo, introduccion, materiales, resultados, conclusiones, fecha 
                                FROM ttrabajo WHERE (evaluador1 = ? or evaluador2 = ? or evaluador3 = ?)  ORDER BY fecha DESC LIMIT 1");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            // Reemplazar variables de trabajo
            foreach ($row as $key => $value) {
                $template = str_replace('$ttrabajo.'.$key, $value, $template);
            }
        }
        
        $stmt->close();
        $conn->close();
    }
    
    // Buscar variables de categoría/competición en el template
    preg_match_all('/\$ttipo_competicion\.([a-zA-Z0-9_]+)/', $template, $catMatches);
    $catVarsInTemplate = $catMatches[1];
    
    // Si hay variables de categoría, intentar obtenerlas
    if (!empty($catVarsInTemplate) && isset($evaluatorData['id'])) {
        $conn = Activarmysql();
        
        // Obtener datos de categoría (ajusta según tu estructura)
        $stmt = $conn->prepare("SELECT tc.id, tc.codigo, tc.descripcion_esp
                                FROM ttipo_competicion tc 
                                INNER JOIN ttrabajo tt ON tc.codigo = tt.cod_tipo_competicion_propuesto
                                WHERE tt.cod_tipo_competicion_propuesto = ? 
                                LIMIT 1");
        $stmt->bind_param("i", $evaluatorData['id']);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            // Reemplazar variables de categoría
            foreach ($row as $key => $value) {
                $template = str_replace('$ttipo_competicion.'.$key, $value, $template);
            }
        }
        
        $stmt->close();
        $conn->close();
    }
    
    // Mostrar variables no reemplazadas con formato especial
    $template = preg_replace('/\$(tusuario|ttrabajo|ttipo_competicion)\.([a-zA-Z0-9_]+)/', '<span style="color:red;background-color:yellow">[$1.$2-no_disponible]</span>', $template);
    
    return $template;
}


// Email sending function with dynamic template - Función mejorada
function sendEvaluatorEmail($evaluatorId, $campaignId = null) {
    $conn = Activarmysql();
    
    // Get evaluator data - incluir explícitamente el campo contrasena
    $stmt = $conn->prepare("SELECT id, nombre, usuario, contrasena, correo, avatar, cod_ciudad FROM tusuario WHERE id = ?");
    
    // Verificar que la consulta se preparó correctamente
    if ($stmt === false) {
        error_log("Error preparando consulta: " . $conn->error);
        return false;
    }
    
    $stmt->bind_param("i", $evaluatorId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $evaluatorData = $row;
        
        // If campaign ID is provided, use that template
        if ($campaignId) {
            $campaign = getEmailCampaignById($campaignId);
            $emailSubject = $campaign['subject'];
            $emailTemplate = $campaign['content'];
        } else {
            // Fallback to default template and subject
            $emailSubject = "Abstract Evaluation Instructions – XXXVIII Panamerican Congress of Trauma";
            $emailTemplate = generateDefaultEmailTemplate($evaluatorData['nombre'], $evaluatorData['usuario'], $evaluatorData['contrasena'], $evaluatorData['avatar']);
        }
        
        // Parse template with variables
        $emailContent = parseEmailTemplate($emailTemplate, $evaluatorData);
        
        // Email headers
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: PTS Program Committee <no-reply@panamtrauma.site>" . "\r\n";
        
        // Send email
        $mailSent = mail($evaluatorData['correo'], $emailSubject, $emailContent, $headers);
        
        if ($mailSent) {
            registerEmailSent($evaluatorId, $campaignId);
            return true;
        } else {
            error_log("Error enviando correo a " . $evaluatorData['correo']);
        }
    } else {
        error_log("No se encontró el usuario con ID: " . $evaluatorId);
    }
    
    $stmt->close();
    $conn->close();
    return false;
}

// Manage email sending for campaign
function sendCampaignToEvaluator($campaignId, $evaluatorId) {
    return sendEvaluatorEmail($evaluatorId, $campaignId);
}

// Send emails to multiple evaluators for a campaign
function sendBatchCampaignEmails($campaignId, $evaluatorIds) {
    $successCount = 0;
    $failCount = 0;
    
    foreach ($evaluatorIds as $evaluatorId) {
        $result = sendCampaignToEvaluator($campaignId, $evaluatorId);
        if ($result) {
            $successCount++;
        } else {
            $failCount++;
        }
    }
    
    // Update campaign status if all are sent
    if ($successCount > 0) {
        $conn = Activarmysql();
        $stmt = $conn->prepare("UPDATE email_campaigns SET status = 'sent', sent_at = NOW() WHERE id = ?");
        $stmt->bind_param("i", $campaignId);
        $stmt->execute();
        $stmt->close();
        $conn->close();
    }
    
    return [
        'success' => $successCount,
        'failed' => $failCount,
        'total' => count($evaluatorIds)
    ];
}

// Default template as a fallback
function generateDefaultEmailTemplate($nombre, $usuario, $contrasena, $avatar) {
    return '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Abstract Evaluation Instructions</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; background-color: #ffffff; }
            .header { text-align: center; padding: 20px 0; background-color: #427d6e; color: white; margin-bottom: 20px; }
            .greeting { font-weight: bold; font-size: 18px; margin-bottom: 15px; }
            .content { padding: 0 20px; }
            .footer { text-align: center; padding: 20px 0; font-size: 12px; color: #666; border-top: 1px solid #eee; margin-top: 20px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>XXXVII Panamerican Congress of Trauma</h2>
            </div>
            
            <div class="content">
                <p class="greeting">Dear ' . $nombre . ',</p>
                
                <p>Thank you for supporting the Panamerican Trauma Society\'s (PTS) call for abstracts.</p>
                
                <p>Please use these credentials to login:</p>
                <p>Username: <strong>' . $usuario . '</strong><br>
                Password: <strong>' . $contrasena . '</strong></p>
                
                <p>Thank you for your contribution!</p>
                
                <p>Best regards,<br>
                Program Committee<br>
                Panamerican Trauma Society</p>
            </div>
            
            <div class="footer">
                <p>This is an automated message. Please do not reply to this email.</p>
                <p>&copy; 2025 Panamerican Trauma Society. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>';
}


// IMPORTANT: Process form actions before any HTML output

// CREATE/UPDATE CAMPAIGN
if (isset($_POST['save_campaign'])) {
    $campaignName = isset($_POST['campaign_name']) ? $_POST['campaign_name'] : '';
    $campaignSubject = isset($_POST['campaign_subject']) ? $_POST['campaign_subject'] : '';
    $campaignContent = isset($_POST['campaign_content']) ? $_POST['campaign_content'] : '';
    $campaignId = isset($_POST['campaign_id']) ? intval($_POST['campaign_id']) : 0;
    
    if (empty($campaignName) || empty($campaignSubject) || empty($campaignContent)) {
        $_SESSION['campaign_message'] = [
            'type' => 'danger',
            'text' => 'All fields are required for the campaign.'
        ];
    } else {
        if ($campaignId > 0) {
            // Update existing campaign
            $result = updateEmailCampaign($campaignId, $campaignName, $campaignSubject, $campaignContent);
            $message = 'Campaign updated successfully.';
        } else {
            // Create new campaign
            $result = createEmailCampaign($campaignName, $campaignSubject, $campaignContent, $vIdUsr);
            $message = 'Campaign created successfully.';
        }
        
        if ($result) {
            $_SESSION['campaign_message'] = [
                'type' => 'success',
                'text' => $message
            ];
        } else {
            $_SESSION['campaign_message'] = [
                'type' => 'danger',
                'text' => 'Error saving campaign. Please try again.'
            ];
        }
    }
    
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// DELETE CAMPAIGN
if (isset($_POST['delete_campaign']) && isset($_POST['campaign_id'])) {
    $campaignId = intval($_POST['campaign_id']);
    $result = deleteEmailCampaign($campaignId);
    
    if ($result) {
        $_SESSION['campaign_message'] = [
            'type' => 'success',
            'text' => 'Campaign deleted successfully.'
        ];
    } else {
        $_SESSION['campaign_message'] = [
            'type' => 'danger',
            'text' => 'Error deleting campaign. Please try again.'
        ];
    }
    
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// SEND CAMPAIGN TO SELECTED EVALUATORS
if (isset($_POST['send_campaign']) && isset($_POST['campaign_id']) && isset($_POST['selected_evaluators'])) {
    $campaignId = intval($_POST['campaign_id']);
    $selectedEvaluators = $_POST['selected_evaluators'];
    
    if (empty($selectedEvaluators)) {
        $_SESSION['campaign_message'] = [
            'type' => 'warning',
            'text' => 'No evaluators selected. Please select at least one evaluator.'
        ];
    } else {
        // Send emails to all selected evaluators
        $result = sendBatchCampaignEmails($campaignId, $selectedEvaluators);
        
        $_SESSION['campaign_message'] = [
            'type' => $result['failed'] == 0 ? 'success' : 'warning',
            'text' => "Campaign sent: {$result['success']} successful, {$result['failed']} failed out of {$result['total']} total."
        ];
    }
    
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF'] . "?view=send&campaign_id=" . $campaignId);
    exit();
}

// INDIVIDUAL EMAIL RESENDING
if (isset($_POST['resend']) && isset($_POST['evaluator_id'])) {
    $evaluatorId = $_POST['evaluator_id'];
    $campaignId = isset($_POST['campaign_id']) ? $_POST['campaign_id'] : null;
    
    $result = $campaignId ? sendCampaignToEvaluator($campaignId, $evaluatorId) : sendEvaluatorEmail($evaluatorId);
    
    if ($result) {
        $_SESSION['email_action'] = [
            'status' => 'success',
            'text' => 'Email sent successfully.'
        ];
    } else {
        $_SESSION['email_action'] = [
            'status' => 'failure',
            'text' => 'Failed to send email. Please try again.'
        ];
    }
    
    // Redirect to prevent form resubmission
    if ($campaignId) {
        header("Location: " . $_SERVER['PHP_SELF'] . "?view=send&campaign_id=" . $campaignId);
    } else {
        header("Location: " . $_SERVER['PHP_SELF']);
    }
    exit();
}

// Get the current view
$currentView = isset($_GET['view']) ? $_GET['view'] : 'campaigns';
$campaignId = isset($_GET['campaign_id']) ? intval($_GET['campaign_id']) : 0;
$campaign = $campaignId > 0 ? getEmailCampaignById($campaignId) : null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Campaign Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Summernote WYSIWYG Editor -->
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #478576;
            --secondary-color: #13849C;
            --accent-color: #478576;
            --light-color: #00ffca;
            --bg-light: #f8f9fa;
            --text-dark: #333;
            --text-light: #f8f9fa;
            --border-radius: 0.5rem;
            --box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            --transition: all 0.3s ease;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            color: var(--text-dark);
        }
        
        .navbar-custom {
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-brand {
            font-weight: 700;
            letter-spacing: 0.5px;
        }
        
        .nav-pills .nav-link {
            border-radius: var(--border-radius);
            transition: var(--transition);
            margin-right: 5px;
            color: var(--text-dark);
        }
        
        .nav-pills .nav-link.active {
            background-color: var(--accent-color);
            color: var(--text-light);
        }
        
        .nav-pills .nav-link:hover:not(.active) {
            background-color: rgba(5, 191, 219, 0.1);
        }
        
        .card {
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            border: none;
            transition: var(--transition);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
        }
        
        .card-header {
            background: linear-gradient(90deg, var(--secondary-color), var(--accent-color));
            color: white;
            border-bottom: none;
            padding: 15px 20px;
        }
        
        .btn-primary {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
            transition: var(--transition);
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-outline-primary {
            color: var(--accent-color);
            border-color: var(--accent-color);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--accent-color);
            color: white;
        }
        
        .stats-card {
            text-align: center;
            padding: 25px 15px;
        }
        
        .stats-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
            color: var(--accent-color);
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: bold;
            color: var(--primary-color);
        }
        
        .table-container {
            background-color: white;
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: var(--box-shadow);
        }
        
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(5, 191, 219, 0.05);
        }
        
        .avatar-small {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f1f1f1;
        }
        
        .avatar-placeholder {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--secondary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
        }
        
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
        }
        
        .toast {
            min-width: 300px;
        }
        
        .action-bar {
            background-color: var(--bg-light);
            padding: 15px;
            margin-bottom: 20px;
            border-radius: var(--border-radius);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .select-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .campaign-list-item {
            padding: 15px;
            border-left: 4px solid var(--accent-color);
            margin-bottom: 15px;
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            transition: var(--transition);
        }
        
        .campaign-list-item:hover {
            transform: translateX(5px);
        }
        
        .campaign-list-item .badge {
            font-size: 0.75rem;
            padding: 5px 10px;
            border-radius: 20px;
        }
        
        .campaign-title {
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .campaign-subject {
            color: #666;
            margin-bottom: 8px;
        }
        
        .campaign-meta {
            font-size: 0.85rem;
            color: #888;
        }
        
        .badge-draft {
            background-color: #6c757d;
        }
        
        .badge-sent {
            background-color: #28a745;
        }
        
        /* Variable tags styling */
        .variable-tag {
            display: inline-block;
            background-color: var(--accent-color);
            color: white;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            margin: 5px;
            cursor: pointer;
            transition: var(--transition);
        }
        
        .variable-tag:hover {
            background-color: var(--secondary-color);
        }
        
        .variable-section {
            background-color: var(--bg-light);
            padding: 15px;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
        }
        
        .variable-table {
            background-color: white;
            border-radius: var(--border-radius);
            overflow: hidden;
            margin-top: 15px;
        }
        
        .variable-header {
            background-color: var(--secondary-color);
            color: white;
            padding: 10px 15px;
            font-weight: 600;
        }
        
        .variable-group {
            margin-bottom: 15px;
        }
        
        .template-preview {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: var(--border-radius);
            background-color: white;
            height: 400px;
            overflow: auto;
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: var(--text-dark);
            font-weight: 500;
            padding: 10px 20px;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--accent-color);
            border-bottom: 3px solid var(--accent-color);
            background-color: transparent;
        }
        
        .summernote-container {
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            overflow: hidden;
        }
        
        /* New visual enhancements */
        .page-title {
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            color: #6c757d;
            margin-bottom: 1.5rem;
        }
        
        .campaign-actions {
            gap: 8px;
            display: flex;
        }
        
        .campaign-badge {
            font-size: 0.75rem;
            padding: 0.35em 0.65em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .form-title {
            color: var(--primary-color);
            border-bottom: 2px solid var(--accent-color);
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        
        .stat-description {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .help-text {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        .note-editor {
            border-radius: var(--border-radius) !important;
        }
        
        .note-editing-area {
            min-height: 300px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom mb-4">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-envelope-open-text me-2"></i>
                Email Campaign Manager
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link text-white" href="index.php">
                            <i class="fas fa-home me-1"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="#">
                            <i class="fas fa-user me-1"></i> <?php echo isset($_SESSION['usr']) ? $_SESSION['usr'] : 'User'; ?>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="logout.php">
                            <i class="fas fa-sign-out-alt me-1"></i> Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row mb-4">
            <div class="col-md-12">
                <h2 class="page-title">Email Campaign System</h2>
                <p class="page-subtitle">Create, manage and send email campaigns to evaluators</p>
                
                <!-- Navigation Tabs -->
                <ul class="nav nav-pills mb-4">
                    <li class="nav-item">
                        <a class="nav-link <?php echo $currentView == 'campaigns' ? 'active' : ''; ?>" href="?view=campaigns">
                            <i class="fas fa-envelope me-1"></i> Campaigns
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo $currentView == 'create' || ($currentView == 'edit' && $campaignId > 0) ? 'active' : ''; ?>" href="?view=create">
                            <i class="fas fa-plus me-1"></i> Create Campaign
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo $currentView == 'stats' ? 'active' : ''; ?>" href="?view=stats">
                            <i class="fas fa-chart-bar me-1"></i> Statistics
                        </a>
                    </li>
                </ul>
                
                <!-- Alert Messages -->
                <?php if (isset($_SESSION['campaign_message'])): ?>
                <div class="alert alert-<?php echo $_SESSION['campaign_message']['type']; ?> alert-dismissible fade show" role="alert">
                    <?php echo $_SESSION['campaign_message']['text']; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php 
                    // Clear the message so it doesn't show again on refresh
                    unset($_SESSION['campaign_message']);
                ?>
                <?php endif; ?>
                
                <?php if (isset($_SESSION['email_action']) && $_SESSION['email_action']['status'] != 'pending'): ?>
                <div class="alert alert-<?php echo $_SESSION['email_action']['status'] == 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                    <?php echo $_SESSION['email_action']['text']; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php 
                    // Clear the notification so it doesn't show again on refresh
                    unset($_SESSION['email_action']);
                ?>
                <?php endif; ?>
                <!-- Main Content Area - Changes based on view -->
                <?php if ($currentView == 'campaigns'): ?>
                <!-- Campaigns List View -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-envelope me-2"></i> Email Campaigns</h5>
                        <a href="?view=create" class="btn btn-sm btn-light">
                            <i class="fas fa-plus me-1"></i> New Campaign
                        </a>
                    </div>
                    <div class="card-body">
                        <?php
                        $campaigns = getAllEmailCampaigns();
                        if (empty($campaigns)): 
                        ?>
                            <div class="text-center py-5">
                                <i class="fas fa-envelope-open text-muted" style="font-size: 4rem;"></i>
                                <h5 class="mt-3">No campaigns yet</h5>
                                <p class="text-muted">Create your first email campaign to get started</p>
                                <a href="?view=create" class="btn btn-primary mt-2">
                                    <i class="fas fa-plus me-1"></i> Create Campaign
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="campaign-list">
                                <?php foreach ($campaigns as $campaign): ?>
                                <div class="campaign-list-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h5 class="campaign-title"><?php echo htmlspecialchars($campaign['name']); ?></h5>
                                            <p class="campaign-subject mb-1">
                                                <strong>Subject:</strong> <?php echo htmlspecialchars($campaign['subject']); ?>
                                            </p>
                                            <div class="campaign-meta">
                                                <span><i class="far fa-calendar me-1"></i> <?php echo date('M d, Y', strtotime($campaign['created_at'])); ?></span>
                                                <span class="ms-3"><i class="far fa-user me-1"></i> <?php echo htmlspecialchars($campaign['created_by_name']); ?></span>
                                                <span class="ms-3"><i class="far fa-envelope me-1"></i> <?php echo intval($campaign['sent_count']); ?> sent</span>
                                            </div>
                                        </div>
                                        <div>
                                            <span class="badge bg-<?php echo $campaign['status'] == 'sent' ? 'success' : 'secondary'; ?> campaign-badge">
                                                <?php echo ucfirst($campaign['status']); ?>
                                            </span>
                                            <div class="campaign-actions mt-2">
                                                <a href="?view=edit&campaign_id=<?php echo $campaign['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <?php if ($campaign['status'] != 'sent'): ?>
                                                <a href="?view=send&campaign_id=<?php echo $campaign['id']; ?>" class="btn btn-sm btn-outline-success">
                                                    <i class="fas fa-paper-plane"></i>
                                                </a>
                                                <?php endif; ?>
                                                <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this campaign?')">
                                                    <input type="hidden" name="campaign_id" value="<?php echo $campaign['id']; ?>">
                                                    <button type="submit" name="delete_campaign" class="btn btn-sm btn-outline-danger">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php elseif ($currentView == 'create' || $currentView == 'edit'): ?>
                <!-- Create/Edit Campaign Form -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-<?php echo $currentView == 'create' ? 'plus' : 'edit'; ?> me-2"></i>
                            <?php echo $currentView == 'create' ? 'Create New Campaign' : 'Edit Campaign'; ?>
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="post" id="campaign-form">
                            <?php if ($currentView == 'edit' && $campaign): ?>
                            <input type="hidden" name="campaign_id" value="<?php echo $campaign['id']; ?>">
                            <?php endif; ?>
                            
                            <div class="mb-3">
                                <label for="campaign_name" class="form-label">Campaign Name</label>
                                <input type="text" class="form-control" id="campaign_name" name="campaign_name" 
                                       value="<?php echo $currentView == 'edit' && $campaign ? htmlspecialchars($campaign['name']) : ''; ?>" required>
                                <div class="help-text">Internal name to identify this campaign</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="campaign_subject" class="form-label">Email Subject</label>
                                <input type="text" class="form-control" id="campaign_subject" name="campaign_subject" 
                                       value="<?php echo $currentView == 'edit' && $campaign ? htmlspecialchars($campaign['subject']) : ''; ?>" required>
                                <div class="help-text">Subject line recipients will see in their inbox</div>
                            </div>
                            
                            <!-- Available Variables Section -->
                            <div class="variable-section mb-4">
                                <h6><i class="fas fa-code me-1"></i> Available Template Variables</h6>
                                <p class="small text-muted">Click on a variable to insert it into the email template</p>
                                
                                <ul class="nav nav-tabs" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" id="user-tab" data-bs-toggle="tab" data-bs-target="#user-variables" type="button" role="tab">User Variables</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="abstract-tab" data-bs-toggle="tab" data-bs-target="#abstract-variables" type="button" role="tab">Abstract Variables</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="category-tab" data-bs-toggle="tab" data-bs-target="#category-variables" type="button" role="tab">Category Variables</button>
                                    </li>
                                </ul>
                                
                                <div class="tab-content pt-3">
                                    <div class="tab-pane fade show active" id="user-variables" role="tabpanel">
                                        <?php foreach (getAvailableDatabaseVariables()['tusuario'] as $field): ?>
                                        <span class="variable-tag" onclick="insertVariable('tusuario.<?php echo $field; ?>')">
                                            $tusuario.<?php echo $field; ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="tab-pane fade" id="abstract-variables" role="tabpanel">
                                        <?php foreach (getAvailableDatabaseVariables()['ttrabajo'] as $field): ?>
                                        <span class="variable-tag" onclick="insertVariable('ttrabajo.<?php echo $field; ?>')">
                                            $ttrabajo.<?php echo $field; ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="tab-pane fade" id="category-variables" role="tabpanel">
                                        <?php foreach (getAvailableDatabaseVariables()['ttipo_competicion'] as $field): ?>
                                        <span class="variable-tag" onclick="insertVariable('ttipo_competicion.<?php echo $field; ?>')">
                                            ttipo_competicion.<?php echo $field; ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="campaign_content" class="form-label">Email Content</label>
                                <div class="summernote-container">
                                    <textarea id="campaign_content" name="campaign_content" class="summernote"><?php echo $currentView == 'edit' && $campaign ? $campaign['content'] : ''; ?></textarea>
                                </div>
                                <div class="help-text">
                                    Use the editor to format your email. Click on variables above to include them in your template.
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between">
                                <a href="?view=campaigns" class="btn btn-light">Cancel</a>
                                <button type="submit" name="save_campaign" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> 
                                    <?php echo $currentView == 'create' ? 'Create Campaign' : 'Update Campaign'; ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php elseif ($currentView == 'send' && $campaign): ?>
                <!-- Send Campaign View -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-paper-plane me-2"></i> Send Campaign: <?php echo htmlspecialchars($campaign['name']); ?></h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-4">
                            <h6 class="form-title">Campaign Details</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Name:</strong> <?php echo htmlspecialchars($campaign['name']); ?></p>
                                    <p><strong>Subject:</strong> <?php echo htmlspecialchars($campaign['subject']); ?></p>
                                    <p><strong>Status:</strong> 
                                        <span class="badge bg-<?php echo $campaign['status'] == 'sent' ? 'success' : 'secondary'; ?>">
                                            <?php echo ucfirst($campaign['status']); ?>
                                        </span>
                                    </p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Created:</strong> <?php echo date('M d, Y', strtotime($campaign['created_at'])); ?></p>
                                    <?php if (isset($campaign['sent_at']) && $campaign['sent_at']): ?>
                                    <p><strong>Last Sent:</strong> <?php echo date('M d, Y H:i', strtotime($campaign['sent_at'])); ?></p>
                                    <?php endif; ?>
                                    <p><strong>Preview:</strong> 
                                        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#previewModal">
                                            <i class="fas fa-eye me-1"></i> View Template
                                        </button>
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <form method="post" id="send-campaign-form">
                            <input type="hidden" name="campaign_id" value="<?php echo $campaign['id']; ?>">
                            
                            <h6 class="form-title">Select Recipients</h6>
                            
                            <div class="action-bar">
                                <div class="select-controls">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="select-all">
                                        <label class="form-check-label" for="select-all">Select All</label>
                                    </div>
                                </div>
                                <button type="submit" name="send_campaign" class="btn btn-success">
                                    <i class="fas fa-paper-plane me-1"></i> Send to Selected
                                </button>
                            </div>
                            
                            <div class="table-container">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th width="40px">
                                                <i class="fas fa-check-square"></i>
                                            </th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Username</th>
                                            <th>Last Email Sent</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        // Get evaluators list
                                        $conn = Activarmysql();
                                        $query = "SELECT id, nombre, correo, usuario FROM tusuario WHERE tipousuario in ('S','A','E')";
                                        $result = $conn->query($query);
                                        
                                        if ($result && $result->num_rows > 0) {
                                            while ($row = $result->fetch_assoc()) {
                                                // Get last email sent date for this campaign
                                                $stmt = $conn->prepare("SELECT MAX(action_date) as last_sent FROM email_campaign_stats 
                                                                      WHERE evaluator_id = ? AND campaign_id = ? AND action_type = 'sent'");
                                                $stmt->bind_param("ii", $row['id'], $campaign['id']);
                                                $stmt->execute();
                                                $lastSentResult = $stmt->get_result();
                                                $lastSentRow = $lastSentResult->fetch_assoc();
                                                $lastSent = $lastSentRow['last_sent'] ? date('M d, Y H:i', strtotime($lastSentRow['last_sent'])) : 'Never';
                                                
                                                echo "<tr>";
                                                echo "<td>
                                                        <div class='form-check'>
                                                            <input class='form-check-input' type='checkbox' name='selected_evaluators[]' value='" . $row['id'] . "'>
                                                        </div>
                                                      </td>";
                                                echo "<td>" . htmlspecialchars($row['nombre']) . "</td>";
                                                echo "<td>" . htmlspecialchars($row['correo']) . "</td>";
                                                echo "<td>" . htmlspecialchars($row['usuario']) . "</td>";
                                                echo "<td>" . $lastSent . "</td>";
                                                echo "<td>
                                                        <form method='post'>
                                                            <input type='hidden' name='evaluator_id' value='" . $row['id'] . "'>
                                                            <input type='hidden' name='campaign_id' value='" . $campaign['id'] . "'>
                                                            <button type='submit' name='resend' class='btn btn-sm btn-primary'>
                                                                <i class='fas fa-envelope me-1'></i> Send
                                                            </button>
                                                        </form>
                                                      </td>";
                                                echo "</tr>";
                                            }
                                        } else {
                                            echo "<tr><td colspan='6' class='text-center'>No evaluators found</td></tr>";
                                        }
                                        $conn->close();
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Email Preview Modal -->
                <div class="modal fade" id="previewModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Email Template Preview</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="template-preview">
                                    <?php echo $campaign['content']; ?>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php elseif ($currentView == 'stats'): ?>
                <!-- Statistics View -->
                <div class="row">
                    <?php 
                    // Get email statistics
                    $stats = getEmailStatistics();
                    ?>
                 <div class="row">
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-paper-plane stat-icon sent-icon"></i>
                        <h5 class="card-title">Emails Sent</h5>
                        <p class="stat-value"><?php echo $stats['sent']; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-envelope-open stat-icon opened-icon"></i>
                        <h5 class="card-title">Emails Opened</h5>
                        <p class="stat-value"><?php echo $stats['opened']; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-times-circle stat-icon rejected-icon"></i>
                        <h5 class="card-title">Rejections</h5>
                        <p class="stat-value"><?php echo $stats['rejected']; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="fas fa-exclamation-triangle stat-icon bounced-icon"></i>
                        <h5 class="card-title">Bounces</h5>
                        <p class="stat-value"><?php echo $stats['bounced']; ?></p>
                    </div>
                </div>
            </div>
        </div>
                
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i> Campaign Performance</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-container">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Campaign</th>
                                        <th>Sent Date</th>
                                        <th>Recipients</th>
                                        <th>Opens</th>
                                        <th>Open Rate</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $campaigns = getAllEmailCampaigns();
                                    if (!empty($campaigns)) {
                                        foreach ($campaigns as $campaign) {
                                            $stats = getCampaignStatistics($campaign['id']);
                                            $openRate = $stats['sent'] > 0 ? round(($stats['opened'] / $stats['sent']) * 100, 1) : 0;
                                            
                                            echo "<tr>";
                                            echo "<td>" . htmlspecialchars($campaign['name']) . "</td>";
                                            echo "<td>" . ($campaign['status'] == 'sent' ? date('M d, Y', strtotime($campaign['created_at'])) : 'Not sent') . "</td>";
                                            echo "<td>" . $stats['sent'] . "</td>";
                                            echo "<td>" . $stats['opened'] . "</td>";
                                            echo "<td>" . $openRate . "%</td>";
                                            echo "<td>";
                                            echo "<span class='badge bg-" . ($campaign['status'] == 'sent' ? 'success' : 'secondary') . "'>";
                                            echo ucfirst($campaign['status']);
                                            echo "</span>";
                                            echo "</td>";
                                            echo "</tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='6' class='text-center'>No campaigns found</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Summernote WYSIWYG editor
        $('.summernote').summernote({
            height: 350,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'underline', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });
        
        // Toggle select all checkboxes
        $('#select-all').change(function() {
            const isChecked = this.checked;
            $('input[name="selected_evaluators[]"]').prop('checked', isChecked);
        });
        
        // Check if any notification toasts need to be shown
        showNotifications();
    });
    
    // Function to insert template variables into the editor
    function insertVariable(variable) {
        $('.summernote').summernote('insertText', '$' + variable);
    }
    
    // Function to show toast notifications
    function showNotifications() {
        <?php
        // Check if we have a notification to show
        if (isset($_SESSION['email_action']) && $_SESSION['email_action']['status'] != 'pending') {
            echo "
                // Use Bootstrap toast or alert
                if (typeof bootstrap !== 'undefined') {
                    const toastContainer = document.createElement('div');
                    toastContainer.className = 'toast-container';
                    
                    const toastElement = document.createElement('div');
                    toastElement.className = 'toast align-items-center text-white bg-" 
                        . ($_SESSION['email_action']['status'] == 'success' ? 'success' : 'danger') . "';
                    toastElement.setAttribute('role', 'alert');
                    toastElement.setAttribute('aria-live', 'assertive');
                    toastElement.setAttribute('aria-atomic', 'true');
                    
                    toastElement.innerHTML = `
                        <div class='d-flex'>
                            <div class='toast-body'>
                                <i class='fas fa-" . ($_SESSION['email_action']['status'] == 'success' ? 'check-circle' : 'exclamation-circle') . " me-2'></i>
                                " . $_SESSION['email_action']['text'] . "
                            </div>
                            <button type='button' class='btn-close btn-close-white me-2 m-auto' data-bs-dismiss='toast' aria-label='Close'></button>
                        </div>
                    `;
                    
                    document.body.appendChild(toastContainer);
                    toastContainer.appendChild(toastElement);
                    
                    const toast = new bootstrap.Toast(toastElement, {
                        autohide: true,
                        delay: 5000
                    });
                    toast.show();
                } else {
                    // Fallback to alert if Bootstrap is not available
                    alert('" . $_SESSION['email_action']['text'] . "');
                }
            ";
            
            // Clear the notification so it doesn't show again on refresh
            unset($_SESSION['email_action']);
        }
        ?>
    }
    
    // Preview email before sending
    function previewEmail(content) {
        $('#emailPreview').html(content);
        $('#previewModal').modal('show');
    }
    </script>
    <style>
        .card {
            transition: transform 0.3s;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
        }
        .stat-value {
            font-size: 2rem;
            font-weight: bold;
        }
        .sent-icon { color: #4CAF50; }
        .opened-icon { color: #2196F3; }
        .rejected-icon { color: #F44336; }
        .bounced-icon { color: #FF9800; }
        .navbar {
            background-color: #003366 !important;
        }
        .table-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        .avatar-small {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f1f1f1;
        }
        .avatar-placeholder {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 18px;
        }
        /* Toast notification styles */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
        }
        .toast {
            min-width: 300px;
        }
        .action-bar {
            background-color: #f8f9fa;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .select-controls {
            display: flex;
            gap: 10px;
        }
    </style>
    <!-- Database Setup Script -->
    <script>
    /*
    CREATE TABLE IF NOT EXISTS `email_campaigns` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) NOT NULL,
      `subject` varchar(255) NOT NULL,
      `content` text NOT NULL,
      `status` enum('draft','sent') NOT NULL DEFAULT 'draft',
      `created_by` int(11) NOT NULL,
      `created_at` datetime NOT NULL,
      `updated_at` datetime DEFAULT NULL,
      `sent_at` datetime DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `created_by` (`created_by`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

    CREATE TABLE IF NOT EXISTS `email_campaign_stats` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `campaign_id` int(11) NOT NULL,
      `evaluator_id` int(11) NOT NULL,
      `action_type` enum('sent','opened','rejected','bounced') NOT NULL,
      `action_date` datetime NOT NULL,
      PRIMARY KEY (`id`),
      KEY `campaign_id` (`campaign_id`),
      KEY `evaluator_id` (`evaluator_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

    ALTER TABLE `email_campaign_stats`
      ADD CONSTRAINT `email_campaign_stats_ibfk_1` FOREIGN KEY (`campaign_id`) REFERENCES `email_campaigns` (`id`) ON DELETE CASCADE,
      ADD CONSTRAINT `email_campaign_stats_ibfk_2` FOREIGN KEY (`evaluator_id`) REFERENCES `tusuario` (`id`) ON DELETE CASCADE;
    */
    </script>
</body>
</html>