Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/conference/includes/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/conference/includes/email_functions.php

<?php
/**
 * Email Functions for COP Madina Conference Platform
 * Handles email sending, logging, and SMTP configuration
 */

require_once 'functions.php';

/**
 * Send email using configured SMTP settings
 */
function sendEmail($to_email, $to_name, $subject, $body, $email_type = 'notification', $recipient_id = null, $recipient_type = 'user') {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    try {
        // Get email settings
        $stmt = $conn->prepare("SELECT * FROM email_settings WHERE is_active = 1 LIMIT 1");
        $stmt->execute();
        $settings = $stmt->fetch();
        
        if (!$settings) {
            throw new Exception('Email settings not configured or disabled');
        }
        
        // Check daily limit
        $stmt = $conn->prepare("
            SELECT COUNT(*) as today_count 
            FROM email_logs 
            WHERE DATE(created_at) = CURDATE() AND status = 'sent'
        ");
        $stmt->execute();
        $today_count = $stmt->fetch()['today_count'];
        
        if ($today_count >= $settings['daily_limit']) {
            throw new Exception('Daily email limit reached');
        }
        
        // Log email attempt
        $stmt = $conn->prepare("
            INSERT INTO email_logs (
                recipient_email, recipient_name, recipient_type, recipient_id,
                subject, body, email_type, status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");
        $stmt->execute([
            $to_email, $to_name, $recipient_type, $recipient_id,
            $subject, $body, $email_type
        ]);
        $log_id = $conn->lastInsertId();
        
        // In a real implementation, you would use PHPMailer or similar here
        // For now, we'll simulate email sending
        $success = simulateEmailSending($settings, $to_email, $to_name, $subject, $body);
        
        if ($success) {
            // Update log as sent
            $stmt = $conn->prepare("
                UPDATE email_logs 
                SET status = 'sent', sent_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$log_id]);
            
            return true;
        } else {
            throw new Exception('SMTP sending failed');
        }
        
    } catch (Exception $e) {
        // Update log as failed
        if (isset($log_id)) {
            $stmt = $conn->prepare("
                UPDATE email_logs 
                SET status = 'failed', error_message = ?, failed_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$e->getMessage(), $log_id]);
        }
        
        error_log("Email sending failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Simulate email sending (replace with actual SMTP implementation)
 */
function simulateEmailSending($settings, $to_email, $to_name, $subject, $body) {
    // In a real implementation, you would use PHPMailer like this:
    /*
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = $settings['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $settings['smtp_username'];
        $mail->Password   = $settings['smtp_password'];
        $mail->SMTPSecure = $settings['smtp_encryption'];
        $mail->Port       = $settings['smtp_port'];
        
        // Recipients
        $mail->setFrom($settings['from_email'], $settings['from_name']);
        $mail->addAddress($to_email, $to_name);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = nl2br($body);
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        return false;
    }
    */
    
    // For simulation, we'll just return true (assuming email was sent)
    return true;
}

/**
 * Send welcome email to new member
 */
function sendWelcomeEmailToMember($member_id) {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    try {
        // Get member details with organizational info
        $stmt = $conn->prepare("
            SELECT m.*, a.name as area_name, d.name as district_name, ass.name as assembly_name
            FROM members m
            LEFT JOIN areas a ON m.area_id = a.id
            LEFT JOIN districts d ON m.district_id = d.id
            LEFT JOIN assemblies ass ON m.assembly_id = ass.id
            WHERE m.id = ?
        ");
        $stmt->execute([$member_id]);
        $member = $stmt->fetch();
        
        if (!$member) {
            throw new Exception('Member not found');
        }
        
        // Get email template
        $stmt = $conn->prepare("SELECT welcome_email_subject, welcome_email_template FROM email_settings WHERE is_active = 1 LIMIT 1");
        $stmt->execute();
        $template = $stmt->fetch();
        
        if (!$template || !$template['welcome_email_template']) {
            throw new Exception('Welcome email template not configured');
        }
        
        // Prepare email content with placeholders
        $subject = $template['welcome_email_subject'];
        $body = $template['welcome_email_template'];
        
        $placeholders = [
            '{first_name}' => $member['first_name'],
            '{last_name}' => $member['last_name'],
            '{member_name}' => $member['first_name'] . ' ' . $member['last_name'],
            '{member_id}' => $member['member_id'],
            '{area_name}' => $member['area_name'] ?: 'Not Assigned',
            '{district_name}' => $member['district_name'] ?: 'Not Assigned',
            '{assembly_name}' => $member['assembly_name'] ?: 'Not Assigned',
            '{join_date}' => date('F j, Y', strtotime($member['membership_date'] ?? $member['created_at']))
        ];
        
        foreach ($placeholders as $placeholder => $value) {
            $subject = str_replace($placeholder, $value, $subject);
            $body = str_replace($placeholder, $value, $body);
        }
        
        // Send email
        return sendEmail(
            $member['email'],
            $member['first_name'] . ' ' . $member['last_name'],
            $subject,
            $body,
            'welcome',
            $member_id,
            'member'
        );
        
    } catch (Exception $e) {
        error_log("Welcome email failed for member {$member_id}: " . $e->getMessage());
        return false;
    }
}

/**
 * Send test email
 */
function sendTestEmail($to_email) {
    $subject = 'COP Madina - Email Test';
    $body = "This is a test email from your COP Madina system.\n\nIf you received this email, your SMTP configuration is working correctly.\n\nSent at: " . date('F j, Y g:i A');
    
    return sendEmail($to_email, 'Test User', $subject, $body, 'test');
}

/**
 * Send event notification email
 */
function sendEventNotification($user_id, $event_id, $notification_type = 'reminder') {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    try {
        // Get user details
        $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            throw new Exception('User not found');
        }
        
        // Get event details
        $stmt = $conn->prepare("SELECT * FROM events WHERE id = ?");
        $stmt->execute([$event_id]);
        $event = $stmt->fetch();
        
        if (!$event) {
            throw new Exception('Event not found');
        }
        
        // Prepare email content based on notification type
        switch ($notification_type) {
            case 'reminder':
                $subject = "Reminder: {$event['title']} - COP Madina";
                $body = "Dear {$user['first_name']},\n\nThis is a reminder about the upcoming event:\n\n";
                $body .= "Event: {$event['title']}\n";
                $body .= "Date: " . date('F j, Y', strtotime($event['start_date'])) . "\n";
                if ($event['start_time']) {
                    $body .= "Time: " . date('g:i A', strtotime($event['start_time'])) . "\n";
                }
                if ($event['location']) {
                    $body .= "Location: {$event['location']}\n";
                }
                $body .= "\nDescription:\n{$event['description']}\n\n";
                $body .= "We look forward to seeing you there!\n\nCOP Madina";
                break;
                
            case 'registration_confirmation':
                $subject = "Registration Confirmed: {$event['title']} - COP Madina";
                $body = "Dear {$user['first_name']},\n\nYour registration for the following event has been confirmed:\n\n";
                $body .= "Event: {$event['title']}\n";
                $body .= "Date: " . date('F j, Y', strtotime($event['start_date'])) . "\n";
                if ($event['start_time']) {
                    $body .= "Time: " . date('g:i A', strtotime($event['start_time'])) . "\n";
                }
                if ($event['location']) {
                    $body .= "Location: {$event['location']}\n";
                }
                $body .= "\nThank you for registering. We look forward to seeing you!\n\nCOP Madina";
                break;
                
            default:
                throw new Exception('Unknown notification type');
        }
        
        return sendEmail(
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            $subject,
            $body,
            'notification',
            $user_id,
            'user'
        );
        
    } catch (Exception $e) {
        error_log("Event notification failed for user {$user_id}, event {$event_id}: " . $e->getMessage());
        return false;
    }
}

/**
 * Get email statistics
 */
function getEmailStatistics($days = 30) {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    $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 status = 'pending' THEN 1 ELSE 0 END) as pending_emails,
            SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_emails,
            SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL ? DAY) THEN 1 ELSE 0 END) as recent_emails
        FROM email_logs
    ");
    $stmt->execute([$days]);
    
    return $stmt->fetch();
}

/**
 * Check if daily email limit is reached
 */
function isDailyLimitReached() {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    $stmt = $conn->prepare("SELECT daily_limit FROM email_settings WHERE is_active = 1 LIMIT 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if (!$settings) {
        return true; // No settings = no emails allowed
    }
    
    $stmt = $conn->prepare("
        SELECT COUNT(*) as today_count 
        FROM email_logs 
        WHERE DATE(created_at) = CURDATE() AND status = 'sent'
    ");
    $stmt->execute();
    $today_count = $stmt->fetch()['today_count'];
    
    return $today_count >= $settings['daily_limit'];
}

/**
 * Queue email for later sending (for bulk operations)
 */
function queueEmail($to_email, $to_name, $subject, $body, $email_type = 'notification', $recipient_id = null, $recipient_type = 'user') {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    $stmt = $conn->prepare("
        INSERT INTO email_logs (
            recipient_email, recipient_name, recipient_type, recipient_id,
            subject, body, email_type, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', NOW())
    ");
    
    return $stmt->execute([
        $to_email, $to_name, $recipient_type, $recipient_id,
        $subject, $body, $email_type
    ]);
}

/**
 * Process queued emails (to be run via cron job)
 */
function processQueuedEmails($limit = 50) {
    $db = new CopMadinaDB();
    $conn = $db->getConnection();
    
    $stmt = $conn->prepare("
        SELECT * FROM email_logs 
        WHERE status = 'queued' 
        ORDER BY created_at ASC 
        LIMIT ?
    ");
    $stmt->execute([$limit]);
    $queued_emails = $stmt->fetchAll();
    
    $processed = 0;
    $failed = 0;
    
    foreach ($queued_emails as $email) {
        // Update status to pending
        $stmt = $conn->prepare("UPDATE email_logs SET status = 'pending' WHERE id = ?");
        $stmt->execute([$email['id']]);
        
        // Attempt to send
        $success = sendEmail(
            $email['recipient_email'],
            $email['recipient_name'],
            $email['subject'],
            $email['body'],
            $email['email_type'],
            $email['recipient_id'],
            $email['recipient_type']
        );
        
        if ($success) {
            $processed++;
        } else {
            $failed++;
        }
        
        // Small delay to avoid overwhelming SMTP server
        usleep(100000); // 0.1 second
    }
    
    return [
        'processed' => $processed,
        'failed' => $failed,
        'total' => count($queued_emails)
    ];
}
?>

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