<?php
/**
 * Brevo Email Service for XChange 2025 Registration System
 * Handles all email notifications using Brevo API
 */

require_once 'logo_helper.php';

/**
 * Generate secure invoice link for registration
 */
function generateInvoiceLink($registrationData) {
    // Generate security hash (same as in public_invoice.php)
    $securityHash = md5($registrationData['registration_number'] . $registrationData['contact_email'] . $registrationData['created_at']);
    
    // Get base URL from server or configuration
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
    $scriptPath = dirname($_SERVER['SCRIPT_NAME']);
    
    // Handle different script locations (admin folder vs root)
    if (strpos($scriptPath, '/admin') !== false) {
        $basePath = dirname($scriptPath);
    } else {
        $basePath = $scriptPath;
    }
    
    return $baseUrl . $basePath . '/public_invoice.php?id=' . urlencode($registrationData['registration_number']) . '&hash=' . $securityHash;
}

class BrevoEmailService {
    private $apiKey;
    private $apiUrl = 'https://api.brevo.com/v3/smtp/email';
    private $senderEmail;
    private $senderName;
    private $adminEmails;
    
    public function __construct() {
        // Load configuration from database or config file
        $this->loadConfiguration();
    }
    
    private function loadConfiguration() {
        try {
            $pdo = getDBConnection();
            
            // Get email configuration from admin_settings
            $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('brevoApiKey', 'brevoSenderEmail', 'brevoSenderName', 'adminNotificationEmails')");
            $stmt->execute();
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            
            $this->apiKey = $settings['brevoApiKey'] ?? '';
            $this->senderEmail = $settings['brevoSenderEmail'] ?? 'noreply@xchange2025.com';
            $this->senderName = $settings['brevoSenderName'] ?? 'XChange 2025 Team';
            
            // Handle admin emails - could be comma-separated string or JSON array
            $adminEmailsRaw = $settings['adminNotificationEmails'] ?? '';
            if (!empty($adminEmailsRaw)) {
                // Try to decode as JSON first, if that fails, treat as comma-separated string
                $adminEmailsDecoded = json_decode($adminEmailsRaw, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($adminEmailsDecoded)) {
                    $this->adminEmails = $adminEmailsDecoded;
                } else {
                    // Treat as comma-separated string
                    $this->adminEmails = array_map('trim', explode(',', $adminEmailsRaw));
                }
            } else {
                $this->adminEmails = [];
            }
            
            if (empty($this->apiKey)) {
                error_log('Brevo API key not configured');
            }
            
        } catch (Exception $e) {
            error_log('Failed to load email configuration: ' . $e->getMessage());
            // Set defaults
            $this->senderEmail = 'noreply@xchange2025.com';
            $this->senderName = 'XChange 2025 Team';
            $this->adminEmails = [];
        }
    }
    
    /**
     * Send email using Brevo API
     */
    public function sendEmail($to, $subject, $htmlContent, $textContent = null) {
        if (empty($this->apiKey)) {
            error_log('Cannot send email: Brevo API key not configured');
            return false;
        }
        
        $data = [
            'sender' => [
                'name' => $this->senderName,
                'email' => $this->senderEmail
            ],
            'to' => [
                [
                    'email' => $to['email'],
                    'name' => $to['name'] ?? ''
                ]
            ],
            'subject' => $subject,
            'htmlContent' => $htmlContent
        ];
        
        if ($textContent) {
            $data['textContent'] = $textContent;
        }
        
        $headers = [
            'Accept: application/json',
            'Content-Type: application/json',
            'api-key: ' . $this->apiKey
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            error_log("Email sent successfully to {$to['email']}: $subject");
            
            // Extract message ID from Brevo response if available
            $responseData = json_decode($response, true);
            $messageId = $responseData['messageId'] ?? null;
            
            return ['success' => true, 'message_id' => $messageId];
        } else {
            error_log("Failed to send email to {$to['email']}: HTTP $httpCode - $response");
            return ['success' => false, 'error' => "HTTP $httpCode - $response"];
        }
    }
    
