<?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
}
?>
<?php

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

// Statistics tracking functions
function registerEmailSent($evaluatorId) {
    $conn = Activarmysql();
    $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;
}

// Email sending function with HTML template
function sendEvaluatorInvitation($evaluatorId) {
    $conn = Activarmysql();
    
    // Get evaluator data
    $stmt = $conn->prepare("SELECT nombre, usuario, contrasena, correo, avatar FROM tusuario WHERE id = ?");
    $stmt->bind_param("i", $evaluatorId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $nombre = $row['nombre'];
        $usuario = $row['usuario'];
        $contrasena = $row['contrasena'];
        $correo = $row['correo'];
        $avatar = $row['avatar'];
        
        // Build email HTML content
        $emailContent = generateEmailTemplate($nombre, $usuario, $contrasena, $avatar);
        
        // 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
        $subject = "Abstract Evaluation Instructions – XXXVII Panamerican Congress of Trauma";
        $mailSent = mail($correo, $subject, $emailContent, $headers);
        
        if ($mailSent) {
            registerEmailSent($evaluatorId);
            return true;
        }
    }
    
    $stmt->close();
    $conn->close();
    return false;
}

// Manage email resending
function resendInvitation($evaluatorId) {
    return sendEvaluatorInvitation($evaluatorId);
}

// Send emails to multiple evaluators
function sendBatchEmails($evaluatorIds) {
    $successCount = 0;
    $failCount = 0;
    
    foreach ($evaluatorIds as $evaluatorId) {
        $result = sendEvaluatorInvitation($evaluatorId);
        if ($result) {
            $successCount++;
        } else {
            $failCount++;
        }
    }
    
    return [
        'success' => $successCount,
        'failed' => $failCount,
        'total' => count($evaluatorIds)
    ];
}

