Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/conference/admin/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/conference/admin/email-settings.php

<?php
session_start();
require_once '../includes/functions.php';

// Check if user is logged in and has admin privileges
if (!isLoggedIn() || !hasRole('superuser')) {
    header('Location: ../login.php');
    exit;
}

$db = new CopMadinaDB();
$conn = $db->getConnection();
$user = getCurrentUser();

$success = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_smtp') {
        $smtp_host = sanitizeInput($_POST['smtp_host'] ?? '');
        $smtp_port = (int)($_POST['smtp_port'] ?? 587);
        $smtp_username = sanitizeInput($_POST['smtp_username'] ?? '');
        $smtp_password = $_POST['smtp_password'] ?? '';
        $smtp_encryption = $_POST['smtp_encryption'] ?? 'tls';
        $from_email = sanitizeInput($_POST['from_email'] ?? '');
        $from_name = sanitizeInput($_POST['from_name'] ?? '');
        $daily_limit = (int)($_POST['daily_limit'] ?? 100);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Validation
        if (empty($smtp_host) || empty($smtp_username) || empty($from_email) || empty($from_name)) {
            $error = 'Please fill in all required SMTP fields.';
        } elseif (!filter_var($from_email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid from email address.';
        } else {
            try {
                // Check if settings exist
                $stmt = $conn->prepare("SELECT id FROM email_settings LIMIT 1");
                $stmt->execute();
                $existing = $stmt->fetch();
                
                if ($existing) {
                    // Update existing settings
                    $stmt = $conn->prepare("
                        UPDATE email_settings SET 
                        smtp_host = ?, smtp_port = ?, smtp_username = ?, smtp_password = ?,
                        smtp_encryption = ?, from_email = ?, from_name = ?, daily_limit = ?,
                        is_active = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $smtp_host, $smtp_port, $smtp_username, $smtp_password,
                        $smtp_encryption, $from_email, $from_name, $daily_limit,
                        $is_active, $existing['id']
                    ]);
                } else {
                    // Insert new settings
                    $stmt = $conn->prepare("
                        INSERT INTO email_settings (
                            smtp_host, smtp_port, smtp_username, smtp_password,
                            smtp_encryption, from_email, from_name, daily_limit, is_active
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $smtp_host, $smtp_port, $smtp_username, $smtp_password,
                        $smtp_encryption, $from_email, $from_name, $daily_limit, $is_active
                    ]);
                }
                
                logAudit('update', 'email_settings', $existing['id'] ?? $conn->lastInsertId());
                $success = 'SMTP settings updated successfully.';
                
            } catch (Exception $e) {
                $error = 'Failed to update SMTP settings. Please try again.';
                error_log("SMTP settings error: " . $e->getMessage());
            }
        }
    }
    
    if ($action === 'update_templates') {
        $welcome_subject = sanitizeInput($_POST['welcome_email_subject'] ?? '');
        $welcome_template = $_POST['welcome_email_template'] ?? '';
        
        if (empty($welcome_subject) || empty($welcome_template)) {
            $error = 'Please fill in all template fields.';
        } else {
            try {
                $stmt = $conn->prepare("SELECT id FROM email_settings LIMIT 1");
                $stmt->execute();
                $existing = $stmt->fetch();
                
                if ($existing) {
                    $stmt = $conn->prepare("
                        UPDATE email_settings SET 
                        welcome_email_subject = ?, welcome_email_template = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$welcome_subject, $welcome_template, $existing['id']]);
                } else {
                    $stmt = $conn->prepare("
                        INSERT INTO email_settings (welcome_email_subject, welcome_email_template) 
                        VALUES (?, ?)
                    ");
                    $stmt->execute([$welcome_subject, $welcome_template]);
                }
                
                logAudit('update', 'email_templates', $existing['id'] ?? $conn->lastInsertId());
                $success = 'Email templates updated successfully.';
                
            } catch (Exception $e) {
                $error = 'Failed to update email templates. Please try again.';
                error_log("Email templates error: " . $e->getMessage());
            }
        }
    }
    
    if ($action === 'test_email') {
        $test_email = sanitizeInput($_POST['test_email'] ?? '');
        
        if (empty($test_email) || !filter_var($test_email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid test email address.';
        } else {
            // Send test email
            $result = sendTestEmail($test_email);
            if ($result) {
                $success = 'Test email sent successfully to ' . $test_email;
            } else {
                $error = 'Failed to send test email. Please check your SMTP settings.';
            }
        }
    }
}

// Get current email settings
$stmt = $conn->prepare("SELECT * FROM email_settings LIMIT 1");
$stmt->execute();
$email_settings = $stmt->fetch() ?: [];

// Get email statistics
$stmt = $conn->prepare("
    SELECT 
        COUNT(*) as total_emails,
        SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent_emails,
        SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_emails,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_emails
    FROM email_logs
");
$stmt->execute();
$email_stats = $stmt->fetch();

// Test email function
function sendTestEmail($email) {
    global $conn;
    
    // Log test email
    $stmt = $conn->prepare("
        INSERT INTO email_logs (recipient_email, recipient_name, subject, body, email_type, status) 
        VALUES (?, 'Test User', 'COP Madina - Email Test', 'This is a test email from your COP Madina system.', 'test', 'pending')
    ");
    $stmt->execute([$email]);
    
    // In a real implementation, you would send the actual email here using PHPMailer or similar
    // For now, we'll just mark it as sent
    $log_id = $conn->lastInsertId();
    $stmt = $conn->prepare("UPDATE email_logs SET status = 'sent', sent_at = NOW() WHERE id = ?");
    $stmt->execute([$log_id]);
    
    return true;
}

$settings = getSettings();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Settings - COP Madina Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gradient-to-br from-slate-50 to-blue-50 min-h-screen">
    <div id="app">
        <?php include 'includes/admin_sidebar.php'; ?>
        
        <!-- Main Content -->
        <main class="ml-72 min-h-screen">
            <!-- Header -->
            <header class="bg-white/80 backdrop-blur-sm border-b border-slate-200/50 sticky top-0 z-30">
                <div class="px-8 py-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h1 class="text-2xl font-bold text-slate-800">Email Settings</h1>
                            <p class="text-slate-600 mt-1">Configure SMTP settings and email templates</p>
                        </div>
                        <div class="flex items-center space-x-4">
                            <div class="text-right">
                                <p class="text-sm font-medium text-slate-800"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></p>
                                <p class="text-xs text-slate-500"><?php echo ucfirst(str_replace('_', ' ', $user['role'])); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <div class="p-8">
                <!-- Success/Error Messages -->
                <?php if ($success): ?>
                <div class="bg-green-50 border border-green-200 text-green-700 px-6 py-4 rounded-lg mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo htmlspecialchars($success); ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($error): ?>
                <div class="bg-red-50 border border-red-200 text-red-700 px-6 py-4 rounded-lg mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Email Statistics -->
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-slate-600">Total Emails</p>
                                <p class="text-2xl font-bold text-slate-800"><?php echo number_format($email_stats['total_emails']); ?></p>
                            </div>
                            <div class="p-3 bg-blue-100 rounded-lg">
                                <i class="fas fa-envelope text-blue-600"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-slate-600">Sent Successfully</p>
                                <p class="text-2xl font-bold text-green-600"><?php echo number_format($email_stats['sent_emails']); ?></p>
                            </div>
                            <div class="p-3 bg-green-100 rounded-lg">
                                <i class="fas fa-check-circle text-green-600"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-slate-600">Failed</p>
                                <p class="text-2xl font-bold text-red-600"><?php echo number_format($email_stats['failed_emails']); ?></p>
                            </div>
                            <div class="p-3 bg-red-100 rounded-lg">
                                <i class="fas fa-times-circle text-red-600"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-slate-600">Today</p>
                                <p class="text-2xl font-bold text-blue-600"><?php echo number_format($email_stats['today_emails']); ?></p>
                            </div>
                            <div class="p-3 bg-blue-100 rounded-lg">
                                <i class="fas fa-calendar-day text-blue-600"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- SMTP Settings -->
                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50">
                        <div class="p-6 border-b border-slate-200/50">
                            <h2 class="text-xl font-semibold text-slate-800 flex items-center">
                                <i class="fas fa-server mr-2 text-blue-600"></i>
                                SMTP Configuration
                            </h2>
                            <p class="text-slate-600 text-sm mt-1">Configure your email server settings</p>
                        </div>

                        <form method="POST" class="p-6">
                            <input type="hidden" name="action" value="update_smtp">
                            
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="smtp_host" class="block text-sm font-medium text-slate-700 mb-2">
                                            SMTP Host <span class="text-red-500">*</span>
                                        </label>
                                        <input type="text" id="smtp_host" name="smtp_host" required
                                               class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo htmlspecialchars($email_settings['smtp_host'] ?? ''); ?>"
                                               placeholder="smtp.gmail.com">
                                    </div>
                                    
                                    <div>
                                        <label for="smtp_port" class="block text-sm font-medium text-slate-700 mb-2">
                                            SMTP Port <span class="text-red-500">*</span>
                                        </label>
                                        <input type="number" id="smtp_port" name="smtp_port" required
                                               class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo htmlspecialchars($email_settings['smtp_port'] ?? '587'); ?>">
                                    </div>
                                </div>
                                
                                <div>
                                    <label for="smtp_username" class="block text-sm font-medium text-slate-700 mb-2">
                                        SMTP Username <span class="text-red-500">*</span>
                                    </label>
                                    <input type="text" id="smtp_username" name="smtp_username" required
                                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                           value="<?php echo htmlspecialchars($email_settings['smtp_username'] ?? ''); ?>"
                                           placeholder="your-email@gmail.com">
                                </div>
                                
                                <div>
                                    <label for="smtp_password" class="block text-sm font-medium text-slate-700 mb-2">
                                        SMTP Password <span class="text-red-500">*</span>
                                    </label>
                                    <input type="password" id="smtp_password" name="smtp_password"
                                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                           value="<?php echo htmlspecialchars($email_settings['smtp_password'] ?? ''); ?>"
                                           placeholder="Enter SMTP password">
                                </div>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="smtp_encryption" class="block text-sm font-medium text-slate-700 mb-2">
                                            Encryption
                                        </label>
                                        <select id="smtp_encryption" name="smtp_encryption"
                                                class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                            <option value="tls" <?php echo ($email_settings['smtp_encryption'] ?? 'tls') === 'tls' ? 'selected' : ''; ?>>TLS</option>
                                            <option value="ssl" <?php echo ($email_settings['smtp_encryption'] ?? '') === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                            <option value="none" <?php echo ($email_settings['smtp_encryption'] ?? '') === 'none' ? 'selected' : ''; ?>>None</option>
                                        </select>
                                    </div>
                                    
                                    <div>
                                        <label for="daily_limit" class="block text-sm font-medium text-slate-700 mb-2">
                                            Daily Email Limit
                                        </label>
                                        <input type="number" id="daily_limit" name="daily_limit"
                                               class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo htmlspecialchars($email_settings['daily_limit'] ?? '100'); ?>"
                                               min="1" max="1000">
                                    </div>
                                </div>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="from_email" class="block text-sm font-medium text-slate-700 mb-2">
                                            From Email <span class="text-red-500">*</span>
                                        </label>
                                        <input type="email" id="from_email" name="from_email" required
                                               class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo htmlspecialchars($email_settings['from_email'] ?? ''); ?>"
                                               placeholder="noreply@copmadinaconf.com">
                                    </div>
                                    
                                    <div>
                                        <label for="from_name" class="block text-sm font-medium text-slate-700 mb-2">
                                            From Name <span class="text-red-500">*</span>
                                        </label>
                                        <input type="text" id="from_name" name="from_name" required
                                               class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                               value="<?php echo htmlspecialchars($email_settings['from_name'] ?? ''); ?>"
                                               placeholder="COP Madina">
                                    </div>
                                </div>
                                
                                <div class="flex items-center">
                                    <input type="checkbox" id="is_active" name="is_active" 
                                           class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
                                           <?php echo ($email_settings['is_active'] ?? 0) ? 'checked' : ''; ?>>
                                    <label for="is_active" class="ml-2 text-sm font-medium text-slate-700">
                                        Enable email sending
                                    </label>
                                </div>
                            </div>
                            
                            <div class="flex justify-end pt-6">
                                <button type="submit" 
                                        class="bg-gradient-to-r from-blue-500 via-slate-600 to-violet-400 text-white px-6 py-3 rounded-lg font-semibold hover:shadow-lg transform hover:scale-105 transition-all duration-200 flex items-center space-x-2">
                                    <i class="fas fa-save"></i>
                                    <span>Save SMTP Settings</span>
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Email Templates -->
                    <div class="bg-white rounded-xl shadow-sm border border-slate-200/50">
                        <div class="p-6 border-b border-slate-200/50">
                            <h2 class="text-xl font-semibold text-slate-800 flex items-center">
                                <i class="fas fa-file-alt mr-2 text-green-600"></i>
                                Email Templates
                            </h2>
                            <p class="text-slate-600 text-sm mt-1">Customize your email templates</p>
                        </div>

                        <form method="POST" class="p-6">
                            <input type="hidden" name="action" value="update_templates">
                            
                            <div class="space-y-6">
                                <div>
                                    <label for="welcome_email_subject" class="block text-sm font-medium text-slate-700 mb-2">
                                        Welcome Email Subject <span class="text-red-500">*</span>
                                    </label>
                                    <input type="text" id="welcome_email_subject" name="welcome_email_subject" required
                                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                           value="<?php echo htmlspecialchars($email_settings['welcome_email_subject'] ?? 'Welcome to COP Madina!'); ?>">
                                </div>
                                
                                <div>
                                    <label for="welcome_email_template" class="block text-sm font-medium text-slate-700 mb-2">
                                        Welcome Email Template <span class="text-red-500">*</span>
                                    </label>
                                    <textarea id="welcome_email_template" name="welcome_email_template" rows="12" required
                                              class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                              placeholder="Enter your welcome email template here..."><?php echo htmlspecialchars($email_settings['welcome_email_template'] ?? 'Dear {member_name},

Welcome to The Church of Pentecost - Madina Area!

We are delighted to have you join our church family. Your membership registration has been successfully completed.

Member Details:
- Member ID: {member_id}
- Area: {area_name}
- District: {district_name}
- Assembly: {assembly_name}
- Join Date: {join_date}

We look forward to fellowshipping with you and growing together in faith.

God bless you!

The Church of Pentecost - Madina Area
'); ?></textarea>
                                    
                                    <div class="mt-2 text-xs text-slate-500">
                                        <p class="font-medium mb-1">Available placeholders:</p>
                                        <div class="flex flex-wrap gap-2">
                                            <span class="bg-slate-100 px-2 py-1 rounded">{member_name}</span>
                                            <span class="bg-slate-100 px-2 py-1 rounded">{member_id}</span>
                                            <span class="bg-slate-100 px-2 py-1 rounded">{area_name}</span>
                                            <span class="bg-slate-100 px-2 py-1 rounded">{district_name}</span>
                                            <span class="bg-slate-100 px-2 py-1 rounded">{assembly_name}</span>
                                            <span class="bg-slate-100 px-2 py-1 rounded">{join_date}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="flex justify-end pt-6">
                                <button type="submit" 
                                        class="bg-gradient-to-r from-green-500 to-emerald-600 text-white px-6 py-3 rounded-lg font-semibold hover:shadow-lg transform hover:scale-105 transition-all duration-200 flex items-center space-x-2">
                                    <i class="fas fa-save"></i>
                                    <span>Save Templates</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Test Email Section -->
                <div class="mt-8 bg-white rounded-xl shadow-sm border border-slate-200/50">
                    <div class="p-6 border-b border-slate-200/50">
                        <h2 class="text-xl font-semibold text-slate-800 flex items-center">
                            <i class="fas fa-paper-plane mr-2 text-purple-600"></i>
                            Test Email
                        </h2>
                        <p class="text-slate-600 text-sm mt-1">Send a test email to verify your settings</p>
                    </div>

                    <form method="POST" class="p-6">
                        <input type="hidden" name="action" value="test_email">
                        
                        <div class="flex items-end space-x-4">
                            <div class="flex-1">
                                <label for="test_email" class="block text-sm font-medium text-slate-700 mb-2">
                                    Test Email Address
                                </label>
                                <input type="email" id="test_email" name="test_email" required
                                       class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                       placeholder="test@example.com">
                            </div>
                            
                            <button type="submit" 
                                    class="bg-gradient-to-r from-purple-500 to-indigo-600 text-white px-6 py-3 rounded-lg font-semibold hover:shadow-lg transform hover:scale-105 transition-all duration-200 flex items-center space-x-2">
                                <i class="fas fa-paper-plane"></i>
                                <span>Send Test</span>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Email Logs Link -->
                <div class="mt-8 text-center">
                    <a href="email-logs.php" 
                       class="inline-flex items-center space-x-2 text-blue-600 hover:text-blue-700 font-medium">
                        <i class="fas fa-list"></i>
                        <span>View Email Logs</span>
                        <i class="fas fa-arrow-right"></i>
                    </a>
                </div>
            </div>
        </main>
    </div>

    <script>
    const { createApp } = Vue;
    
    createApp({
        data() {
            return {
                // Add any Vue.js data here if needed
            }
        },
        methods: {
            // Add any Vue.js methods here if needed
        }
    }).mount('#app');
    </script>
</body>
</html>

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