<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login with settings permission
$auth = new AdminAuth();
$auth->requireLogin();
$auth->requirePermission('settings', 'edit');

$currentPage = 'email_template_editor';
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_template'])) {
        $templateKey = $_POST['template_key'];
        $templateContent = $_POST['template_content'];
        
        try {
            $pdo = getDBConnection();
            
            // Check if template exists
            $stmt = $pdo->prepare("SELECT id FROM admin_settings WHERE setting_key = ?");
            $stmt->execute([$templateKey]);
            
            if ($stmt->fetch()) {
                // Update existing template
                $stmt = $pdo->prepare("UPDATE admin_settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = ?");
                $stmt->execute([$templateContent, $templateKey]);
            } else {
                // Insert new template
                $stmt = $pdo->prepare("INSERT INTO admin_settings (setting_key, setting_value, setting_type, description) VALUES (?, ?, 'template', ?)");
                $description = getTemplateDescription($templateKey);
                $stmt->execute([$templateKey, $templateContent, $description]);
            }
            
            $success = "Template updated successfully!";
        } catch (Exception $e) {
            $error = "Error updating template: " . $e->getMessage();
        }
    }
}

// Get all email templates
function getEmailTemplates() {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key LIKE 'emailTemplate_%'");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}

// Get template description
function getTemplateDescription($templateKey) {
    $descriptions = [
        'emailTemplate_pendingRegistration_subject' => 'Subject line for pending registration emails',
        'emailTemplate_pendingRegistration_greeting' => 'Greeting text for pending registration emails',
        'emailTemplate_pendingRegistration_intro' => 'Introduction text for pending registration emails',
        'emailTemplate_pendingRegistration_instructions' => 'Payment instructions text',
        'emailTemplate_pendingRegistration_footer' => 'Footer text for pending registration emails',
        
        'emailTemplate_confirmation_subject' => 'Subject line for confirmation emails',
        'emailTemplate_confirmation_greeting' => 'Greeting text for confirmation emails',
        'emailTemplate_confirmation_intro' => 'Introduction text for confirmation emails',
        'emailTemplate_confirmation_nextSteps' => 'Next steps text for confirmation emails',
        'emailTemplate_confirmation_footer' => 'Footer text for confirmation emails',
        
        'emailTemplate_reminder_subject_24h' => 'Subject line for 24h payment reminders',
        'emailTemplate_reminder_subject_48h' => 'Subject line for 48h payment reminders',
        'emailTemplate_reminder_subject_7d' => 'Subject line for 7d payment reminders',
        'emailTemplate_reminder_message_24h' => 'Message for 24h payment reminders',
        'emailTemplate_reminder_message_48h' => 'Message for 48h payment reminders',
        'emailTemplate_reminder_message_7d' => 'Message for 7d payment reminders',
        'emailTemplate_reminder_footer' => 'Footer text for reminder emails',
        
        'emailTemplate_failure_subject' => 'Subject line for payment failure emails',
        'emailTemplate_failure_intro' => 'Introduction text for payment failure emails',
        'emailTemplate_failure_instructions' => 'Instructions for payment failure emails',
        'emailTemplate_failure_footer' => 'Footer text for payment failure emails'
    ];
    
    return $descriptions[$templateKey] ?? 'Email template content';
}

// Initialize default templates if they don't exist
function initializeDefaultTemplates() {
    $defaults = [
        'emailTemplate_pendingRegistration_subject' => 'Registration Received - Payment Pending | {EVENT_NAME}',
        'emailTemplate_pendingRegistration_greeting' => 'Dear {CONTACT_NAME},',
        'emailTemplate_pendingRegistration_intro' => 'Thank you for registering for {EVENT_NAME}! We have received your registration details.',
        'emailTemplate_pendingRegistration_instructions' => 'Your registration is not yet confirmed. Please complete the payment to secure your spot.',
        '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',
        
        'emailTemplate_confirmation_subject' => 'Registration Confirmed - Welcome to {EVENT_NAME}!',
        'emailTemplate_confirmation_greeting' => 'Dear {CONTACT_NAME},',
        '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.',
        '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.',
        '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',
        
        'emailTemplate_reminder_subject_24h' => 'Payment Reminder (24h) - {EVENT_NAME}',
        'emailTemplate_reminder_subject_48h' => 'Payment Reminder (48h) - {EVENT_NAME}',
        'emailTemplate_reminder_subject_7d' => 'Final Payment Reminder - {EVENT_NAME}',
        'emailTemplate_reminder_message_24h' => 'We noticed your registration is still pending payment.',
        'emailTemplate_reminder_message_48h' => 'This is a friendly reminder that your payment is still pending.',
        'emailTemplate_reminder_message_7d' => 'Final reminder: Your registration will expire soon without payment.',
        'emailTemplate_reminder_footer' => 'Please complete your payment to secure your registration for {EVENT_NAME}.\n\nIf you have already made the payment, please disregard this reminder.\n\nBest regards,\n{EVENT_NAME} Team',
        
        'emailTemplate_failure_subject' => 'Payment Issue - {EVENT_NAME}',
        'emailTemplate_failure_intro' => 'We encountered an issue processing your payment for {EVENT_NAME} registration.',
        'emailTemplate_failure_instructions' => 'Please try again or contact us for assistance. Your registration spot is still reserved for a limited time.',
        'emailTemplate_failure_footer' => 'If you continue to experience issues, please contact our support team.\n\nBest regards,\n{EVENT_NAME} Team'
    ];
    
    $pdo = getDBConnection();
    foreach ($defaults as $key => $value) {
        $stmt = $pdo->prepare("SELECT id FROM admin_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        
        if (!$stmt->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO admin_settings (setting_key, setting_value, setting_type, description) VALUES (?, ?, 'template', ?)");
            $description = getTemplateDescription($key);
            $stmt->execute([$key, $value, $description]);
        }
    }
}

// Initialize templates
initializeDefaultTemplates();
$templates = getEmailTemplates();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Template Editor - XChange Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <?php if ($message): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <h1>📝 Email Template Editor</h1>
        <p>Customize the text content of all email templates. Use placeholders like {EVENT_NAME}, {CONTACT_NAME}, etc.</p>

        <div class="settings-grid">
            <!-- Pending Registration Templates -->
            <div class="settings-card">
                <h3>📧 Pending Registration Email</h3>
                <p>Sent immediately to users who choose bank transfer payment.</p>
                
                <?php
                $pendingTemplates = [
                    'emailTemplate_pendingRegistration_subject' => 'Email Subject',
                    'emailTemplate_pendingRegistration_greeting' => 'Greeting',
                    'emailTemplate_pendingRegistration_intro' => 'Introduction Text',
                    'emailTemplate_pendingRegistration_instructions' => 'Payment Instructions',
                    'emailTemplate_pendingRegistration_footer' => 'Footer Text'
                ];
                
                foreach ($pendingTemplates as $key => $label):
                    $value = $templates[$key] ?? '';
                ?>
                <form method="POST" style="margin-bottom: 20px;">
                    <div class="form-group">
                        <label class="form-label"><?php echo $label; ?></label>
                        <?php if (strpos($key, 'subject') !== false): ?>
                            <input type="text" name="template_content" value="<?php echo htmlspecialchars($value); ?>" class="form-input" style="width: 100%;">
                        <?php else: ?>
                            <textarea name="template_content" class="form-input" rows="4" style="width: 100%; resize: vertical;"><?php echo htmlspecialchars($value); ?></textarea>
                        <?php endif; ?>
                        <small style="color: #64748b; margin-top: 5px; display: block;">
                            Available placeholders: {EVENT_NAME}, {CONTACT_NAME}, {REGISTRATION_NUMBER}, {TOTAL_AMOUNT}, {UNIVERSITY_NAME}
                        </small>
                    </div>
                    <input type="hidden" name="template_key" value="<?php echo $key; ?>">
                    <button type="submit" name="update_template" class="btn btn-primary">Save <?php echo $label; ?></button>
                </form>
                <?php endforeach; ?>
            </div>

            <!-- Confirmation Templates -->
            <div class="settings-card">
                <h3>✅ Registration Confirmation Email</h3>
                <p>Sent when payment is confirmed (Stripe success or admin approval).</p>
                
                <?php
                $confirmationTemplates = [
                    'emailTemplate_confirmation_subject' => 'Email Subject',
                    'emailTemplate_confirmation_greeting' => 'Greeting',
                    'emailTemplate_confirmation_intro' => 'Introduction Text',
                    'emailTemplate_confirmation_nextSteps' => 'Next Steps Text',
                    'emailTemplate_confirmation_footer' => 'Footer Text'
                ];
                
                foreach ($confirmationTemplates as $key => $label):
                    $value = $templates[$key] ?? '';
                ?>
                <form method="POST" style="margin-bottom: 20px;">
                    <div class="form-group">
                        <label class="form-label"><?php echo $label; ?></label>
                        <?php if (strpos($key, 'subject') !== false): ?>
                            <input type="text" name="template_content" value="<?php echo htmlspecialchars($value); ?>" class="form-input" style="width: 100%;">
                        <?php else: ?>
                            <textarea name="template_content" class="form-input" rows="4" style="width: 100%; resize: vertical;"><?php echo htmlspecialchars($value); ?></textarea>
                        <?php endif; ?>
                        <small style="color: #64748b; margin-top: 5px; display: block;">
                            Available placeholders: {EVENT_NAME}, {CONTACT_NAME}, {REGISTRATION_NUMBER}, {TOTAL_AMOUNT}, {UNIVERSITY_NAME}
                        </small>
                    </div>
                    <input type="hidden" name="template_key" value="<?php echo $key; ?>">
                    <button type="submit" name="update_template" class="btn btn-primary">Save <?php echo $label; ?></button>
                </form>
                <?php endforeach; ?>
            </div>

            <!-- Payment Reminder Templates -->
            <div class="settings-card">
                <h3>⏰ Payment Reminder Emails</h3>
                <p>Sent at 24h, 48h, and 7 days for pending payments.</p>
                
                <?php
                $reminderTemplates = [
                    'emailTemplate_reminder_subject_24h' => '24h Reminder Subject',
                    'emailTemplate_reminder_subject_48h' => '48h Reminder Subject',
                    'emailTemplate_reminder_subject_7d' => '7d Reminder Subject',
                    'emailTemplate_reminder_message_24h' => '24h Reminder Message',
                    'emailTemplate_reminder_message_48h' => '48h Reminder Message',
                    'emailTemplate_reminder_message_7d' => '7d Reminder Message',
                    'emailTemplate_reminder_footer' => 'Reminder Footer Text'
                ];
                
                foreach ($reminderTemplates as $key => $label):
                    $value = $templates[$key] ?? '';
                ?>
                <form method="POST" style="margin-bottom: 20px;">
                    <div class="form-group">
                        <label class="form-label"><?php echo $label; ?></label>
                        <?php if (strpos($key, 'subject') !== false || strpos($key, 'message') !== false): ?>
                            <input type="text" name="template_content" value="<?php echo htmlspecialchars($value); ?>" class="form-input" style="width: 100%;">
                        <?php else: ?>
                            <textarea name="template_content" class="form-input" rows="4" style="width: 100%; resize: vertical;"><?php echo htmlspecialchars($value); ?></textarea>
                        <?php endif; ?>
                        <small style="color: #64748b; margin-top: 5px; display: block;">
                            Available placeholders: {EVENT_NAME}, {CONTACT_NAME}, {REGISTRATION_NUMBER}, {TOTAL_AMOUNT}
                        </small>
                    </div>
                    <input type="hidden" name="template_key" value="<?php echo $key; ?>">
                    <button type="submit" name="update_template" class="btn btn-primary">Save <?php echo $label; ?></button>
                </form>
                <?php endforeach; ?>
            </div>

            <!-- Payment Failure Templates -->
            <div class="settings-card">
                <h3>❌ Payment Failure Email</h3>
                <p>Sent when Stripe payments fail or are cancelled.</p>
                
                <?php
                $failureTemplates = [
                    'emailTemplate_failure_subject' => 'Email Subject',
                    'emailTemplate_failure_intro' => 'Introduction Text',
                    'emailTemplate_failure_instructions' => 'Recovery Instructions',
                    'emailTemplate_failure_footer' => 'Footer Text'
                ];
                
                foreach ($failureTemplates as $key => $label):
                    $value = $templates[$key] ?? '';
                ?>
                <form method="POST" style="margin-bottom: 20px;">
                    <div class="form-group">
                        <label class="form-label"><?php echo $label; ?></label>
                        <?php if (strpos($key, 'subject') !== false): ?>
                            <input type="text" name="template_content" value="<?php echo htmlspecialchars($value); ?>" class="form-input" style="width: 100%;">
                        <?php else: ?>
                            <textarea name="template_content" class="form-input" rows="4" style="width: 100%; resize: vertical;"><?php echo htmlspecialchars($value); ?></textarea>
                        <?php endif; ?>
                        <small style="color: #64748b; margin-top: 5px; display: block;">
                            Available placeholders: {EVENT_NAME}, {CONTACT_NAME}, {REGISTRATION_NUMBER}, {FAILURE_REASON}
                        </small>
                    </div>
                    <input type="hidden" name="template_key" value="<?php echo $key; ?>">
                    <button type="submit" name="update_template" class="btn btn-primary">Save <?php echo $label; ?></button>
                </form>
                <?php endforeach; ?>
            </div>

            <!-- Help Section -->
            <div class="settings-card">
                <h3>💡 Template Help</h3>
                <h4>Available Placeholders:</h4>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    <li><code>{EVENT_NAME}</code> - Event name from settings</li>
                    <li><code>{CONTACT_NAME}</code> - Registrant's full name</li>
                    <li><code>{REGISTRATION_NUMBER}</code> - Unique registration number</li>
                    <li><code>{TOTAL_AMOUNT}</code> - Total amount due/paid</li>
                    <li><code>{UNIVERSITY_NAME}</code> - University name</li>
                    <li><code>{FAILURE_REASON}</code> - Payment failure reason (failure emails only)</li>
                </ul>
                
                <h4>Notes:</h4>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    <li>The detailed order summary is automatically included</li>
                    <li>Use \n for line breaks in text areas</li>
                    <li>Changes take effect immediately for new emails</li>
                    <li>Test your changes using the Email Templates preview page</li>
                </ul>
                
                <div style="margin-top: 20px;">
                    <a href="email_templates.php" class="btn btn-secondary">📧 Preview Templates</a>
                    <a href="email_logs.php" class="btn btn-secondary">📊 View Email Logs</a>
                </div>
            </div>
        </div>
    </div>

</body>
</html>
