Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/setup_email_system.php

<?php
require_once '../config/config.php';

// Check if user is logged in and is superuser
if (!isLoggedIn() || !hasRole('superuser')) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['setup_email'])) {
    try {
        // Add tracking code column to attendance_records if it doesn't exist
        $check_column = "SHOW COLUMNS FROM attendance_records LIKE 'tracking_code'";
        $result = $conn->query($check_column);
        
        if ($result->rowCount() == 0) {
            $conn->exec("ALTER TABLE attendance_records ADD COLUMN tracking_code VARCHAR(20) UNIQUE NOT NULL AFTER id");
            $conn->exec("CREATE INDEX idx_attendance_tracking ON attendance_records(tracking_code)");
        }
        
        // Create email_settings table
        $conn->exec("CREATE TABLE IF NOT EXISTS email_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            smtp_host VARCHAR(255) NOT NULL,
            smtp_port INT NOT NULL DEFAULT 587,
            smtp_username VARCHAR(255) NOT NULL,
            smtp_password VARCHAR(255) NOT NULL,
            smtp_encryption ENUM('tls', 'ssl', 'none') DEFAULT 'tls',
            from_email VARCHAR(255) NOT NULL,
            from_name VARCHAR(255) NOT NULL,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
        
        // Create email_templates table
        $conn->exec("CREATE TABLE IF NOT EXISTS email_templates (
            id INT AUTO_INCREMENT PRIMARY KEY,
            template_name VARCHAR(100) NOT NULL,
            subject VARCHAR(255) NOT NULL,
            body TEXT NOT NULL,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
        
        // Create email_logs table
        $conn->exec("CREATE TABLE IF NOT EXISTS email_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            recipient_email VARCHAR(255) NOT NULL,
            subject VARCHAR(255) NOT NULL,
            status ENUM('sent', 'failed') NOT NULL,
            sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_email_logs_recipient (recipient_email),
            INDEX idx_email_logs_date (sent_at)
        )");
        
        // Insert default email settings if none exist
        $check_settings = "SELECT COUNT(*) FROM email_settings";
        $stmt = $conn->prepare($check_settings);
        $stmt->execute();
        
        if ($stmt->fetchColumn() == 0) {
            $conn->exec("INSERT INTO email_settings (smtp_host, smtp_port, smtp_username, smtp_password, from_email, from_name) 
                        VALUES ('smtp.gmail.com', 587, 'your-email@gmail.com', 'your-app-password', 'your-email@gmail.com', 'Church Attendance System')");
        }
        
        // Insert default email template if none exist
        $check_template = "SELECT COUNT(*) FROM email_templates WHERE template_name = 'attendance_confirmation'";
        $stmt = $conn->prepare($check_template);
        $stmt->execute();
        
        if ($stmt->fetchColumn() == 0) {
            $template_body = "Dear {{full_name}},

Thank you for registering your attendance for {{program_name}}.

Your attendance has been successfully recorded with the following details:
- Tracking Code: {{tracking_code}}
- Program: {{program_name}}
- District: {{district_name}}
- Assembly: {{assembly_name}}
- Date: {{submission_date}}

You can use your tracking code ({{tracking_code}}) to check your attendance details anytime by visiting our status check page.

Thank you for your participation!

Best regards,
Church Attendance Management Team";
            
            $stmt = $conn->prepare("INSERT INTO email_templates (template_name, subject, body) VALUES (?, ?, ?)");
            $stmt->execute([
                'attendance_confirmation',
                'Welcome to {{program_name}} - Attendance Confirmed',
                $template_body
            ]);
        }
        
        // Update existing attendance records with tracking codes if they don't have them
        $update_records = "SELECT id FROM attendance_records WHERE tracking_code IS NULL OR tracking_code = ''";
        $stmt = $conn->prepare($update_records);
        $stmt->execute();
        $records_to_update = $stmt->fetchAll();
        
        foreach ($records_to_update as $record) {
            $tracking_code = generateUniqueTrackingCode($conn);
            $update_stmt = $conn->prepare("UPDATE attendance_records SET tracking_code = ? WHERE id = ?");
            $update_stmt->execute([$tracking_code, $record['id']]);
        }
        
        logActivity($_SESSION['user_id'], 'setup_email_system', 'Email system setup completed');
        $success_message = 'Email system setup completed successfully! Updated ' . count($records_to_update) . ' existing records with tracking codes.';
        
    } catch (Exception $e) {
        $error_message = 'Setup failed: ' . $e->getMessage();
    }
}

// Get site settings
$query = "SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('site_title', 'site_logo')";
$stmt = $conn->prepare($query);
$stmt->execute();
$settings = [];
while ($row = $stmt->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email System Setup - <?php echo $settings['site_title'] ?? SITE_TITLE; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#F59E0B',
                        accent: '#6B7280'
                    }
                }
            }
        }
    </script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #3B82F6 0%, #F59E0B 50%, #6B7280 100%);
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Include Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <div class="md:ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b">
            <div class="px-6 py-4">
                <h1 class="text-2xl font-bold text-gray-900">Email System Setup</h1>
            </div>
        </header>

        <!-- Content -->
        <main class="p-6">
            <div class="max-w-4xl mx-auto">
                <!-- Success/Error Messages -->
                <?php if ($success_message): ?>
                    <div class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg mb-6">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo $success_message; ?>
                    </div>
                <?php endif; ?>

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

                <!-- Setup Information -->
                <div class="bg-white rounded-lg shadow p-8">
                    <div class="text-center mb-8">
                        <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-envelope-open-text text-blue-600 text-2xl"></i>
                        </div>
                        <h2 class="text-2xl font-bold text-gray-900 mb-2">Email System Setup</h2>
                        <p class="text-gray-600">This will set up the email notification system for attendance confirmations</p>
                    </div>

                    <!-- What will be created -->
                    <div class="mb-8">
                        <h3 class="text-lg font-semibold text-gray-900 mb-4">What will be set up:</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                        <i class="fas fa-database text-green-600 text-sm"></i>
                                    </div>
                                </div>
                                <div class="ml-3">
                                    <h4 class="font-medium text-gray-900">Database Tables</h4>
                                    <p class="text-sm text-gray-600">Email settings, templates, and logs tables</p>
                                </div>
                            </div>

                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                                        <i class="fas fa-barcode text-blue-600 text-sm"></i>
                                    </div>
                                </div>
                                <div class="ml-3">
                                    <h4 class="font-medium text-gray-900">Tracking Codes</h4>
                                    <p class="text-sm text-gray-600">Add tracking codes to existing records</p>
                                </div>
                            </div>

                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <div class="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                                        <i class="fas fa-envelope text-yellow-600 text-sm"></i>
                                    </div>
                                </div>
                                <div class="ml-3">
                                    <h4 class="font-medium text-gray-900">Email Templates</h4>
                                    <p class="text-sm text-gray-600">Default attendance confirmation template</p>
                                </div>
                            </div>

                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <div class="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                                        <i class="fas fa-cog text-purple-600 text-sm"></i>
                                    </div>
                                </div>
                                <div class="ml-3">
                                    <h4 class="font-medium text-gray-900">Default Settings</h4>
                                    <p class="text-sm text-gray-600">Basic SMTP configuration (needs customization)</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Setup Button -->
                    <form method="POST" class="text-center">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <button type="submit" name="setup_email" 
                                class="bg-primary text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition duration-300 font-semibold"
                                onclick="return confirm('Are you sure you want to set up the email system? This will modify the database.')">
                            <i class="fas fa-rocket mr-2"></i>Setup Email System
                        </button>
                    </form>

                    <!-- Next Steps -->
                    <div class="mt-8 p-4 bg-blue-50 rounded-lg">
                        <h4 class="font-semibold text-blue-900 mb-2">
                            <i class="fas fa-info-circle mr-2"></i>Next Steps After Setup:
                        </h4>
                        <ol class="list-decimal list-inside text-sm text-blue-800 space-y-1">
                            <li>Go to <a href="email_management.php" class="underline">Email Management</a> to configure SMTP settings</li>
                            <li>Update the email templates with your organization's branding</li>
                            <li>Test email functionality with a test email address</li>
                            <li>Enable email notifications in the settings</li>
                        </ol>
                    </div>
                </div>
            </div>
        </main>
    </div>
</body>
</html>

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