// IMPORTANT: Process email resending before any HTML output
// Single email sending
if (isset($_POST['resend']) && isset($_POST['evaluator_id'])) {
    $evaluatorId = $_POST['evaluator_id'];
    
    // Store the action temporarily in the session
    $_SESSION['email_action'] = array(
        'status' => 'pending',
        'evaluator_id' => $evaluatorId,
        'type' => 'single'
    );
    
    // Send the email
    $result = resendInvitation($evaluatorId);
    
    if ($result) {
        $_SESSION['email_action']['status'] = 'success';
    } else {
        $_SESSION['email_action']['status'] = 'failure';
    }
    
    // Redirect to the same page but without POST data to prevent resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Batch email sending
if (isset($_POST['send_selected']) && isset($_POST['selected_evaluators']) && is_array($_POST['selected_evaluators'])) {
    $selectedEvaluators = $_POST['selected_evaluators'];
    
    if (empty($selectedEvaluators)) {
        $_SESSION['email_action'] = array(
            'status' => 'no_selection',
            'type' => 'batch'
        );
    } else {
        // Store the action temporarily in the session
        $_SESSION['email_action'] = array(
            'status' => 'pending',
            'type' => 'batch'
        );
        
        // Send emails to all selected evaluators
        $result = sendBatchEmails($selectedEvaluators);
        
        $_SESSION['email_action']['status'] = 'completed';
        $_SESSION['email_action']['result'] = $result;
    }
    
    // Redirect to the same page but without POST data to prevent resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Generate HTML email template
function generateEmailTemplate($nombre, $usuario, $contrasena, $avatar) {
    $avatarPath = "dist/pages/evaluadores/acciones_evaluador/fotos_empleados/" . $avatar;
    
    $template = '
    <!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>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
        <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;
            }
            .logo-icon {
                font-size: 48px;
                color: white;
                margin-bottom: 10px;
            }
            .avatar {
                width: 80px;
                height: 80px;
                border-radius: 50%;
                object-fit: cover;
                margin: 0 auto 10px;
                display: block;
                border: 3px solid #f1f1f1;
            }
            .greeting {
                font-weight: bold;
                font-size: 18px;
                margin-bottom: 15px;
            }
            .content {
                padding: 0 20px;
            }
            .instructions {
                background-color: #f9f9f9;
                padding: 15px;
                border-radius: 5px;
                margin: 20px 0;
            }
            .instructions ol {
                margin-left: 20px;
                padding-left: 0;
            }
            .instructions li {
                margin-bottom: 10px;
            }
            .credentials {
                background-color: #eef5ff;
                padding: 10px 15px;
                border-left: 4px solid #427d6e;
                margin: 10px 0;
            }
            .footer {
                text-align: center;
                padding: 20px 0;
                font-size: 12px;
                color: #666;
                border-top: 1px solid #eee;
                margin-top: 20px;
            }
            .highlight {
                font-weight: bold;
                color: #003366;
            }
            .button {
                display: inline-block;
                padding: 10px 20px;
                background-color: #427d6e;
                color: white;
                text-decoration: none;
                border-radius: 4px;
                margin: 15px 0;
                text-align: center;
            }
            .language-separator {
                border-top: 1px dashed #ccc;
                margin: 30px 0;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <i class="fas fa-hospital-user logo-icon"></i>
                <h2>XXXVII Panamerican Congress of Trauma</h2>
            </div>
            
            <div class="content">
                
                <!-- ENGLISH VERSION -->
                <p><strong>***ENGLISH***</strong><br>
                <em>Por favor vea mensaje en Español debajo de la versión de Ingles.</em></p>
                
                <p class="greeting">Dear ' . $nombre . ',</p>
                
                <p>Thank you once again for supporting the Panamerican Trauma Society\'s (PTS) call for abstracts for the upcoming <span class="highlight">XXXVII Panamerican Congress of Trauma, Critical Care, and Emergency Surgery on May 21–24, 2025 in Cuenca, Ecuador.</span></p>
                
                <p>The abstract evaluation period will be open from February 12–28, 2025. Please follow the instructions below to begin reviewing the abstracts assigned to you:</p>
                
                <div class="instructions">
                    <ol>
                        <li>Click on the following link to access the abstract evaluation platform: 
                            <a href="https://panamtrauma.site/trauma2025/Administrador/login.php" class="button">Access Evaluation Platform</a>
                        </li>
                        <li>Log in using the credentials provided:
                            <div class="credentials">
                                <p>Username: <strong>' . $usuario . '</strong><br>
                                Password: <strong>' . $contrasena . '</strong></p>
                            </div>
                        </li>
                        <li>Once logged in, click on the "+" symbol to view the abstracts assigned to you.</li>
                        <li><strong>Conflict of Interest:</strong> If you are a co-author of an abstract, please refrain from evaluating it. Notify us immediately so we can reassign it to another evaluator, ensuring transparency in the review process.</li>
                        <li><strong>Evaluation Deadline:</strong> Kindly complete all assigned evaluations by February 28, 2025.</li>
                    </ol>
                </div>
                
                <p>We sincerely appreciate your time and expertise in this process. If you experience any technical issues or need assistance accessing the evaluation system, please contact Eliasib Julio at <a href="mailto:eliasibjuliogarcia@gmail.com">eliasibjuliogarcia@gmail.com</a>, and we will be happy to assist you.</p>
                
                <p>Thank you for your valuable contribution!</p>
                
                <p>Best regards,<br>
                Program Committee<br>
                Panamerican Trauma Society HQ office</p>
                
                <div class="language-separator"></div>
                
                <!-- SPANISH VERSION -->
                <p><strong>***ESPAÑOL***</strong></p>
                <p><strong>Referencia:</strong> Instrucciones para la evaluación de resúmenes – XXXVII Congreso Panamericano de Trauma</p>
                
                <p class="greeting">Estimado Dr. ' . $nombre . ',</p>
                
                <p>Gracias una vez más por apoyar a la convocatoria de resúmenes de la Sociedad Panamericana de Trauma (STP) para el próximo <span class="highlight">XXXVII Congreso Panamericano de Trauma, Cuidados Intensivos y Cirugía de Emergencia</span>, que se realizará del <span class="highlight">21 al 24 de mayo, 2025</span> en <span class="highlight">Cuenca, Ecuador</span>.</p>
                
                <p><strong>El período de evaluación de resúmenes estará abierto del 12 al 28 de febrero de 2025</strong>. Por favor siga las instrucciones a continuación para comenzar a revisar los resúmenes asignados a usted:</p>
                
                <div class="instructions">
                    <ol>
                        <li>Haga clic en el siguiente <strong>enlace para acceder a la plataforma de evaluación de resúmenes</strong>: 
                            <a href="https://panamtrauma.site/trauma2025/Administrador/login.php" class="button">Acceder a la Plataforma</a>
                        </li>
                        <li><strong>Inicie sesión con las credenciales proporcionadas</strong>:
                            <div class="credentials">
                                <p>Nombre de usuario: <strong>' . $usuario . '</strong><br>
                                Contraseña: <strong>' . $contrasena . '</strong></p>
                            </div>
                        </li>
                        <li>Una vez que haya iniciado sesión, haga clic en el símbolo "+" para ver los resúmenes que se le asignaron.</li>
                        <li><strong>Conflicto de intereses</strong>: si es coautor de un resumen, absténgase de evaluarlo. Notificarnos de inmediato para que podamos reasignarlo a otro evaluador, asegurando la transparencia en el proceso de revisión.</li>
                        <li><strong>Fecha límite de evaluación</strong>: Por favor complete todas las evaluaciones asignadas hasta el 28 de febrero de 2025.</li>
                    </ol>
                </div>
                
                <p>Agradecemos sinceramente su tiempo y experiencia en este proceso. Si experimenta algún problema técnico o necesita ayuda para acceder al sistema de evaluación, comuníquese con Eliasib Julio al email: <a href="mailto:eliasibjuliogarcia@gmail.com">eliasibjuliogarcia@gmail.com</a> estaremos encantados de ayudarlo.</p>
                
                <p>¡Gracias por su valiosa contribución!</p>
                
                <p>Atentamente,<br>
                Comité de Programa<br>
                Oficina central de la SPT</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>
    ';
    
    return $template;
}

?>

<!-- Statistics Dashboard Page -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Statistics Dashboard</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">
    <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>
    <!-- Add this JavaScript to handle notifications without causing form resubmission -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Function to toggle select all checkboxes
        document.getElementById('select-all').addEventListener('change', function() {
            const isChecked = this.checked;
            document.querySelectorAll('input[name="selected_evaluators[]"]').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
        });
        
        <?php
        // Check if we have a notification to show
        if (isset($_SESSION['email_action']) && $_SESSION['email_action']['status'] != 'pending') {
            if ($_SESSION['email_action']['type'] == 'single') {
                // Single email notification
                if ($_SESSION['email_action']['status'] == 'success') {
                    echo "
                        // Use Bootstrap toast if available, or fallback to alert
                        if (typeof bootstrap !== 'undefined') {
                            // Create toast element
                            const toastContainer = document.createElement('div');
                            toastContainer.className = 'toast-container';
                            
                            const toastElement = document.createElement('div');
                            toastElement.className = 'toast align-items-center text-white bg-success';
                            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-check-circle me-2'></i>
                                        Invitation email sent successfully!
                                    </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: 3000
                            });
                            toast.show();
                        } else {
                            // Fallback to alert if Bootstrap is not available
                            alert('Invitation email sent successfully!');
                        }
                    ";
                } else {
                    echo "
                        // Similar code for failure notification but with different styling
                        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-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-exclamation-circle me-2'></i>
                                        Failed to send invitation email. Please try again.
                                    </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: 3000
                            });
                            toast.show();
                        } else {
                            alert('Failed to send invitation email. Please try again.');
                        }
                    ";
                }
            } else if ($_SESSION['email_action']['type'] == 'batch') {
                // Batch email notification
                if ($_SESSION['email_action']['status'] == 'no_selection') {
                    echo "
                        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-warning';
                            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-exclamation-triangle me-2'></i>
                                        No evaluators selected. Please select at least one evaluator.
                                    </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: 3000
                            });
                            toast.show();
                        } else {
                            alert('No evaluators selected. Please select at least one evaluator.');
                        }
                    ";
                } else if ($_SESSION['email_action']['status'] == 'completed') {
                    $result = $_SESSION['email_action']['result'];
                    echo "
                        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 " . ($result['failed'] == 0 ? "bg-success" : "bg-warning") . "';
                            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 " . ($result['failed'] == 0 ? "fa-check-circle" : "fa-exclamation-triangle") . " me-2'></i>
                                        Batch email results: " . $result['success'] . " sent successfully, " . $result['failed'] . " failed out of " . $result['total'] . " total
                                    </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 {
                            alert('Batch email results: " . $result['success'] . " sent successfully, " . $result['failed'] . " failed out of " . $result['total'] . " total');
                        }
                    ";
                }
            }
            
            // Clear the notification so it doesn't show again on refresh
            unset($_SESSION['email_action']);
        }
        ?>
    });
    </script>
</head>
<body class="bg-light">
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-hospital-user me-2"></i>
                Evaluator Email System
            </a>
        </div>
    </nav>

    <div class="container">
        <div class="row mb-4">
            <div class="col">
                <h2>Email Statistics Dashboard</h2>
                <p class="text-muted">Track all evaluator invitation emails</p>
            </div>
        </div>

        <?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="row mt-4">
            <div class="col">
                <div class="table-container">
                    <h4 class="mb-3">Evaluator List</h4>
                    
                    <form method="post" id="evaluator-form">
                        <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_selected" class="btn btn-success">
                                <i class="fas fa-paper-plane me-1"></i> Send to Selected
                            </button>
                        </div>
                    
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th width="40px">
                                        <i class="fas fa-check-square"></i>
                                    </th>
                                    <th>Avatar</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, avatar 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
                                        $stmt = $conn->prepare("SELECT MAX(action_date) as last_sent FROM email_statistics WHERE evaluator_id = ? AND action_type = 'sent'");
                                        $stmt->bind_param("i", $row['id']);
                                        $stmt->execute();
                                        $lastSentResult = $stmt->get_result();
                                        $lastSentRow = $lastSentResult->fetch_assoc();
                                        $lastSent = $lastSentRow['last_sent'] ? $lastSentRow['last_sent'] : 'Never';
                                        
                                        // Avatar display
                                        $avatarDisplay = '';
                                        if (!empty($row['avatar'])) {
                                            $avatarPath = "dist/pages/evaluadores/acciones_evaluador/fotos_empleados/" . $row['avatar'];
                                            $avatarDisplay = "<img src='{$avatarPath}' alt='{$row['nombre']}' class='avatar-small'>";
                                        } else {
                                            $initials = substr($row['nombre'], 0, 1);
                                            $avatarDisplay = "<div class='avatar-placeholder'><i class='fas fa-user'></i></div>";
                                        }
                                        
                                        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>" . $avatarDisplay . "</td>";
                                        echo "<td>" . $row['nombre'] . "</td>";
                                        echo "<td>" . $row['correo'] . "</td>";
                                        echo "<td>" . $row['usuario'] . "</td>";
                                        echo "<td>" . $lastSent . "</td>";
                                        echo "<td>
                                                <form method='post'>
                                                    <input type='hidden' name='evaluator_id' value='" . $row['id'] . "'>
                                                    <button type='submit' name='resend' class='btn btn-sm btn-primary'>
                                                        <i class='fas fa-envelope me-1'></i> Send Email
                                                    </button>
                                                </form>
                                              </td>";
                                        echo "</tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='7' class='text-center'>No evaluators found</td></tr>";
                                }
                                $conn->close();
                                ?>
                            </tbody>
                        </table>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

