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

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

$currentPage = 'email_templates';

// Get selected template and registration ID
$selectedTemplate = $_GET['template'] ?? 'pending_registration';
$selectedRegistrationId = $_GET['registration_id'] ?? null;

// Function to get real registration data
function getRealRegistrationData($registrationId = null) {
    $pdo = getDBConnection();
    
    if ($registrationId) {
        $stmt = $pdo->prepare("SELECT * FROM registrations WHERE id = ?");
        $stmt->execute([$registrationId]);
        $registration = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        // Get the most recent registration if no ID specified
        $stmt = $pdo->prepare("SELECT * FROM registrations ORDER BY created_at DESC LIMIT 1");
        $stmt->execute();
        $registration = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    if (!$registration) {
        return null;
    }
    
    // Convert database data to expected format
    return [
        'id' => $registration['id'],
        'registration_number' => $registration['registration_number'],
        'delegate_type' => $registration['delegate_type'],
        'delegate_count' => $registration['delegate_count'],
        'has_standard_table' => (bool)$registration['has_standard_table'],
        'has_double_table' => (bool)$registration['has_double_table'],
        'contact_salutation' => $registration['contact_salutation'],
        'contact_full_name' => $registration['contact_full_name'],
        'contact_badge_name' => $registration['contact_badge_name'],
        'contact_designation' => $registration['contact_designation'],
        'contact_department' => $registration['contact_department'],
        'contact_email' => $registration['contact_email'],
        'contact_mobile' => $registration['contact_mobile'],
        'university_name' => $registration['university_name'],
        'country' => $registration['country'],
        'payment_method' => $registration['payment_method'],
        'payment_status' => $registration['payment_status'],
        'total_amount' => $registration['total_amount'],
        'created_at' => $registration['created_at'],
        'payment_deadline' => $registration['payment_deadline'],
        'sponsorships' => [], // These would need to be fetched from related tables if they exist
        'otherSponsorships' => []
    ];
}

// Get available registrations for dropdown
function getAvailableRegistrations() {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT id, registration_number, contact_full_name, payment_status, created_at FROM registrations ORDER BY created_at DESC LIMIT 20");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get registration data (live data only)
$registrationData = getRealRegistrationData($selectedRegistrationId);
$availableRegistrations = getAvailableRegistrations();

// If no live data exists, show error message instead of template
if (!$registrationData) {
    $noDataError = true;
} else {
    $noDataError = false;
}

// Initialize email service for template generation
$emailService = new BrevoEmailService();

// Get template content based on selection
function getTemplateContent($templateType, $registrationData, $emailService) {
    switch ($templateType) {
        case 'pending_registration':
            return [
                'title' => 'Pending Registration Email (Bank Transfer)',
                'description' => 'Sent immediately after registration when payment method is bank transfer',
                'content' => $emailService->generatePendingRegistrationTemplate($registrationData)
            ];
            
        case 'registration_confirmation':
            return [
                'title' => 'Registration Confirmation Email (Payment Success)',
                'description' => 'Sent when payment is confirmed (Stripe success or admin marks bank transfer as paid)',
                'content' => $emailService->generateRegistrationConfirmationTemplate($registrationData)
            ];
            
        case 'payment_failure':
            return [
                'title' => 'Payment Failure Email',
                'description' => 'Sent when Stripe payment fails or is cancelled',
                'content' => $emailService->generatePaymentFailureTemplate($registrationData, 'Your card was declined. Please check your payment details and try again.')
            ];
            
        case 'payment_reminder_24h':
            return [
                'title' => 'Payment Reminder (24 hours)',
                'description' => 'Sent 24 hours after registration if payment is still pending',
                'content' => $emailService->generatePaymentReminderTemplate($registrationData, '24h')
            ];
            
        case 'payment_reminder_48h':
            return [
                'title' => 'Payment Reminder (48 hours)',
                'description' => 'Sent 48 hours after registration if payment is still pending',
                'content' => $emailService->generatePaymentReminderTemplate($registrationData, '48h')
            ];
            
        case 'payment_reminder_7d':
            return [
                'title' => 'Payment Reminder (7 days)',
                'description' => 'Final reminder sent 7 days after registration if payment is still pending',
                'content' => $emailService->generatePaymentReminderTemplate($registrationData, '7d')
            ];
            
        case 'admin_notification':
            return [
                'title' => 'Admin Notification Email',
                'description' => 'Sent to administrators for new registrations, payments received, and payment issues',
                'content' => $emailService->generateAdminNotificationTemplate('payment_received', $registrationData, 'Payment ID: pi_1234567890, Amount: $1500.00')
            ];
            
        default:
            return [
                'title' => 'Unknown Template',
                'description' => 'Template not found',
                'content' => '<p>Template not found</p>'
            ];
    }
}

// Only generate template if we have live data
if (!$noDataError) {
    $templateData = getTemplateContent($selectedTemplate, $registrationData, $emailService);
}

// Available templates
$templates = [
    'pending_registration' => 'Pending Registration (Bank Transfer)',
    'registration_confirmation' => 'Registration Confirmation (Payment Success)',
    'payment_failure' => 'Payment Failure',
    'payment_reminder_24h' => 'Payment Reminder (24h)',
    'payment_reminder_48h' => 'Payment Reminder (48h)',
    'payment_reminder_7d' => 'Payment Reminder (7d)',
    'admin_notification' => 'Admin Notification'
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Templates - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <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@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .template-container {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: 30px;
            height: calc(100vh - 120px);
        }
        
        .template-sidebar {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            height: fit-content;
            position: sticky;
            top: 20px;
        }
        
        .template-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .template-item {
            margin-bottom: 8px;
        }
        
        .template-link {
            display: block;
            padding: 12px 16px;
            border-radius: 6px;
            text-decoration: none;
            color: #374151;
            font-weight: 500;
            font-size: 0.875rem;
            transition: all 0.2s;
            border: 1px solid transparent;
        }
        
        .template-link:hover {
            background: #f3f4f6;
            color: #1f2937;
        }
        
        .template-link.active {
            background: #2563eb;
            color: white;
            border-color: #2563eb;
        }
        
        .template-content {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .template-header {
            background: #f9fafb;
            border-bottom: 1px solid #e5e7eb;
            padding: 20px;
        }
        
        .template-title {
            margin: 0 0 8px 0;
            color: #1f2937;
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .template-description {
            margin: 0;
            color: #6b7280;
            font-size: 0.875rem;
        }
        
        .template-preview {
            padding: 20px;
            max-height: calc(100vh - 300px);
            overflow-y: auto;
        }
        
        .preview-controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .preview-mode {
            padding: 8px 16px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
            color: #374151;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .preview-mode.active {
            background: #2563eb;
            color: white;
            border-color: #2563eb;
        }
        
        .preview-mode:hover:not(.active) {
            background: #f3f4f6;
        }
        
        .email-preview {
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            overflow: hidden;
        }
        
        .email-preview iframe {
            width: 100%;
            height: 600px;
            border: none;
        }
        
        .code-preview {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 16px;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            overflow-x: auto;
            max-height: 600px;
            overflow-y: auto;
        }
        
        .sample-data-section {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .sample-data-section h4 {
            margin: 0 0 10px 0;
            color: #92400e;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .sample-data-section p {
            margin: 0;
            color: #78350f;
            font-size: 0.75rem;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .btn-test {
            background: #059669;
            color: white;
        }
        
        .btn-test:hover {
            background: #047857;
        }
        
        .editor-toolbar {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            padding: 10px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px 6px 0 0;
        }
        
        .html-editor-textarea {
            width: 100%;
            height: 500px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            border: 1px solid #e2e8f0;
            border-top: none;
            border-radius: 0 0 6px 6px;
            padding: 15px;
            resize: vertical;
            background: #ffffff;
            line-height: 1.5;
        }
        
        .editor-preview {
            margin-top: 20px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            height: 400px;
        }
        
        .editor-preview iframe {
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 6px;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header">
            <h1>📧 Email Templates</h1>
            <p>Preview and review all email templates used by the system</p>
        </div>

        <div class="template-container">
            <!-- Template Sidebar -->
            <div class="template-sidebar">
                <h3 style="margin: 0 0 20px 0; color: #374151;">Email Templates</h3>
                <ul class="template-list">
                    <?php foreach ($templates as $key => $name): ?>
                    <li class="template-item">
                        <a href="?template=<?php echo $key; ?>" 
                           class="template-link <?php echo $selectedTemplate === $key ? 'active' : ''; ?>">
                            <?php echo htmlspecialchars($name); ?>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
                
                <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
                    <h4 style="margin: 0 0 10px 0; color: #374151; font-size: 0.875rem;">Preview Data</h4>
                    <form method="GET" style="margin-bottom: 15px;">
                        <input type="hidden" name="template" value="<?php echo htmlspecialchars($selectedTemplate); ?>">
                        <select name="registration_id" class="form-control" style="font-size: 0.875rem; margin-bottom: 8px;" onchange="this.form.submit()">
                            <option value="">Latest Registration</option>
                            <?php foreach ($availableRegistrations as $reg): ?>
                            <option value="<?php echo $reg['id']; ?>" <?php echo $selectedRegistrationId == $reg['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($reg['registration_number']); ?> - <?php echo htmlspecialchars($reg['contact_full_name']); ?> (<?php echo ucfirst($reg['payment_status']); ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                    
                    <h4 style="margin: 15px 0 10px 0; color: #374151; font-size: 0.875rem;">Quick Actions</h4>
                    <a href="email_logs.php" class="btn btn-sm btn-secondary" style="display: block; text-align: center; margin-bottom: 8px;">
                        📊 View Email Logs
                    </a>
                    <a href="settings.php#email" class="btn btn-sm btn-secondary" style="display: block; text-align: center;">
                        ⚙️ Email Settings
                    </a>
                </div>
            </div>

            <!-- Template Content -->
            <div class="template-content">
                <?php if (!$noDataError): ?>
                <div class="template-header">
                    <h2 class="template-title"><?php echo htmlspecialchars($templateData['title']); ?></h2>
                    <p class="template-description"><?php echo htmlspecialchars($templateData['description']); ?></p>
                </div>
                <?php else: ?>
                <div class="template-header">
                    <h2 class="template-title">Email Templates - No Data Available</h2>
                    <p class="template-description">Live registration data is required to preview email templates</p>
                </div>
                <?php endif; ?>

                <div class="template-preview">
                    <?php if ($noDataError): ?>
                        <div class="sample-data-section" style="background: #fef2f2; border-color: #dc2626;">
                            <h4 style="color: #dc2626;">❌ No Live Data Available</h4>
                            <p style="color: #991b1b;">
                                Cannot preview email templates because no registration data exists in the database. 
                                Please create at least one registration to preview email templates with live data.
                            </p>
                        </div>
                    <?php else: ?>
                        <div class="sample-data-section">
                            <h4>✅ Live Data Preview</h4>
                            <p>
                                This preview uses real registration data from <strong><?php echo htmlspecialchars($registrationData['registration_number']); ?></strong> 
                                (<?php echo htmlspecialchars($registrationData['contact_full_name']); ?>).
                            </p>
                        </div>
                    <?php endif; ?>

                    <?php if (!$noDataError): ?>
                    <div class="action-buttons">
                        <button class="btn btn-test" onclick="sendTestEmail('<?php echo $selectedTemplate; ?>')">
                            📧 Send Test Email
                        </button>
                        <button class="btn btn-secondary" onclick="downloadTemplate('<?php echo $selectedTemplate; ?>')">
                            💾 Download HTML
                        </button>
                    </div>

                    <div class="preview-controls">
                        <button class="preview-mode active" onclick="showPreview('visual')">
                            👁️ Visual Preview
                        </button>
                        <button class="preview-mode" onclick="showPreview('code')">
                            📝 HTML Code
                        </button>
                        <button class="preview-mode" onclick="showPreview('editor')">
                            ✏️ HTML Editor
                        </button>
                    </div>

                    <!-- Visual Preview -->
                    <div id="visual-preview" class="email-preview">
                        <iframe srcdoc="<?php echo htmlspecialchars($templateData['content']); ?>"></iframe>
                    </div>

                    <!-- Code Preview -->
                    <div id="code-preview" class="code-preview" style="display: none;">
                        <pre><code><?php echo htmlspecialchars($templateData['content']); ?></code></pre>
                    </div>

                    <!-- HTML Editor -->
                    <div id="html-editor" style="display: none;">
                        <div class="editor-toolbar">
                            <button class="btn btn-primary" onclick="saveHtmlTemplate()">💾 Save Changes</button>
                            <button class="btn btn-secondary" onclick="previewEditorContent()">👁️ Preview Changes</button>
                            <button class="btn btn-warning" onclick="resetEditor()">🔄 Reset to Original</button>
                        </div>
                        <textarea id="htmlEditor" class="html-editor-textarea"><?php echo htmlspecialchars($templateData['content']); ?></textarea>
                        <div id="editor-preview" class="editor-preview" style="display: none;">
                            <iframe id="editorPreviewFrame"></iframe>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Test Email Modal -->
    <div id="testEmailModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Send Test Email</h3>
                <span class="modal-close" onclick="closeTestModal()">&times;</span>
            </div>
            <form id="testEmailForm">
                <div class="form-group">
                    <label for="testEmail" class="form-label">Test Email Address</label>
                    <input type="email" id="testEmail" name="testEmail" class="form-control" 
                           placeholder="your.email@example.com" required>
                </div>
                <div class="form-group">
                    <label for="testName" class="form-label">Test Name (Optional)</label>
                    <input type="text" id="testName" name="testName" class="form-control" 
                           placeholder="Your Name">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Send Test Email</button>
                    <button type="button" class="btn btn-secondary" onclick="closeTestModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showPreview(mode) {
            // Update button states
            document.querySelectorAll('.preview-mode').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // Show/hide previews
            document.getElementById('visual-preview').style.display = mode === 'visual' ? 'block' : 'none';
            document.getElementById('code-preview').style.display = mode === 'code' ? 'block' : 'none';
            document.getElementById('html-editor').style.display = mode === 'editor' ? 'block' : 'none';
        }
        
        function sendTestEmail(templateType) {
            document.getElementById('testEmailModal').style.display = 'block';
            document.getElementById('testEmailForm').dataset.template = templateType;
        }
        
        function closeTestModal() {
            document.getElementById('testEmailModal').style.display = 'none';
        }
        
        function downloadTemplate(templateType) {
            const iframe = document.querySelector('#visual-preview iframe');
            const htmlContent = iframe.srcdoc;
            
            const blob = new Blob([htmlContent], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `email_template_${templateType}.html`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
        
        // HTML Editor Functions
        function saveHtmlTemplate() {
            const htmlContent = document.getElementById('htmlEditor').value;
            const templateType = '<?php echo $selectedTemplate; ?>';
            
            // Show loading state
            const saveBtn = event.target;
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = ' Saving...';
            saveBtn.disabled = true;
            
            // Save to server (you can implement this endpoint)
            fetch('save_html_template.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    template_type: templateType,
                    html_content: htmlContent
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(' Template saved successfully!');
                    // Update the visual preview
                    document.querySelector('#visual-preview iframe').srcdoc = htmlContent;
                    // Update the code preview
                    document.querySelector('#code-preview pre code').textContent = htmlContent;
                } else {
                    alert(' Error saving template: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert(' Error saving template: ' + error.message);
            })
            .finally(() => {
                saveBtn.innerHTML = originalText;
                saveBtn.disabled = false;
            });
        }
        
        function previewEditorContent() {
            const htmlContent = document.getElementById('htmlEditor').value;
            const previewFrame = document.getElementById('editorPreviewFrame');
            const previewDiv = document.getElementById('editor-preview');
            
            previewFrame.srcdoc = htmlContent;
            previewDiv.style.display = previewDiv.style.display === 'none' ? 'block' : 'none';
        }
        
        function resetEditor() {
            if (confirm('Are you sure you want to reset the editor to the original template? This will lose any unsaved changes.')) {
                const originalContent = <?php echo json_encode($templateData['content']); ?>;
                document.getElementById('htmlEditor').value = originalContent;
                document.getElementById('editor-preview').style.display = 'none';
            }
        }
        
        // Test email form submission
        document.getElementById('testEmailForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const templateType = this.dataset.template;
            
            fetch('email_template_actions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'send_test',
                    template: templateType,
                    email: formData.get('testEmail'),
                    name: formData.get('testName')
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Test email sent successfully!');
                    closeTestModal();
                } else {
                    alert('Failed to send test email: ' + data.error);
                }
            })
            .catch(error => {
                alert('Error: ' + error);
            });
        });
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('testEmailModal');
            if (event.target === modal) {
                closeTestModal();
            }
        }
    </script>
</body>
</html>