    /**
     * Log email notification to database
     */
    private function logEmailNotification($registrationId, $emailType, $recipient, $result, $subject) {
        try {
            $pdo = getDBConnection();
            
            $status = $result['success'] ? 'sent' : 'failed';
            $messageId = $result['message_id'] ?? null;
            $errorMessage = $result['success'] ? null : ($result['error'] ?? 'Unknown error');
            
            $stmt = $pdo->prepare("
                INSERT INTO email_notifications 
                (registration_id, email_type, recipient_email, recipient_name, subject, status, sent_at, brevo_message_id, error_message) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?)
            ");
            $stmt->execute([
                $registrationId,
                $emailType,
                $recipient['email'],
                $recipient['name'] ?? '',
                $subject,
                $status,
                $messageId,
                $errorMessage
            ]);
        } catch (Exception $e) {
            error_log('Failed to log email notification: ' . $e->getMessage());
        }
    }
    
    /**
     * Send pending registration email (Bank Transfer only)
     */
    public function sendPendingRegistrationEmail($registrationData) {
        $eventName = $this->getEventName();
        $subject = "Registration Received - Payment Pending | {$eventName}";
        
        $htmlContent = $this->generatePendingRegistrationTemplate($registrationData);
        
        $recipient = [
            'email' => $registrationData['contact_email'],
            'name' => $registrationData['contact_full_name']
        ];
        
        $result = $this->sendEmail($recipient, $subject, $htmlContent);
        
        $this->logEmailNotification(
            $registrationData['id'] ?? null,
            'pending_registration',
            $recipient,
            $result,
            $subject
        );
        
        return $result['success'];
    }
    
    /**
     * Send registration confirmation email (Payment Success)
     */
    public function sendRegistrationConfirmationEmail($registrationData) {
        $eventName = $this->getEventName();
        $subject = "Registration Confirmed - Welcome to {$eventName}!";
        
        $htmlContent = $this->generateRegistrationConfirmationTemplate($registrationData);
        
        $recipient = [
            'email' => $registrationData['contact_email'],
            'name' => $registrationData['contact_full_name']
        ];
        
        $result = $this->sendEmail($recipient, $subject, $htmlContent);
        
        $this->logEmailNotification(
            $registrationData['id'] ?? null,
            'registration_confirmation',
            $recipient,
            $result,
            $subject
        );
        
        return $result['success'];
    }
    
    /**
     * Send payment failure email
     */
    public function sendPaymentFailureEmail($registrationData, $failureReason = '') {
        $eventName = $this->getEventName();
        $subject = "Payment Issue - {$eventName} Registration";
        
        $htmlContent = $this->generatePaymentFailureTemplate($registrationData, $failureReason);
        
        $recipient = [
            'email' => $registrationData['contact_email'],
            'name' => $registrationData['contact_full_name']
        ];
        
        $result = $this->sendEmail($recipient, $subject, $htmlContent);
        
        $this->logEmailNotification(
            $registrationData['id'] ?? null,
            'payment_failure',
            $recipient,
            $result,
            $subject
        );
        
        return $result['success'];
    }
    
    /**
     * Send payment reminder email
     */
    public function sendPaymentReminderEmail($registrationData, $reminderType = '24h') {
        $eventName = $this->getEventName();
        $subject = "Payment Reminder - {$eventName} Registration";
        
        $htmlContent = $this->generatePaymentReminderTemplate($registrationData, $reminderType);
        
        $recipient = [
            'email' => $registrationData['contact_email'],
            'name' => $registrationData['contact_full_name']
        ];
        
        $result = $this->sendEmail($recipient, $subject, $htmlContent);
        
        $this->logEmailNotification(
            $registrationData['id'] ?? null,
            'payment_reminder_' . $reminderType,
            $recipient,
            $result,
            $subject
        );
        
        return $result['success'];
    }
    
    /**
     * Send admin notification email
     */
    public function sendAdminNotification($type, $registrationData, $additionalInfo = '') {
        if (empty($this->adminEmails)) {
            return false;
        }
        
        $eventName = $this->getEventName();
        $subjects = [
            'new_registration' => "New Registration - {$eventName}",
            'payment_received' => "Payment Received - {$eventName}",
            'payment_failed' => "Payment Failed - {$eventName}"
        ];
        
        $subject = $subjects[$type] ?? "{$eventName} Notification";
        $htmlContent = $this->generateAdminNotificationTemplate($type, $registrationData, $additionalInfo);
        
        $success = true;
        foreach ($this->adminEmails as $adminEmail) {
            $recipient = ['email' => $adminEmail, 'name' => 'Admin'];
            $result = $this->sendEmail($recipient, $subject, $htmlContent);
            if (!$result) $success = false;
        }
        
        return $success;
    }
    
    /**
     * Get event name from admin settings
     */
    private function getEventName() {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = 'eventName'");
        $stmt->execute();
        return $stmt->fetchColumn() ?: 'XChange';
    }

    /**
     * Get email template content from database
     */
    private function getTemplateContent($templateKey, $defaultValue = '') {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = ?");
        $stmt->execute([$templateKey]);
        $value = $stmt->fetchColumn() ?: $defaultValue;
        
        // Convert any literal \n sequences to actual newlines
        // This ensures that newlines in the database or default values are properly handled
        $value = str_replace('\\n', "\n", $value);
        return $value;
    }

    /**
     * Replace placeholders in template content
     */
    private function replacePlaceholders($content, $data, $additionalData = []) {
        $eventName = $this->getEventName();
        
        $placeholders = [
            '{EVENT_NAME}' => $eventName,
            '{CONTACT_NAME}' => $data['contact_full_name'] ?? '',
            '{REGISTRATION_NUMBER}' => $data['registration_number'] ?? '',
            '{TOTAL_AMOUNT}' => number_format($data['total_amount'] ?? 0, 2),
            '{UNIVERSITY_NAME}' => $data['university_name'] ?? '',
            '{FAILURE_REASON}' => $additionalData['failure_reason'] ?? ''
        ];
        
        // Replace placeholders in the content
        return str_replace(array_keys($placeholders), array_values($placeholders), $content);
    }

    /**
     * Get configuration data directly from database
     */
    private function getConfigData() {
        try {
            $pdo = getDBConnection();
            
            // Get products with their categories
            $stmt = $pdo->prepare("
                SELECT p.*, c.category_name, c.category_type 
                FROM products p 
                LEFT JOIN categories c ON p.category_id = c.id 
                WHERE p.is_active = 1 
                ORDER BY c.sort_order, p.sort_order
            ");
            $stmt->execute();
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Debug: Log products found
            error_log('Email Service: Found ' . count($products) . ' products');
            foreach ($products as $product) {
                error_log('Product: ' . $product['product_code'] . ' - ' . $product['name'] . ' - Type: ' . $product['category_type']);
            }
            
            // Organize products by category type
            $config = [
                'frontend' => [
                    'sponsorship' => ['products' => []],
                    'otherSponsorship' => ['products' => []]
                ]
            ];
            
            foreach ($products as $product) {
                if ($product['category_type'] === 'sponsorship') {
                    $config['frontend']['sponsorship']['products'][] = $product;
                } elseif ($product['category_type'] === 'other_sponsorship') {
                    $config['frontend']['otherSponsorship']['products'][] = $product;
                }
            }
            
            // Debug: Log final config
            error_log('Email Service: Sponsorship products: ' . count($config['frontend']['sponsorship']['products']));
            error_log('Email Service: Other sponsorship products: ' . count($config['frontend']['otherSponsorship']['products']));
            
            return $config;
        } catch (Exception $e) {
            error_log('Failed to load config data for email: ' . $e->getMessage());
            return ['frontend' => ['sponsorship' => ['products' => []], 'otherSponsorship' => ['products' => []]]];
        }
    }

    /**
     * Generate detailed order summary for emails
     */
    private function generateOrderSummary($data) {
        $pdo = getDBConnection();
        
        $html = "
        <div style='background: #fefce8; border: 2px solid #eab308; padding: 20px; border-radius: 8px; margin: 20px 0;'>
            <h3 style='margin: 0 0 15px 0; color: #a16207;'>🛒 Your Order Details</h3>
            <p style='margin: 0 0 15px 0; color: #713f12;'>Here's exactly what you're registering and paying for:</p>
            
            <table style='width: 100%; border-collapse: collapse; background: white; border-radius: 5px; overflow: hidden;'>
                <thead>
                    <tr style='background: #f59e0b; color: white;'>
                        <th style='padding: 12px; text-align: left; border-bottom: 1px solid #d97706;'>Item</th>
                        <th style='padding: 12px; text-align: center; border-bottom: 1px solid #d97706;'>Qty</th>
                        <th style='padding: 12px; text-align: right; border-bottom: 1px solid #d97706;'>Unit Price</th>
                        <th style='padding: 12px; text-align: right; border-bottom: 1px solid #d97706;'>Total</th>
                    </tr>
                </thead>
                <tbody>";
        
        // Get all actual products for this registration from database
        try {
            $stmt = $pdo->prepare("
                SELECT rp.*, p.name, p.description, c.name as category_name 
                FROM registration_products rp
                LEFT JOIN products p ON rp.product_id = p.id
                LEFT JOIN product_categories c ON p.category_id = c.id
                WHERE rp.registration_id = ?
                ORDER BY c.display_order, p.id
            ");
            $stmt->execute([$data['id']]);
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            error_log('Email Order Details: Found ' . count($products) . ' products for registration ' . $data['id']);
            error_log('Email Order Details: Registration data keys: ' . implode(', ', array_keys($data)));
            
            if (count($products) > 0) {
                foreach ($products as $product) {
                    $unitPrice = floatval($product['unit_price']);
                    $totalPrice = floatval($product['total_price']);
                    $quantity = intval($product['quantity']);
                    
                    error_log('Email Order Details: Product - ' . $product['name'] . ' (Qty: ' . $quantity . ', Unit: $' . $unitPrice . ', Total: $' . $totalPrice . ')');
                    
                    $html .= "
                        <tr style='border-bottom: 1px solid #f3f4f6;'>
                            <td style='padding: 12px;'>
                                <strong>" . htmlspecialchars($product['name']) . "</strong><br>
                                <small style='color: #6b7280;'>" . htmlspecialchars(strip_tags($product['description'] ?? '')) . "</small>
                            </td>
                            <td style='padding: 12px; text-align: center;'>{$quantity}</td>
                            <td style='padding: 12px; text-align: right;'>USD $" . number_format($unitPrice, 2) . "</td>
                            <td style='padding: 12px; text-align: right; font-weight: bold;'>USD $" . number_format($totalPrice, 2) . "</td>
                        </tr>";
                }
            } else {
                error_log('Email Order Details: No products found, using fallback');
                // Fallback to basic registration info if no products found
                $html .= "
                        <tr style='border-bottom: 1px solid #f3f4f6;'>
                            <td style='padding: 12px;'>
                                <strong>Registration</strong><br>
                                <small style='color: #6b7280;'>Conference registration</small>
                            </td>
                            <td style='padding: 12px; text-align: center;'>1</td>
                            <td style='padding: 12px; text-align: right;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                            <td style='padding: 12px; text-align: right; font-weight: bold;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                        </tr>";
            }
            
        } catch (Exception $e) {
            error_log('Failed to get products for email order summary: ' . $e->getMessage());
            // Fallback to basic registration info if product query fails
            $html .= "
                    <tr style='border-bottom: 1px solid #f3f4f6;'>
                        <td style='padding: 12px;'>
                            <strong>Registration</strong><br>
                            <small style='color: #6b7280;'>Conference registration</small>
                        </td>
                        <td style='padding: 12px; text-align: center;'>1</td>
                        <td style='padding: 12px; text-align: right;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                        <td style='padding: 12px; text-align: right; font-weight: bold;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                    </tr>";
        }
        
        
        // Total row
        $html .= "
                    <tr style='background: #f9fafb; border-top: 2px solid #e5e7eb;'>
                        <td colspan='3' style='padding: 15px; text-align: right; font-weight: bold; font-size: 16px;'>
                            TOTAL AMOUNT DUE:
                        </td>
                        <td style='padding: 15px; text-align: right; font-weight: bold; font-size: 18px; color: #dc2626; white-space: nowrap;'>
                            USD $" . number_format($data['total_amount'], 2) . "
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>";
        
        return $html;
    }

    /**
     * Generate pending registration email template
     */
    public function generatePendingRegistrationTemplate($data) {
        // Get settings from admin settings
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = 'bankTransferDetails'");
        $stmt->execute();
        $bankDetails = $stmt->fetchColumn() ?: 'Bank details not configured';
        
        $eventName = $this->getEventName();
        
        // Get editable template content
        $subject = $this->getTemplateContent('emailTemplate_pendingRegistration_subject', 'Registration Received - Payment Pending | {EVENT_NAME}');
        $greeting = $this->getTemplateContent('emailTemplate_pendingRegistration_greeting', 'Dear {CONTACT_NAME},');
        $intro = $this->getTemplateContent('emailTemplate_pendingRegistration_intro', 'Thank you for registering for {EVENT_NAME}! We have received your registration details.');
        $instructions = $this->getTemplateContent('emailTemplate_pendingRegistration_instructions', 'Your registration is not yet confirmed. Please complete the payment to secure your spot.');
        $footer = $this->getTemplateContent('emailTemplate_pendingRegistration_footer', 'Once we receive and verify your payment, we will send you a confirmation email with your complete registration details.\n\nIf you have any questions, please don\'t hesitate to contact us.\n\nBest regards,\n{EVENT_NAME} Team');
        
        // Replace placeholders
        $subject = $this->replacePlaceholders($subject, $data);
        $greeting = $this->replacePlaceholders($greeting, $data);
        $intro = $this->replacePlaceholders($intro, $data);
        $instructions = $this->replacePlaceholders($instructions, $data);
        $footer = $this->replacePlaceholders($footer, $data);
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>" . htmlspecialchars($subject) . "</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: #f1f5f9; color: #1e293b; padding: 20px; text-align: center; border-bottom: 1px solid #e2e8f0; }
                .content { padding: 20px; background: #f9fafb; }
                .status-pending { background: #fef3c7; border: 1px solid #f59e0b; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .bank-details { background: #e0f2fe; border: 1px solid #0284c7; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
                .btn { display: inline-block; background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; margin: 10px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    " . getEventLogoForEmail('300px', '120px', $eventName . ' Logo') . "
                    <h1 style='color: #1e293b; margin: 20px 0 0 0; font-size: 28px; font-weight: 700;'>
                        {$eventName}
                    </h1>
                    <p style='color: #64748b; margin: 8px 0 0 0; font-size: 16px;'>Registration Received</p>
                </div>
                
                <div class='content'>
                    <p>" . nl2br(htmlspecialchars($greeting)) . "</p>
                    
                    <p>" . nl2br(htmlspecialchars($intro)) . "</p>
                    
                    <div class='status-pending'>
                        <strong>⏳ Registration Status: PENDING PAYMENT</strong><br>
                        " . nl2br(htmlspecialchars($instructions)) . "
                    </div>
                    
                    " . $this->generateOrderSummary($data) . "
                    
                    <div style='background: #f0f9ff; border: 1px solid #0284c7; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                        <h3 style='margin: 0 0 15px 0; color: #0c4a6e;'>📋 Registration Summary</h3>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>Registration Number:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;'>{$data['registration_number']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>Contact Person:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;'>{$data['contact_full_name']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>University:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;'>{$data['university_name']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>Payment Method:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;'>Bank Transfer</td>
                            </tr>
                        </table>
                    </div>
                    
                    <div class='bank-details'>
                        <h3>🏦 Bank Transfer Instructions:</h3>
                        <div>" . nl2br(htmlspecialchars($bankDetails)) . "</div>
                        <p><strong>Payment Reference:</strong> {$data['registration_number']}</p>
                        <p><strong>Amount:</strong> USD $" . number_format($data['total_amount'], 2) . "</p>
                    </div>
                    
                    <div style='text-align: center; margin: 25px 0;'>
                        <a href='" . generateInvoiceLink($data) . "' class='btn' style='background: #059669; color: white; text-decoration: none; padding: 12px 24px; border-radius: 5px; display: inline-block;'>
                            📄 View/Download Invoice
                        </a>
                    </div>
                    
                    <p><strong>Important:</strong> Please include your registration number <strong>{$data['registration_number']}</strong> as the payment reference when making the bank transfer.</p>
                    
                    <p>" . nl2br(htmlspecialchars($footer)) . "</p>
                </div>
                
                <div class='footer'>
                    <p>This is an automated email. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Generate registration confirmation email template
     */
    public function generateRegistrationConfirmationTemplate($data) {
        $eventName = $this->getEventName();
        
        // Get editable template content
        $subject = $this->getTemplateContent('emailTemplate_confirmation_subject', 'Registration Confirmed - Welcome to {EVENT_NAME}!');
        $greeting = $this->getTemplateContent('emailTemplate_confirmation_greeting', 'Dear {CONTACT_NAME},');
        $intro = $this->getTemplateContent('emailTemplate_confirmation_intro', 'Congratulations! You are now officially registered for {EVENT_NAME}. We\'re excited to have you join us for this premier academic exchange event.');
        $nextSteps = $this->getTemplateContent('emailTemplate_confirmation_nextSteps', 'You will receive event details and schedule closer to the event date. Delegate badges and materials will be prepared based on your registration. Any updates will be sent to this email address.');
        $footer = $this->getTemplateContent('emailTemplate_confirmation_footer', 'Please keep this email and your registration number {REGISTRATION_NUMBER} for your records.\n\nThank you for choosing {EVENT_NAME}. We look forward to seeing you at the event!\n\nBest regards,\n{EVENT_NAME} Organizing Committee');
        
        // Replace placeholders
        $subject = $this->replacePlaceholders($subject, $data);
        $greeting = $this->replacePlaceholders($greeting, $data);
        $intro = $this->replacePlaceholders($intro, $data);
        $nextSteps = $this->replacePlaceholders($nextSteps, $data);
        $footer = $this->replacePlaceholders($footer, $data);
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>" . htmlspecialchars($subject) . "</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: #f1f5f9; color: #1e293b; padding: 20px; text-align: center; border-bottom: 1px solid #e2e8f0; }
                .content { padding: 20px; background: #f9fafb; }
                .status-confirmed { background: #d1fae5; border: 1px solid #059669; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .details-box { background: white; border: 1px solid #d1d5db; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    " . getEventLogoForEmail('300px', '120px', $eventName . ' Logo') . "
                    <h1 style='color: #1e293b; margin: 20px 0 0 0; font-size: 28px; font-weight: 700;'>
                        Welcome to {$eventName}!
                    </h1>
                    <p style='color: #64748b; margin: 8px 0 0 0; font-size: 16px;'>Registration Confirmed</p>
                </div>
                
                <div class='content'>
                    <p>" . nl2br(htmlspecialchars($greeting)) . "</p>
                    
                    <div class='status-confirmed'>
                        <strong>✅ Registration Status: CONFIRMED</strong><br>
                        Your payment has been received and your registration is now complete!
                    </div>
                    
                    <p>" . nl2br(htmlspecialchars($intro)) . "</p>
                    
                    " . $this->generateOrderSummary($data) . "
                    
                    <div style='background: #d1fae5; border: 1px solid #10b981; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                        <h3 style='margin: 0 0 15px 0; color: #065f46;'>✅ Payment Confirmed</h3>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0;'><strong>Registration Number:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0; text-align: right;'>{$data['registration_number']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0;'><strong>Contact Person:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0; text-align: right;'>{$data['contact_full_name']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0;'><strong>University:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0; text-align: right;'>{$data['university_name']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0;'><strong>Total Amount Paid:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #a7f3d0; text-align: right; font-weight: bold; color: #059669;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0;'><strong>Payment Status:</strong></td>
                                <td style='padding: 8px 0; text-align: right; font-weight: bold; color: #059669;'>✅ CONFIRMED</td>
                            </tr>
                        </table>
                    </div>
                    
                    <div style='text-align: center; margin: 25px 0;'>
                        <a href='" . generateInvoiceLink($data) . "' class='btn' style='background: #059669; color: white; text-decoration: none; padding: 12px 24px; border-radius: 5px; display: inline-block;'>
                            📄 View/Download Invoice
                        </a>
                    </div>
                    
                    <h3>📅 What's Next?</h3>
                    <p>" . nl2br(htmlspecialchars($nextSteps)) . "</p>
                    
                    <p>" . nl2br(htmlspecialchars($footer)) . "</p>
                </div>
                
                <div class='footer'>
                    <p>This is an automated email. Please do not reply to this email.</p>
                    <p>For questions, please contact our support team.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Generate payment failure email template
     */
    public function generatePaymentFailureTemplate($data, $failureReason) {
        $eventName = $this->getEventName();
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Payment Issue - {$eventName}</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: #f1f5f9; color: #1e293b; padding: 20px; text-align: center; border-bottom: 1px solid #e2e8f0; }
                .content { padding: 20px; background: #f9fafb; }
                .status-failed { background: #fee2e2; border: 1px solid #dc2626; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .retry-box { background: #e0f2fe; border: 1px solid #0284c7; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
                .btn { display: inline-block; background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; margin: 10px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    " . getEventLogoForEmail('300px', '120px', $eventName . ' Logo') . "
                    <h1 style='color: #1e293b; margin: 20px 0 0 0; font-size: 28px; font-weight: 700;'>
                        {$eventName}
                    </h1>
                    <p style='color: #64748b; margin: 8px 0 0 0; font-size: 16px;'>Payment Issue</p>
                </div>
                
                <div class='content'>
                    <p>Dear {$data['contact_full_name']},</p>
                    
                    <div class='status-failed'>
                        <strong>❌ Payment Status: FAILED</strong><br>
                        There was an issue processing your payment for {$eventName} registration.
                    </div>
                    
                    <p>We encountered a problem while processing your payment for registration number <strong>{$data['registration_number']}</strong>.</p>
                    
                    " . (!empty($failureReason) ? "<p><strong>Reason:</strong> " . htmlspecialchars($failureReason) . "</p>" : "") . "
                    
                    <div class='retry-box'>
                        <h3>🔄 Next Steps:</h3>
                        <ol>
                            <li>Check your payment method details</li>
                            <li>Ensure sufficient funds are available</li>
                            <li>Try the payment again</li>
                            <li>Contact your bank if the issue persists</li>
                        </ol>
                        
                        <p>You can retry your payment using the same registration details.</p>
                    </div>
                    
                    <p>If you continue to experience issues, please contact our support team with your registration number.</p>
                    
                    <p>We apologize for any inconvenience and look forward to completing your registration.</p>
                    
                    <p>Best regards,<br>{$eventName} Team</p>
                </div>
                
                <div class='footer'>
                    <p>This is an automated email. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Generate payment reminder email template
     */
    public function generatePaymentReminderTemplate($data, $reminderType) {
        $eventName = $this->getEventName();
        
        $urgencyMessages = [
            '24h' => 'We noticed your registration is still pending payment.',
            '48h' => 'This is a friendly reminder that your payment is still pending.',
            '7d' => 'Final reminder: Your registration will expire soon without payment.'
        ];
        
        $message = $urgencyMessages[$reminderType] ?? $urgencyMessages['24h'];
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Payment Reminder - {$eventName}</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: #f1f5f9; color: #1e293b; padding: 20px; text-align: center; border-bottom: 1px solid #e2e8f0; }
                .content { padding: 20px; background: #f9fafb; }
                .status-reminder { background: #fef3c7; border: 1px solid #f59e0b; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                " . getEventLogoForEmail('300px', '120px', $eventName . ' Logo') . "
                <h1 style='color: #1e293b; margin: 20px 0 0 0; font-size: 28px; font-weight: 700;'>
                    {$eventName}
                </h1>
                <p style='color: #64748b; margin: 8px 0 0 0; font-size: 16px;'>Payment Reminder</p>
            </div>
                
                <div class='content'>
                    <p>Dear {$data['contact_full_name']},</p>
                    
                    <div class='status-reminder'>
                        <strong>⏰ Payment Reminder</strong><br>
                        {$message}
                    </div>
                    
                    " . $this->generateOrderSummary($data) . "
                    
                    <div style='background: #fef3c7; border: 1px solid #f59e0b; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                        <h3 style='margin: 0 0 15px 0; color: #92400e;'>⚠️ Payment Required</h3>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #fde68a;'><strong>Registration Number:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #fde68a; text-align: right;'>{$data['registration_number']}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #fde68a;'><strong>Amount Due:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #fde68a; text-align: right; font-weight: bold; color: #dc2626;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0;'><strong>Payment Method:</strong></td>
                                <td style='padding: 8px 0; text-align: right;'>" . ($data['payment_method'] == 'gateway' ? 'Online Payment' : 'Bank Transfer') . "</td>
                            </tr>
                        </table>
                    </div>
                    
                    <div style='text-align: center; margin: 25px 0;'>
                        <a href='" . generateInvoiceLink($data) . "' class='btn' style='background: #f59e0b; color: white; text-decoration: none; padding: 12px 24px; border-radius: 5px; display: inline-block;'>
                            📄 View/Download Invoice
                        </a>
                    </div>
                    
                    <p>Please complete your payment to secure your registration for {$eventName}.</p>
                    
                    <p>If you have already made the payment, please disregard this reminder.</p>
                    
                    <p>Best regards,<br>{$eventName} Team</p>
                </div>
                
                <div class='footer'>
                    <p>This is an automated email. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Generate admin notification email template
     */
    public function generateAdminNotificationTemplate($type, $data, $additionalInfo) {
        $eventName = $this->getEventName();
        
        $titles = [
            'new_registration' => 'New Registration Received',
            'payment_received' => 'Payment Received',
            'payment_failed' => 'Payment Failed'
        ];
        
        $title = $titles[$type] ?? 'Notification';
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Admin Notification - {$eventName}</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: #f1f5f9; color: #1e293b; padding: 20px; text-align: center; border-bottom: 1px solid #e2e8f0; }
                .content { padding: 20px; background: #f9fafb; }
                .details-box { background: white; border: 1px solid #d1d5db; padding: 15px; border-radius: 5px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    " . getEventLogoForEmail('300px', '120px', $eventName . ' Logo') . "
                    <h1 style='color: #1e293b; margin: 20px 0 0 0; font-size: 28px; font-weight: 700;'>
                        {$eventName} Admin
                    </h1>
                    <p style='color: #64748b; margin: 8px 0 0 0; font-size: 16px;'>{$title}</p>
                </div>
                
                <div class='content'>
                    <div class='details-box'>
                        <h3>Registration Details:</h3>
                        <ul>
                            <li><strong>Registration Number:</strong> {$data['registration_number']}</li>
                            <li><strong>Contact:</strong> {$data['contact_full_name']}</li>
                            <li><strong>Email:</strong> {$data['contact_email']}</li>
                            <li><strong>University:</strong> {$data['university_name']}</li>
                            <li><strong>Country:</strong> {$data['country']}</li>
                            <li><strong>Payment Method:</strong> " . ($data['payment_method'] == 'gateway' ? 'Online Payment' : 'Bank Transfer') . "</li>
                            <li><strong>Payment Status:</strong> " . ucfirst($data['payment_status']) . "</li>
                        </ul>
                        
                        " . (!empty($additionalInfo) ? "<p><strong>Additional Info:</strong> " . htmlspecialchars($additionalInfo) . "</p>" : "") . "
                    </div>
                    
                    " . $this->generateOrderSummary($data) . "
                    
                    <div style='background: #f0f9ff; border: 1px solid #0284c7; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                        <h3 style='margin: 0 0 15px 0; color: #0c4a6e;'>💰 Payment Summary</h3>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>Total Amount:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right; font-weight: bold; color: #059669; font-size: 18px;'>USD $" . number_format($data['total_amount'], 2) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0;'><strong>Payment Method:</strong></td>
                                <td style='padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;'>" . ($data['payment_method'] == 'gateway' ? 'Online Payment' : 'Bank Transfer') . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0;'><strong>Status:</strong></td>
                                <td style='padding: 8px 0; text-align: right;'><span style='background: " . ($data['payment_status'] == 'paid' ? '#dcfce7; color: #166534' : ($data['payment_status'] == 'pending' ? '#fef3c7; color: #92400e' : '#fee2e2; color: #dc2626')) . "; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;'>" . strtoupper($data['payment_status']) . "</span></td>
                            </tr>
                        </table>
                    </div>
                    
                    <div style='text-align: center; margin: 25px 0;'>
                        <a href='" . generateInvoiceLink($data) . "' class='btn' style='background: #0284c7; color: white; text-decoration: none; padding: 12px 24px; border-radius: 5px; display: inline-block;'>
                            📄 View Customer Invoice
                        </a>
                    </div>
                    
                    <p>Please review this registration in the admin panel for complete details and delegate information.</p>
                </div>
            </div>
        </body>
        </html>";
    }
}

// Include database connection
require_once 'db_config.php';
?>
