Sindbad~EG File Manager

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

<?php
// Email notification functions

/**
 * Send attendance confirmation email
 */
function sendAttendanceConfirmationEmail($conn, $attendance_record) {
    try {
        // Get email settings
        $settings_query = "SELECT * FROM email_settings WHERE is_active = 1 ORDER BY created_at DESC LIMIT 1";
        $settings_stmt = $conn->prepare($settings_query);
        $settings_stmt->execute();
        $email_settings = $settings_stmt->fetch();
        
        if (!$email_settings || empty($attendance_record['email'])) {
            return false; // Email not configured or no recipient email
        }
        
        // Get email template
        $template_query = "SELECT * FROM email_templates WHERE template_name = 'attendance_confirmation' AND is_active = 1 LIMIT 1";
        $template_stmt = $conn->prepare($template_query);
        $template_stmt->execute();
        $template = $template_stmt->fetch();
        
        if (!$template) {
            return false; // No template found
        }
        
        // Get program details
        $program_query = "SELECT p.*, l.name as location_name FROM programs p 
                         LEFT JOIN locations l ON p.location_id = l.id 
                         WHERE p.id = ?";
        $program_stmt = $conn->prepare($program_query);
        $program_stmt->execute([$attendance_record['program_id']]);
        $program = $program_stmt->fetch();
        
        // Prepare email content with variable replacement
        $variables = [
            '{{full_name}}' => $attendance_record['full_name'],
            '{{program_name}}' => $program['name'] ?? 'Unknown Program',
            '{{tracking_code}}' => $attendance_record['tracking_code'],
            '{{district_name}}' => $attendance_record['district_name'] ?? 'N/A',
            '{{assembly_name}}' => $attendance_record['assembly_name'] ?? 'N/A',
            '{{submission_date}}' => date('F j, Y g:i A', strtotime($attendance_record['submitted_at'] ?? 'now'))
        ];
        
        $subject = str_replace(array_keys($variables), array_values($variables), $template['subject']);
        $body = str_replace(array_keys($variables), array_values($variables), $template['body']);
        
        // For now, we'll use PHP's mail() function
        // In production, you should use PHPMailer or similar library
        $headers = [
            'From: ' . $email_settings['from_name'] . ' <' . $email_settings['from_email'] . '>',
            'Reply-To: ' . $email_settings['from_email'],
            'Content-Type: text/plain; charset=UTF-8',
            'X-Mailer: Church Attendance System'
        ];
        
        $result = mail(
            $attendance_record['email'],
            $subject,
            $body,
            implode("\r\n", $headers)
        );
        
        // Log email attempt
        if ($result) {
            logEmailActivity($conn, $attendance_record['email'], $subject, 'sent');
        } else {
            logEmailActivity($conn, $attendance_record['email'], $subject, 'failed');
        }
        
        return $result;
        
    } catch (Exception $e) {
        error_log("Email sending error: " . $e->getMessage());
        return false;
    }
}

/**
 * Log email activity
 */
function logEmailActivity($conn, $recipient, $subject, $status) {
    try {
        // Create email_logs table if it doesn't exist
        $create_table = "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)
        )";
        $conn->exec($create_table);
        
        $query = "INSERT INTO email_logs (recipient_email, subject, status) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($query);
        $stmt->execute([$recipient, $subject, $status]);
        
    } catch (Exception $e) {
        error_log("Email logging error: " . $e->getMessage());
    }
}

/**
 * Check if email notifications are enabled
 */
function isEmailNotificationEnabled($conn) {
    try {
        $query = "SELECT is_active FROM email_settings WHERE is_active = 1 LIMIT 1";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Get email statistics
 */
function getEmailStats($conn) {
    try {
        $stats = [];
        
        // Total emails sent today
        $query = "SELECT COUNT(*) FROM email_logs WHERE DATE(sent_at) = CURDATE() AND status = 'sent'";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $stats['today_sent'] = $stmt->fetchColumn();
        
        // Total emails failed today
        $query = "SELECT COUNT(*) FROM email_logs WHERE DATE(sent_at) = CURDATE() AND status = 'failed'";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $stats['today_failed'] = $stmt->fetchColumn();
        
        // Total emails this month
        $query = "SELECT COUNT(*) FROM email_logs WHERE MONTH(sent_at) = MONTH(CURDATE()) AND YEAR(sent_at) = YEAR(CURDATE()) AND status = 'sent'";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $stats['month_sent'] = $stmt->fetchColumn();
        
        return $stats;
    } catch (Exception $e) {
        return ['today_sent' => 0, 'today_failed' => 0, 'month_sent' => 0];
    }
}
?>

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