Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/email/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/email/index.php

<?php
require_once '../../config/config.php';
checkLogin();

// Only superusers and area/district/assembly level users can access
if (!isSuperuser() && !in_array(getAccessLevel(), ['area', 'district', 'assembly'])) {
    redirect('../../dashboard.php');
}

$pageTitle = "Email Management - " . APP_NAME;
$db = Database::getInstance()->getConnection();
$success = '';
$error = '';

// Get current email settings
$stmt = $db->query("SELECT * FROM email_settings ORDER BY id DESC LIMIT 1");
$emailSettings = $stmt->fetch();

// If no settings exist, create default settings
if (!$emailSettings) {
    $db->exec("INSERT INTO email_settings (smtp_host, smtp_port, from_email, from_name) VALUES ('localhost', 587, 'noreply@localhost', 'Church Management System')");
    $emailSettings = $db->query("SELECT * FROM email_settings ORDER BY id DESC LIMIT 1")->fetch();
}

// Ensure all keys have default values
$emailSettings = array_merge([
    'id' => 1,
    'smtp_host' => 'localhost',
    'smtp_port' => 587,
    'smtp_username' => '',
    'smtp_password' => '',
    'smtp_encryption' => 'tls',
    'from_email' => 'noreply@localhost',
    'from_name' => 'Church Management System',
    'send_welcome_user' => 1,
    'send_welcome_member' => 1,
    'user_welcome_subject' => 'Welcome to our Church Management System',
    'user_welcome_template' => '<h2>Welcome!</h2><p>Dear {name}, your account has been created.</p>',
    'member_welcome_subject' => 'Welcome to our Church Community',
    'member_welcome_template' => '<h2>Welcome!</h2><p>Dear {name}, welcome to our church community!</p>',
    'is_enabled' => 0
], $emailSettings ?: []);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_settings'])) {
        try {
            $stmt = $db->prepare("
                UPDATE email_settings 
                SET smtp_host = :smtp_host,
                    smtp_port = :smtp_port,
                    smtp_username = :smtp_username,
                    smtp_password = :smtp_password,
                    smtp_encryption = :smtp_encryption,
                    from_email = :from_email,
                    from_name = :from_name,
                    send_welcome_user = :send_welcome_user,
                    send_welcome_member = :send_welcome_member,
                    user_welcome_subject = :user_welcome_subject,
                    user_welcome_template = :user_welcome_template,
                    member_welcome_subject = :member_welcome_subject,
                    member_welcome_template = :member_welcome_template,
                    is_enabled = :is_enabled
                WHERE id = :id
            ");
            
            $stmt->execute([
                'smtp_host' => $_POST['smtp_host'] ?? 'localhost',
                'smtp_port' => $_POST['smtp_port'] ?? 587,
                'smtp_username' => $_POST['smtp_username'] ?? '',
                'smtp_password' => $_POST['smtp_password'] ?? '',
                'smtp_encryption' => $_POST['smtp_encryption'] ?? 'tls',
                'from_email' => $_POST['from_email'] ?? 'noreply@localhost',
                'from_name' => $_POST['from_name'] ?? 'Church Management System',
                'send_welcome_user' => isset($_POST['send_welcome_user']) ? 1 : 0,
                'send_welcome_member' => isset($_POST['send_welcome_member']) ? 1 : 0,
                'user_welcome_subject' => $_POST['user_welcome_subject'] ?? 'Welcome',
                'user_welcome_template' => $_POST['user_welcome_template'] ?? '',
                'member_welcome_subject' => $_POST['member_welcome_subject'] ?? 'Welcome',
                'member_welcome_template' => $_POST['member_welcome_template'] ?? '',
                'is_enabled' => isset($_POST['is_enabled']) ? 1 : 0,
                'id' => $emailSettings['id']
            ]);
            
            $auditLog = new AuditLog();
            $auditLog->log($_SESSION['user_id'], 'update', 'email_settings', $emailSettings['id']);
            
            $success = "Email settings updated successfully!";
            
            // Refresh settings
            $stmt = $db->query("SELECT * FROM email_settings ORDER BY id DESC LIMIT 1");
            $emailSettings = $stmt->fetch();
            
        } catch (Exception $e) {
            $error = "Error updating settings: " . $e->getMessage();
        }
    }
    
    if (isset($_POST['test_email'])) {
        try {
            $testEmail = $_POST['test_email_address'] ?? '';
            if (empty($testEmail)) {
                throw new Exception("Please enter a test email address");
            }
            
            // Add test email to queue
            $stmt = $db->prepare("
                INSERT INTO email_queue (recipient_email, recipient_name, subject, body, email_type) 
                VALUES (:email, :name, :subject, :body, 'general')
            ");
            
            $stmt->execute([
                'email' => $testEmail,
                'name' => 'Test User',
                'subject' => 'Test Email from ' . $emailSettings['from_name'],
                'body' => '<h2>Test Email</h2><p>This is a test email from your Church Management System.</p><p>If you received this email, your email configuration is working correctly!</p>'
            ]);
            
            $success = "Test email queued successfully! Check your email inbox.";
            
        } catch (Exception $e) {
            $error = "Error sending test email: " . $e->getMessage();
        }
    }
    
    // Handle retry single email
    if (isset($_POST['retry_email'])) {
        try {
            $emailId = $_POST['email_id'] ?? 0;
            if ($emailId) {
                require_once '../../classes/EmailService.php';
                $emailService = new EmailService();
                
                if ($emailService->retryEmail($emailId)) {
                    $success = "Email has been reset and will be retried on the next cron run.";
                } else {
                    $error = "Failed to retry email.";
                }
            }
        } catch (Exception $e) {
            $error = "Error retrying email: " . $e->getMessage();
        }
    }
    
    // Handle retry all failed emails
    if (isset($_POST['retry_all_failed'])) {
        try {
            require_once '../../classes/EmailService.php';
            $emailService = new EmailService();
            
            $count = $emailService->retryAllFailed();
            $success = "$count failed email(s) have been reset and will be retried on the next cron run.";
            
        } catch (Exception $e) {
            $error = "Error retrying emails: " . $e->getMessage();
        }
    }
    
    // Handle delete single email
    if (isset($_POST['delete_email'])) {
        try {
            $emailId = $_POST['email_id'] ?? 0;
            if ($emailId) {
                require_once '../../classes/EmailService.php';
                $emailService = new EmailService();
                
                if ($emailService->deleteEmail($emailId)) {
                    $success = "Email deleted successfully.";
                } else {
                    $error = "Failed to delete email.";
                }
            }
        } catch (Exception $e) {
            $error = "Error deleting email: " . $e->getMessage();
        }
    }
    
    // Handle delete all failed emails
    if (isset($_POST['delete_all_failed'])) {
        try {
            require_once '../../classes/EmailService.php';
            $emailService = new EmailService();
            
            $count = $emailService->deleteAllFailed();
            $success = "$count failed email(s) deleted successfully.";
            
        } catch (Exception $e) {
            $error = "Error deleting emails: " . $e->getMessage();
        }
    }
    
    // Handle process pending emails now
    if (isset($_POST['process_pending'])) {
        try {
            require_once '../../classes/EmailService.php';
            $emailService = new EmailService();
            
            if (!$emailService->isEnabled()) {
                $error = "Email system is disabled. Please enable it in settings first.";
            } else {
                $count = $emailService->processPendingEmails(50);
                $success = "$count pending email(s) processed successfully!";
            }
            
        } catch (Exception $e) {
            $error = "Error processing emails: " . $e->getMessage();
        }
    }
}

