<?php
// Email Notification System for Payment Events

require_once 'config/database.php';

class PaymentNotifications {
    private $db;

    public function __construct() {
        $this->db = getDB();
    }

    /**
     * Send payment success notification
     */
    public function sendPaymentSuccessNotification($transactionId) {
        $transaction = $this->getTransactionDetails($transactionId);
        if (!$transaction) return false;

        $user = $this->getUserDetails($transaction['user_id']);
        if (!$user) return false;

        $subject = "Payment Successful - " . getSiteSetting('site_name');
        $message = $this->getPaymentSuccessTemplate($transaction, $user);

        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send payment failed notification
     */
    public function sendPaymentFailedNotification($transactionId) {
        $transaction = $this->getTransactionDetails($transactionId);
        if (!$transaction) return false;

        $user = $this->getUserDetails($transaction['user_id']);
        if (!$user) return false;

        $subject = "Payment Failed - " . getSiteSetting('site_name');
        $message = $this->getPaymentFailedTemplate($transaction, $user);

        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send refund processed notification
     */
    public function sendRefundProcessedNotification($refundId) {
        $refund = $this->getRefundDetails($refundId);
        if (!$refund) return false;

        $user = $this->getUserDetails($refund['user_id']);
        if (!$user) return false;

        $subject = "Refund Processed - " . getSiteSetting('site_name');
        $message = $this->getRefundProcessedTemplate($refund, $user);

        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send enrollment confirmation notification
     */
    public function sendEnrollmentConfirmationNotification($enrollmentId) {
        $enrollment = $this->getEnrollmentDetails($enrollmentId);
        if (!$enrollment) return false;

        $user = $this->getUserDetails($enrollment['student_id']);
        if (!$user) return false;

        $subject = "Enrollment Confirmed - " . getSiteSetting('site_name');
        $message = $this->getEnrollmentConfirmationTemplate($enrollment, $user);

        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Get transaction details
     */
    private function getTransactionDetails($transactionId) {
        $stmt = $this->db->prepare("
            SELECT pt.*, c.title as course_title, e.title as exam_title
            FROM payment_transactions pt
            LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
            LEFT JOIN exams e ON pt.item_type = 'exam' AND pt.item_id = e.id
            WHERE pt.transaction_id = ? OR pt.reference_number = ?
        ");
        $stmt->execute([$transactionId, $transactionId]);
        return $stmt->fetch();
    }

    /**
     * Get refund details
     */
    private function getRefundDetails($refundId) {
        $stmt = $this->db->prepare("
            SELECT pr.*, pt.transaction_id, pt.reference_number, pt.final_amount, pt.currency,
                   pt.user_id, pt.item_type, pt.item_id, c.title as course_title, e.title as exam_title
            FROM payment_refunds pr
            JOIN payment_transactions pt ON pr.transaction_id = pt.id
            LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
            LEFT JOIN exams e ON pt.item_type = 'exam' AND pt.item_id = e.id
            WHERE pr.id = ?
        ");
        $stmt->execute([$refundId]);
        return $stmt->fetch();
    }

    /**
     * Get enrollment details
     */
    private function getEnrollmentDetails($enrollmentId) {
        $stmt = $this->db->prepare("
            SELECT ce.*, c.title as course_title, c.price, c.currency,
                   u.username as instructor_name, up.first_name, up.last_name
            FROM course_enrollments ce
            JOIN courses c ON ce.course_id = c.id
            JOIN users u ON c.instructor_id = u.id
            LEFT JOIN user_profiles up ON u.id = up.user_id
            WHERE ce.id = ?
        ");
        $stmt->execute([$enrollmentId]);
        return $stmt->fetch();
    }

    /**
     * Get user details
     */
    private function getUserDetails($userId) {
        $stmt = $this->db->prepare("
            SELECT u.*, up.first_name, up.last_name
            FROM users u
            LEFT JOIN user_profiles up ON u.id = up.user_id
            WHERE u.id = ?
        ");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    }

    /**
     * Send email using PHP mail function
     */
    private function sendEmail($to, $subject, $message) {
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=UTF-8',
            'From: ' . getSiteSetting('site_name') . ' <noreply@' . $_SERVER['HTTP_HOST'] . '>',
            'Reply-To: noreply@' . $_SERVER['HTTP_HOST']
        ];

        // Log email attempt
        $stmt = $this->db->prepare("
            INSERT INTO payment_logs (action, level, message, context, created_at)
            VALUES ('email_sent', 'info', ?, ?, NOW())
        ");
        $stmt->execute([
            "Email sent to {$to}: {$subject}",
            json_encode(['to' => $to, 'subject' => $subject])
        ]);

        return mail($to, $subject, $message, implode("\r\n", $headers));
    }

    /**
     * Email templates
     */
    private function getPaymentSuccessTemplate($transaction, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $itemTitle = $transaction['course_title'] ?: $transaction['exam_title'] ?: 'Item';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Payment Successful</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #2563eb; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Payment Successful!</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>Thank you for your payment! Your transaction has been processed successfully.</p>

                    <h3>Transaction Details:</h3>
                    <ul>
                        <li><strong>Item:</strong> {$itemTitle}</li>
                        <li><strong>Amount:</strong> {$transaction['currency']} " . number_format($transaction['final_amount'], 2) . "</li>
                        <li><strong>Transaction ID:</strong> {$transaction['transaction_id']}</li>
                        <li><strong>Reference:</strong> {$transaction['reference_number']}</li>
                        <li><strong>Date:</strong> " . date('F j, Y H:i', strtotime($transaction['created_at'])) . "</li>
                    </ul>

                    <p>You can now access your purchased content in your dashboard.</p>

                    <p>If you have any questions, please don't hesitate to contact our support team.</p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    private function getPaymentFailedTemplate($transaction, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $itemTitle = $transaction['course_title'] ?: $transaction['exam_title'] ?: 'Item';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Payment Failed</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #dc2626; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Payment Failed</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>We're sorry to inform you that your payment could not be processed.</p>

                    <h3>Transaction Details:</h3>
                    <ul>
                        <li><strong>Item:</strong> {$itemTitle}</li>
                        <li><strong>Amount:</strong> {$transaction['currency']} " . number_format($transaction['final_amount'], 2) . "</li>
                        <li><strong>Transaction ID:</strong> {$transaction['transaction_id']}</li>
                        <li><strong>Reference:</strong> {$transaction['reference_number']}</li>
                        <li><strong>Date:</strong> " . date('F j, Y H:i', strtotime($transaction['created_at'])) . "</li>
                    </ul>

                    <p><strong>Possible reasons for failure:</strong></p>
                    <ul>
                        <li>Insufficient funds</li>
                        <li>Invalid payment details</li>
                        <li>Payment gateway error</li>
                        <li>Transaction timeout</li>
                    </ul>

                    <p>Please try again or contact your bank/card provider if the issue persists.</p>

                    <p>If you need assistance, please don't hesitate to contact our support team.</p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    private function getRefundProcessedTemplate($refund, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $itemTitle = $refund['course_title'] ?: $refund['exam_title'] ?: 'Item';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Refund Processed</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #10b981; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Refund Processed</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>Your refund request has been processed successfully.</p>

                    <h3>Refund Details:</h3>
                    <ul>
                        <li><strong>Item:</strong> {$itemTitle}</li>
                        <li><strong>Refund Amount:</strong> {$refund['currency']} " . number_format($refund['amount'], 2) . "</li>
                        <li><strong>Reason:</strong> {$refund['reason']}</li>
                        <li><strong>Refund ID:</strong> {$refund['reference_number']}</li>
                        <li><strong>Original Transaction:</strong> {$refund['transaction_id']}</li>
                        <li><strong>Processed Date:</strong> " . date('F j, Y H:i', strtotime($refund['processed_at'])) . "</li>
                    </ul>

                    <p>The refund amount will be credited back to your original payment method within 3-5 business days, depending on your bank's processing time.</p>

                    <p>If you have any questions about this refund, please contact our support team.</p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    private function getEnrollmentConfirmationTemplate($enrollment, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];
        $instructorName = $enrollment['first_name'] && $enrollment['last_name'] ? $enrollment['first_name'] . ' ' . $enrollment['last_name'] : $enrollment['instructor_name'];

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Enrollment Confirmed</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #2563eb; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Enrollment Confirmed!</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>Congratulations! You have successfully enrolled in the following course:</p>

                    <h3>Course Details:</h3>
                    <ul>
                        <li><strong>Course:</strong> {$enrollment['course_title']}</li>
                        <li><strong>Instructor:</strong> {$instructorName}</li>
                        <li><strong>Enrollment Date:</strong> " . date('F j, Y H:i', strtotime($enrollment['enrollment_date'])) . "</li>
                    </ul>

                    <p>You can now access your course materials in your student dashboard. Start learning at your own pace!</p>

                    <p><a href='" . (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://{$_SERVER['HTTP_HOST']}/student/dashboard.php' class='button'>Go to Dashboard</a></p>

                    <p>If you have any questions or need assistance, please don't hesitate to contact our support team.</p>

                    <p>Happy learning!</p>
                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
}

class CalendarNotifications {
    private $db;

    public function __construct() {
        $this->db = getDB();
    }

    /**
     * Send event reminder notification
     */
    public function sendEventReminderNotification($eventId, $userId = null) {
        $event = $this->getEventDetails($eventId);
        if (!$event) return false;

        // If no specific user, send to all users (admin events) or creator
        if (!$userId) {
            // Send to all users who have calendar notifications enabled
            $users = $this->getUsersWithCalendarNotifications();
            $sent = 0;
            foreach ($users as $user) {
                if ($this->sendEventReminderToUser($event, $user)) {
                    $sent++;
                }
            }
            return $sent > 0;
        } else {
            $user = $this->getUserDetails($userId);
            return $user ? $this->sendEventReminderToUser($event, $user) : false;
        }
    }

    /**
     * Send event created notification
     */
    public function sendEventCreatedNotification($eventId) {
        $event = $this->getEventDetails($eventId);
        if (!$event) return false;

        // Send to all users with calendar notifications enabled
        $users = $this->getUsersWithCalendarNotifications();
        $sent = 0;
        foreach ($users as $user) {
            if ($this->sendEventCreatedToUser($event, $user)) {
                $sent++;
            }
        }
        return $sent > 0;
    }

    /**
     * Send event updated notification
     */
    public function sendEventUpdatedNotification($eventId) {
        $event = $this->getEventDetails($eventId);
        if (!$event) return false;

        // Send to all users with calendar notifications enabled
        $users = $this->getUsersWithCalendarNotifications();
        $sent = 0;
        foreach ($users as $user) {
            if ($this->sendEventUpdatedToUser($event, $user)) {
                $sent++;
            }
        }
        return $sent > 0;
    }

    /**
     * Get event details
     */
    private function getEventDetails($eventId) {
        $stmt = $this->db->prepare("
            SELECT ce.*, u.username as creator_name
            FROM calendar_events ce
            LEFT JOIN users u ON ce.creator_id = u.id
            WHERE ce.id = ?
        ");
        $stmt->execute([$eventId]);
        return $stmt->fetch();
    }

    /**
     * Get users who have calendar notifications enabled
     */
    private function getUsersWithCalendarNotifications() {
        // For now, get all users. In future, add user preferences for calendar notifications
        $stmt = $this->db->query("
            SELECT u.*, up.first_name, up.last_name
            FROM users u
            LEFT JOIN user_profiles up ON u.id = up.user_id
            WHERE u.email IS NOT NULL AND u.email != ''
        ");
        return $stmt->fetchAll();
    }

    /**
     * Send event reminder to specific user
     */
    private function sendEventReminderToUser($event, $user) {
        $subject = "Event Reminder: " . getSiteSetting('site_name');
        $message = $this->getEventReminderTemplate($event, $user);
        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send event created notification to specific user
     */
    private function sendEventCreatedToUser($event, $user) {
        $subject = "New Event Added: " . getSiteSetting('site_name');
        $message = $this->getEventCreatedTemplate($event, $user);
        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send event updated notification to specific user
     */
    private function sendEventUpdatedToUser($event, $user) {
        $subject = "Event Updated: " . getSiteSetting('site_name');
        $message = $this->getEventUpdatedTemplate($event, $user);
        return $this->sendEmail($user['email'], $subject, $message);
    }

    /**
     * Send email using PHP mail function
     */
    private function sendEmail($to, $subject, $message) {
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=UTF-8',
            'From: ' . getSiteSetting('site_name') . ' <noreply@' . $_SERVER['HTTP_HOST'] . '>',
            'Reply-To: noreply@' . $_SERVER['HTTP_HOST']
        ];

        // Log email attempt
        $stmt = $this->db->prepare("
            INSERT INTO payment_logs (action, level, message, context, created_at)
            VALUES ('calendar_email_sent', 'info', ?, ?, NOW())
        ");
        $stmt->execute([
            "Calendar email sent to {$to}: {$subject}",
            json_encode(['to' => $to, 'subject' => $subject])
        ]);

        return mail($to, $subject, $message, implode("\r\n", $headers));
    }

    /**
     * Get user details
     */
    private function getUserDetails($userId) {
        $stmt = $this->db->prepare("
            SELECT u.*, up.first_name, up.last_name
            FROM users u
            LEFT JOIN user_profiles up ON u.id = up.user_id
            WHERE u.id = ?
        ");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    }

    /**
     * Event reminder email template
     */
    private function getEventReminderTemplate($event, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];
        $eventDateTime = date('F j, Y', strtotime($event['event_date'])) . ' at ' . date('g:i A', strtotime($event['event_time']));

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Event Reminder</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #2563eb; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .event-box { background: white; border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; margin: 15px 0; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Event Reminder</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>This is a reminder for an upcoming event:</p>

                    <div class='event-box'>
                        <h3>{$event['title']}</h3>
                        <p><strong>Date & Time:</strong> {$eventDateTime}</p>
                        " . ($event['description'] ? "<p><strong>Description:</strong> {$event['description']}</p>" : "") . "
                        " . ($event['creator_name'] ? "<p><strong>Created by:</strong> {$event['creator_name']}</p>" : "") . "
                    </div>

                    <p>Please mark your calendar and be prepared for this event.</p>

                    <p><a href='" . (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://{$_SERVER['HTTP_HOST']}/admin/calendar.php' class='button'>View Calendar</a></p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Event created email template
     */
    private function getEventCreatedTemplate($event, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];
        $eventDateTime = date('F j, Y', strtotime($event['event_date'])) . ' at ' . date('g:i A', strtotime($event['event_time']));

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>New Event Added</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #10b981; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .event-box { background: white; border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; margin: 15px 0; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>New Event Added</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>A new event has been added to the calendar:</p>

                    <div class='event-box'>
                        <h3>{$event['title']}</h3>
                        <p><strong>Date & Time:</strong> {$eventDateTime}</p>
                        " . ($event['description'] ? "<p><strong>Description:</strong> {$event['description']}</p>" : "") . "
                        " . ($event['creator_name'] ? "<p><strong>Created by:</strong> {$event['creator_name']}</p>" : "") . "
                    </div>

                    <p>Please check the calendar for more details and mark your schedule accordingly.</p>

                    <p><a href='" . (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://{$_SERVER['HTTP_HOST']}/admin/calendar.php' class='button'>View Calendar</a></p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Event updated email template
     */
    private function getEventUpdatedTemplate($event, $user) {
        $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
        $userName = $user['first_name'] && $user['last_name'] ? $user['first_name'] . ' ' . $user['last_name'] : $user['username'];
        $eventDateTime = date('F j, Y', strtotime($event['event_date'])) . ' at ' . date('g:i A', strtotime($event['event_time']));

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Event Updated</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #f59e0b; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f8f9fa; }
                .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .event-box { background: white; border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; margin: 15px 0; }
                .button { display: inline-block; padding: 10px 20px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>{$siteName}</h1>
                    <h2>Event Updated</h2>
                </div>
                <div class='content'>
                    <p>Dear {$userName},</p>
                    <p>An event has been updated in the calendar:</p>

                    <div class='event-box'>
                        <h3>{$event['title']}</h3>
                        <p><strong>Date & Time:</strong> {$eventDateTime}</p>
                        " . ($event['description'] ? "<p><strong>Description:</strong> {$event['description']}</p>" : "") . "
                        " . ($event['creator_name'] ? "<p><strong>Created by:</strong> {$event['creator_name']}</p>" : "") . "
                    </div>

                    <p>Please check the calendar for the latest information.</p>

                    <p><a href='" . (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://{$_SERVER['HTTP_HOST']}/admin/calendar.php' class='button'>View Calendar</a></p>

                    <p>Best regards,<br>The {$siteName} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
}

/**
 * Helper function to send payment notifications
 */
function sendPaymentNotification($type, $id) {
    $notifications = new PaymentNotifications();

    switch ($type) {
        case 'payment_success':
            return $notifications->sendPaymentSuccessNotification($id);
        case 'payment_failed':
            return $notifications->sendPaymentFailedNotification($id);
        case 'refund_processed':
            return $notifications->sendRefundProcessedNotification($id);
        case 'enrollment_confirmed':
            return $notifications->sendEnrollmentConfirmationNotification($id);
        default:
            return false;
    }
}

/**
 * Helper function to send calendar notifications
 */
function sendCalendarNotification($type, $id) {
    $notifications = new CalendarNotifications();

    switch ($type) {
        case 'event_reminder':
            return $notifications->sendEventReminderNotification($id);
        case 'event_created':
            return $notifications->sendEventCreatedNotification($id);
        case 'event_updated':
            return $notifications->sendEventUpdatedNotification($id);
        default:
            return false;
    }
}