// Get email queue statistics
$stmt = $db->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
    SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
    FROM email_queue");
$emailStats = $stmt->fetch();

// Get failed emails
require_once '../../classes/EmailService.php';
$emailService = new EmailService();
$failedEmails = $emailService->getFailedEmails(100);
$recentEmails = $emailService->getRecentEmails(20);

include '../../includes/header.php';
?>

<?php include '../../includes/sidebar.php'; ?>

<!-- Main Content -->
<main class="flex-1 md:ml-64 mt-16">
<div class="container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto">
        <div class="mb-6">
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-envelope mr-2 text-blue-500"></i>Email Management
            </h1>
            <p class="text-gray-600 mt-2">Configure email settings and manage automated notifications</p>
        </div>
        
        <?php if ($success): ?>
            <div id="successMessage" class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-6 flex items-center justify-between transition-all duration-300">
                <div>
                    <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                </div>
                <button onclick="dismissMessage('successMessage')" class="text-green-700 hover:text-green-900 ml-4">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div id="errorMessage" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6 flex items-center justify-between transition-all duration-300">
                <div>
                    <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                </div>
                <button onclick="dismissMessage('errorMessage')" class="text-red-700 hover:text-red-900 ml-4">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        <?php endif; ?>
        
        <!-- System Status -->
        <?php 
        // Load composer autoload if needed
        if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
            require_once __DIR__ . '/../../vendor/autoload.php';
        }
        
        $mailerInstalled = class_exists('Symfony\Component\Mailer\Mailer') || 
                          (file_exists(__DIR__ . '/../../vendor/autoload.php') && 
                           file_exists(__DIR__ . '/../../vendor/symfony/mailer'));
        ?>
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h3 class="text-lg font-bold text-gray-800 mb-4">
                <i class="fas fa-cogs mr-2 text-gray-600"></i>System Status
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="flex items-center space-x-3">
                    <div class="flex-shrink-0">
                        <?php if ($emailSettings['is_enabled']): ?>
                            <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                                <i class="fas fa-check text-green-600 text-lg"></i>
                            </div>
                        <?php else: ?>
                            <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                                <i class="fas fa-times text-red-600 text-lg"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <p class="text-sm font-medium text-gray-600">Email System</p>
                        <p class="text-sm font-bold <?php echo $emailSettings['is_enabled'] ? 'text-green-600' : 'text-red-600'; ?>">
                            <?php echo $emailSettings['is_enabled'] ? 'Enabled' : 'Disabled'; ?>
                        </p>
                    </div>
                </div>
                
                <div class="flex items-center space-x-3">
                    <div class="flex-shrink-0">
                        <?php if ($mailerInstalled): ?>
                            <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                                <i class="fas fa-check text-green-600 text-lg"></i>
                            </div>
                        <?php else: ?>
                            <div class="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
                                <i class="fas fa-exclamation text-yellow-600 text-lg"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <p class="text-sm font-medium text-gray-600">Symfony Mailer</p>
                        <p class="text-sm font-bold <?php echo $mailerInstalled ? 'text-green-600' : 'text-yellow-600'; ?>">
                            <?php echo $mailerInstalled ? 'Installed' : 'Simulation Mode'; ?>
                        </p>
                        <?php if (!$mailerInstalled): ?>
                            <p class="text-xs text-gray-600 mt-1">Run: composer install</p>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="flex items-center space-x-3">
                    <div class="flex-shrink-0">
                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                            <i class="fas fa-server text-blue-600 text-lg"></i>
                        </div>
                    </div>
                    <div>
                        <p class="text-sm font-medium text-gray-600">SMTP Host</p>
                        <p class="text-sm font-bold text-gray-800">
                            <?php echo htmlspecialchars($emailSettings['smtp_host'] ?? 'Not configured'); ?>
                        </p>
                    </div>
                </div>
            </div>
            
            <?php if (!$mailerInstalled): ?>
            <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p class="text-sm text-yellow-800">
                    <i class="fas fa-info-circle mr-1"></i>
                    <strong>Symfony Mailer is not installed.</strong> Emails are being simulated (logged but not sent). 
                    To send real emails, run: <code class="bg-yellow-100 px-2 py-1 rounded">composer install</code>
                </p>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Email Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                        <i class="fas fa-envelope text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">Total Emails</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $emailStats['total'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">
                        <i class="fas fa-clock text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">Pending</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $emailStats['pending'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-600">
                        <i class="fas fa-check text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">Sent</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $emailStats['sent'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-red-100 text-red-600">
                        <i class="fas fa-times text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">Failed</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $emailStats['failed'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <?php if ($emailStats['pending'] > 0): ?>
        <div class="bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl shadow-lg p-6 mb-8 text-white">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        You have <?php echo $emailStats['pending']; ?> pending email(s) in the queue
                    </h3>
                    <p class="text-blue-100">These emails are waiting to be sent. Click the button to process them now.</p>
                </div>
                <div class="mt-4 md:mt-0">
                    <form method="POST" class="inline">
                        <button type="submit" name="process_pending" 
                                onclick="return confirm('Process <?php echo $emailStats['pending']; ?> pending email(s) now?')"
                                class="bg-white text-blue-600 px-6 py-3 rounded-lg font-bold hover:bg-blue-50 transition-all duration-300 shadow-lg inline-flex items-center">
                            <i class="fas fa-paper-plane mr-2"></i>
                            Process Now (<?php echo $emailStats['pending']; ?>)
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Cron Job Info -->
        <div class="bg-blue-50 border border-blue-200 rounded-xl p-6 mb-8">
            <h4 class="font-bold text-blue-900 mb-3">
                <i class="fas fa-info-circle mr-2"></i>
                Automated Email Processing
            </h4>
            <p class="text-blue-800 text-sm mb-3">
                For automatic email sending, set up a cron job to run every 5-10 minutes:
            </p>
            <div class="bg-blue-100 p-3 rounded-lg font-mono text-sm text-blue-900 mb-2">
                */5 * * * * php <?php echo realpath(__DIR__ . '/../../cron/process_emails.php'); ?>
            </div>
            <p class="text-blue-800 text-sm">
                Or manually trigger processing: 
                <a href="../../cron/process_emails.php?manual=1" target="_blank" class="underline font-semibold hover:text-blue-600">
                    Run Email Processor
                </a>
            </p>
        </div>
        
        <!-- Email Settings Tabs -->
        <div class="bg-white rounded-xl shadow-lg">
            <div class="border-b border-gray-200">
                <nav class="flex flex-wrap">
                    <button onclick="switchEmailTab('smtp')" class="email-tab px-6 py-4 font-medium border-b-2 border-blue-500 text-blue-600">
                        <i class="fas fa-server mr-2"></i>SMTP Settings
                    </button>
                    <button onclick="switchEmailTab('templates')" class="email-tab px-6 py-4 font-medium text-gray-600 hover:text-blue-600 border-b-2 border-transparent">
                        <i class="fas fa-file-alt mr-2"></i>Email Templates
                    </button>
                    <button onclick="switchEmailTab('queue')" class="email-tab px-6 py-4 font-medium text-gray-600 hover:text-blue-600 border-b-2 border-transparent">
                        <i class="fas fa-list mr-2"></i>Email Queue
                    </button>
                    <button onclick="switchEmailTab('failed')" class="email-tab px-6 py-4 font-medium text-gray-600 hover:text-blue-600 border-b-2 border-transparent">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Failed Emails <?php if(($emailStats['failed'] ?? 0) > 0): ?><span class="ml-1 px-2 py-0.5 bg-red-500 text-white text-xs rounded-full"><?php echo $emailStats['failed']; ?></span><?php endif; ?>
                    </button>
                    <button onclick="switchEmailTab('test')" class="email-tab px-6 py-4 font-medium text-gray-600 hover:text-blue-600 border-b-2 border-transparent">
                        <i class="fas fa-paper-plane mr-2"></i>Test Email
                    </button>
                </nav>
            </div>
            
            <!-- SMTP Settings Tab -->
            <div id="smtpTab" class="email-tab-content p-8">
                <form method="POST" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Enable Email System</label>
                            <label class="flex items-center">
                                <input type="checkbox" name="is_enabled" <?php echo $emailSettings['is_enabled'] ? 'checked' : ''; ?> 
                                       class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                <span class="ml-2 text-sm text-gray-600">Enable email functionality</span>
                            </label>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Host</label>
                            <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($emailSettings['smtp_host']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Port</label>
                            <input type="number" name="smtp_port" value="<?php echo htmlspecialchars($emailSettings['smtp_port']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Encryption</label>
                            <select name="smtp_encryption" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                <option value="none" <?php echo $emailSettings['smtp_encryption'] === 'none' ? 'selected' : ''; ?>>None</option>
                                <option value="tls" <?php echo $emailSettings['smtp_encryption'] === 'tls' ? 'selected' : ''; ?>>TLS</option>
                                <option value="ssl" <?php echo $emailSettings['smtp_encryption'] === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Username</label>
                            <input type="text" name="smtp_username" value="<?php echo htmlspecialchars($emailSettings['smtp_username']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Password</label>
                            <input type="password" name="smtp_password" value="<?php echo htmlspecialchars($emailSettings['smtp_password']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">From Email</label>
                            <input type="email" name="from_email" value="<?php echo htmlspecialchars($emailSettings['from_email']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">From Name</label>
                            <input type="text" name="from_name" value="<?php echo htmlspecialchars($emailSettings['from_name']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" required>
                        </div>
                    </div>
                    
                    <div class="flex justify-end">
                        <button type="submit" name="update_settings" class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition">
                            <i class="fas fa-save mr-2"></i>Save SMTP Settings
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Email Templates Tab -->
            <div id="templatesTab" class="email-tab-content hidden p-8">
                <form method="POST" class="space-y-8">
                    <!-- Welcome Email Settings -->
                    <div class="bg-gray-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">Welcome Email Settings</h3>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div>
                                <label class="flex items-center">
                                    <input type="checkbox" name="send_welcome_user" <?php echo $emailSettings['send_welcome_user'] ? 'checked' : ''; ?> 
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm font-medium text-gray-700">Send welcome email when user account is created</span>
                                </label>
                            </div>
                            
                            <div>
                                <label class="flex items-center">
                                    <input type="checkbox" name="send_welcome_member" <?php echo $emailSettings['send_welcome_member'] ? 'checked' : ''; ?> 
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm font-medium text-gray-700">Send welcome email when member is created</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- User Welcome Template -->
                    <div class="space-y-4">
                        <h4 class="text-lg font-semibold text-gray-800">User Welcome Email Template</h4>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Subject</label>
                            <input type="text" name="user_welcome_subject" value="<?php echo htmlspecialchars($emailSettings['user_welcome_subject']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Email Template</label>
                            <textarea name="user_welcome_template" rows="8" 
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($emailSettings['user_welcome_template']); ?></textarea>
                            <p class="text-xs text-gray-500 mt-1">Available variables: {name}, {email}, {username}, {login_url}</p>
                        </div>
                    </div>
                    
                    <!-- Member Welcome Template -->
                    <div class="space-y-4">
                        <h4 class="text-lg font-semibold text-gray-800">Member Welcome Email Template</h4>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Subject</label>
                            <input type="text" name="member_welcome_subject" value="<?php echo htmlspecialchars($emailSettings['member_welcome_subject']); ?>" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Email Template</label>
                            <textarea name="member_welcome_template" rows="8" 
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($emailSettings['member_welcome_template']); ?></textarea>
                            <p class="text-xs text-gray-500 mt-1">Available variables: {name}, {email}, {member_id}, {phone}</p>
                        </div>
                    </div>
                    
                    <div class="flex justify-end">
                        <button type="submit" name="update_settings" class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition">
                            <i class="fas fa-save mr-2"></i>Save Templates
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Email Queue Tab -->
            <div id="queueTab" class="email-tab-content hidden p-8">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">Recent Email Queue</h3>
                    <p class="text-gray-600">Monitor the status of sent and pending emails</p>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Recipient</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Subject</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php
                            $queueStmt = $db->query("SELECT * FROM email_queue ORDER BY created_at DESC LIMIT 20");
                            $queueEmails = $queueStmt->fetchAll();
                            
                            if (empty($queueEmails)): ?>
                                <tr>
                                    <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                                        <i class="fas fa-inbox text-3xl mb-2"></i>
                                        <p>No emails in queue</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($queueEmails as $email): ?>
                                    <tr>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div>
                                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($email['recipient_name'] ?? 'N/A'); ?></div>
                                                <div class="text-sm text-gray-500"><?php echo htmlspecialchars($email['recipient_email']); ?></div>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($email['subject']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
                                                <?php echo htmlspecialchars($email['email_type']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <?php
                                            $statusClass = [
                                                'pending' => 'bg-yellow-100 text-yellow-800',
                                                'sent' => 'bg-green-100 text-green-800',
                                                'failed' => 'bg-red-100 text-red-800'
                                            ][$email['status']] ?? 'bg-gray-100 text-gray-800';
                                            ?>
                                            <span class="px-2 py-1 text-xs font-medium rounded-full <?php echo $statusClass; ?>">
                                                <?php echo ucfirst($email['status']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo date('M j, Y H:i', strtotime($email['created_at'])); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Failed Emails Tab -->
            <div id="failedTab" class="email-tab-content hidden p-8">
                <div class="mb-6">
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <h3 class="text-lg font-semibold text-gray-800">Failed Emails</h3>
                            <p class="text-gray-600">Emails that failed after 3 retry attempts</p>
                        </div>
                        <?php if (!empty($failedEmails)): ?>
                        <div class="flex space-x-2">
                            <form method="POST" class="inline" onsubmit="return confirm('Retry all failed emails? They will be processed on the next cron run.');">
                                <button type="submit" name="retry_all_failed" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition text-sm">
                                    <i class="fas fa-redo mr-2"></i>Retry All
                                </button>
                            </form>
                            <form method="POST" class="inline" onsubmit="return confirm('Delete all failed emails permanently?');">
                                <button type="submit" name="delete_all_failed" class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition text-sm">
                                    <i class="fas fa-trash mr-2"></i>Delete All
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Recipient</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Subject</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Attempts</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Error</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Failed At</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($failedEmails)): ?>
                                <tr>
                                    <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                                        <i class="fas fa-check-circle text-3xl mb-2 text-green-500"></i>
                                        <p>No failed emails - Great job!</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($failedEmails as $email): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4">
                                            <div>
                                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($email['recipient_name'] ?? 'N/A'); ?></div>
                                                <div class="text-sm text-gray-500"><?php echo htmlspecialchars($email['recipient_email']); ?></div>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900">
                                            <div class="max-w-xs truncate" title="<?php echo htmlspecialchars($email['subject']); ?>">
                                                <?php echo htmlspecialchars($email['subject']); ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
                                                <?php echo htmlspecialchars($email['email_type']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-800">
                                                <?php echo $email['attempts']; ?> / 3
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-red-600">
                                            <div class="max-w-xs truncate" title="<?php echo htmlspecialchars($email['error_message'] ?? 'Unknown error'); ?>">
                                                <?php echo htmlspecialchars($email['error_message'] ?? 'Unknown error'); ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo date('M j, Y H:i', strtotime($email['updated_at'])); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                                            <div class="flex space-x-2">
                                                <form method="POST" class="inline">
                                                    <input type="hidden" name="email_id" value="<?php echo $email['id']; ?>">
                                                    <button type="submit" name="retry_email" 
                                                            class="text-blue-600 hover:text-blue-900 transition"
                                                            title="Retry this email">
                                                        <i class="fas fa-redo"></i>
                                                    </button>
                                                </form>
                                                <form method="POST" class="inline" onsubmit="return confirm('Delete this email permanently?');">
                                                    <input type="hidden" name="email_id" value="<?php echo $email['id']; ?>">
                                                    <button type="submit" name="delete_email" 
                                                            class="text-red-600 hover:text-red-900 transition"
                                                            title="Delete this email">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if (!empty($failedEmails)): ?>
                <div class="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <div class="flex items-start">
                        <i class="fas fa-info-circle text-yellow-600 mt-1 mr-3"></i>
                        <div class="text-sm text-yellow-800">
                            <p class="font-semibold mb-1">About Failed Emails:</p>
                            <ul class="list-disc list-inside space-y-1">
                                <li>Emails fail after 3 unsuccessful send attempts</li>
                                <li>Click <strong>Retry</strong> to reset attempts and try sending again</li>
                                <li>Check error messages to diagnose SMTP issues</li>
                                <li>Verify SMTP settings before retrying</li>
                                <li>Delete emails that are no longer needed</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Test Email Tab -->
            <div id="testTab" class="email-tab-content hidden p-8">
                <div class="max-w-md mx-auto">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Send Test Email</h3>
                    <p class="text-gray-600 mb-6">Send a test email to verify your SMTP configuration</p>
                    
                    <form method="POST" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Test Email Address</label>
                            <input type="email" name="test_email_address" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" 
                                   placeholder="Enter email address" required>
                        </div>
                        
                        <button type="submit" name="test_email" class="w-full bg-green-500 text-white px-6 py-2 rounded-lg hover:bg-green-600 transition">
                            <i class="fas fa-paper-plane mr-2"></i>Send Test Email
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</main>

<script>
function switchEmailTab(tabName) {
    // Hide all tab contents
    document.querySelectorAll('.email-tab-content').forEach(content => {
        content.classList.add('hidden');
    });
    
    // Reset all tabs to inactive state
    document.querySelectorAll('.email-tab').forEach(tab => {
        tab.classList.remove('border-blue-500', 'text-blue-600');
        tab.classList.add('border-transparent', 'text-gray-600', 'hover:text-blue-600');
    });
    
    // Show selected tab content
    document.getElementById(tabName + 'Tab').classList.remove('hidden');
    
    // Activate selected tab
    event.target.classList.remove('border-transparent', 'text-gray-600', 'hover:text-blue-600');
    event.target.classList.add('border-blue-500', 'text-blue-600');
}

// Initialize first tab as active
document.addEventListener('DOMContentLoaded', function() {
    // SMTP tab is active by default
    
    // Auto-dismiss messages after 5 seconds
    setTimeout(function() {
        dismissMessage('successMessage');
        dismissMessage('errorMessage');
    }, 5000);
});

// Function to dismiss message boxes
function dismissMessage(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.style.opacity = '0';
        element.style.transform = 'translateY(-10px)';
        setTimeout(function() {
            element.style.display = 'none';
        }, 300);
    }
}
</script>

<?php include '../../includes/footer.php'; ?>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists