<?php
$page_title = "Email Templates";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Handle template creation/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = trim($_POST['name']);
    $subject = trim($_POST['subject']);
    $content = trim($_POST['content']);
    $variables = trim($_POST['variables'] ?? '');
    $status = $_POST['status'] ?? 'active';
    
    if (empty($name) || empty($subject) || empty($content)) {
        $error = "Name, subject and content are required";
    } else {
        try {
            if ($id) {
                // Update existing template
                $stmt = $db->prepare("
                    UPDATE email_templates 
                    SET name = ?, subject = ?, content = ?, variables = ?, status = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$name, $subject, $content, $variables, $status, $id]);
                $success = "Template updated successfully!";
            } else {
                // Create new template
                $stmt = $db->prepare("
                    INSERT INTO email_templates (name, subject, content, variables, status)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$name, $subject, $content, $variables, $status]);
                $id = $db->lastInsertId();
                $success = "Template created successfully!";
            }
            
            // Log the action
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, action, details)
                VALUES (?, 'email_template_update', ?)
            ");
            
            $log_stmt->execute([
                $_SESSION['admin_id'],
                json_encode(['template_id' => $id, 'name' => $name, 'action' => $id ? 'update' : 'create'])
            ]);
            
        } catch (Exception $e) {
            $error = "Failed to save template: " . $e->getMessage();
        }
    }
}

// Handle template deletion
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    
    try {
        // Check if template exists
        $check_stmt = $db->prepare("SELECT name FROM email_templates WHERE id = ?");
        $check_stmt->execute([$id]);
        $template = $check_stmt->fetch();
        
        if ($template) {
            $delete_stmt = $db->prepare("DELETE FROM email_templates WHERE id = ?");
            $delete_stmt->execute([$id]);
            
            // Log the action
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, action, details)
                VALUES (?, 'email_template_delete', ?)
            ");
            
            $log_stmt->execute([
                $_SESSION['admin_id'],
                json_encode(['template_id' => $id, 'name' => $template['name']])
            ]);
            
            $success = "Template deleted successfully!";
        }
    } catch (Exception $e) {
        $error = "Failed to delete template: " . $e->getMessage();
    }
}

// Handle duplicate action
if (isset($_GET['duplicate'])) {
    $id = intval($_GET['duplicate']);
    
    try {
        $stmt = $db->prepare("
            INSERT INTO email_templates (name, subject, content, variables, status)
            SELECT CONCAT(name, ' (Copy)'), subject, content, variables, 'inactive'
            FROM email_templates 
            WHERE id = ?
        ");
        $stmt->execute([$id]);
        
        $success = "Template duplicated successfully!";
    } catch (Exception $e) {
        $error = "Failed to duplicate template: " . $e->getMessage();
    }
}

// Get all templates
$stmt = $db->query("SELECT * FROM email_templates ORDER BY name");
$templates = $stmt->fetchAll();

// Get template statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_templates,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_templates,
        SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive_templates,
        (SELECT COUNT(*) FROM email_templates WHERE name LIKE '%welcome%') as welcome_templates,
        (SELECT COUNT(*) FROM email_templates WHERE name LIKE '%deposit%') as deposit_templates
    FROM email_templates
";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();

// Default variables
$default_variables = [
    'General' => ['{username}', '{email}', '{site_name}', '{site_url}', '{current_date}'],
    'User' => ['{user_id}', '{full_name}', '{balance}', '{account_status}'],
    'Transaction' => ['{amount}', '{reference}', '{method}', '{transaction_date}'],
    'Investment' => ['{investment_id}', '{plan_name}', '{daily_return}', '{total_amount}', '{profit_amount}'],
    'Referral' => ['{referral_code}', '{referral_count}', '{referral_bonus}']
];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Email Templates</h1>
        <p class="text-gray-600">Manage email templates for automated communications</p>
    </div>

    <!-- Messages -->
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $success; ?>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Templates</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total_templates']); ?></h3>
                </div>
                <i class="fas fa-envelope text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Templates</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['active_templates']); ?></h3>
                </div>
                <i class="fas fa-check-circle text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Inactive Templates</p>
                    <h3 class="text-2xl font-bold text-gray-600"><?php echo number_format($stats['inactive_templates']); ?></h3>
                </div>
                <i class="fas fa-ban text-gray-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Deposit Templates</p>
                    <h3 class="text-2xl font-bold text-blue-600"><?php echo number_format($stats['deposit_templates']); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Template List -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b flex justify-between items-center">
                    <h3 class="text-lg font-bold">Email Templates</h3>
                    <button onclick="showNewTemplateForm()" 
                            class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-plus mr-2"></i>New Template
                    </button>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="p-4 text-left">Template Name</th>
                                <th class="p-4 text-left">Subject</th>
                                <th class="p-4 text-left">Status</th>
                                <th class="p-4 text-left">Variables</th>
                                <th class="p-4 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <?php foreach ($templates as $template): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="p-4">
                                    <p class="font-medium"><?php echo htmlspecialchars($template['name']); ?></p>
                                    <p class="text-sm text-gray-500">ID: <?php echo $template['id']; ?></p>
                                </td>
                                <td class="p-4">
                                    <p class="text-sm"><?php echo htmlspecialchars($template['subject']); ?></p>
                                </td>
                                <td class="p-4">
                                    <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                        <?php echo $template['status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                        <?php echo ucfirst($template['status']); ?>
                                    </span>
                                </td>
                                <td class="p-4">
                                    <p class="text-xs text-gray-600">
                                        <?php 
                                        $var_count = !empty($template['variables']) ? count(json_decode($template['variables'], true)) : 0;
                                        echo $var_count . ' variable' . ($var_count != 1 ? 's' : '');
                                        ?>
                                    </p>
                                </td>
                                <td class="p-4">
                                    <div class="flex space-x-2">
                                        <button onclick="editTemplate(<?php echo $template['id']; ?>)" 
                                                class="text-blue-600 hover:text-blue-800">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button onclick="previewTemplate(<?php echo $template['id']; ?>)" 
                                                class="text-green-600 hover:text-green-800">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <a href="?duplicate=<?php echo $template['id']; ?>" 
                                           class="text-purple-600 hover:text-purple-800">
                                            <i class="fas fa-copy"></i>
                                        </a>
                                        <button onclick="deleteTemplate(<?php echo $template['id']; ?>, '<?php echo htmlspecialchars($template['name']); ?>')" 
                                                class="text-red-600 hover:text-red-800">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if (empty($templates)): ?>
                <div class="p-8 text-center text-gray-500">
                    <i class="fas fa-envelope-open-text text-4xl mb-4 text-gray-300"></i>
                    <p class="text-lg">No email templates found</p>
                    <p class="text-sm mt-2">Create your first template to get started</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Template Editor -->
        <div id="templateEditor" class="<?php echo isset($_GET['edit']) ? '' : 'hidden'; ?>">
            <div class="bg-white rounded-xl shadow p-6">
                <h3 id="editorTitle" class="text-lg font-bold mb-4">New Email Template</h3>
                <form method="POST" action="" class="space-y-6">
                    <input type="hidden" id="templateId" name="id">
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Template Name *</label>
                        <input type="text" id="templateName" name="name" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                               placeholder="e.g., Welcome Email">
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Email Subject *</label>
                        <input type="text" id="templateSubject" name="subject" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                               placeholder="e.g., Welcome to {site_name}!">
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Template Content *</label>
                        <div class="border rounded-lg overflow-hidden">
                            <div class="bg-gray-50 px-4 py-2 border-b flex justify-between">
                                <div class="flex space-x-2">
                                    <button type="button" onclick="insertVariable('username')" class="text-sm bg-gray-200 px-2 py-1 rounded hover:bg-gray-300">
                                        Username
                                    </button>
                                    <button type="button" onclick="insertVariable('email')" class="text-sm bg-gray-200 px-2 py-1 rounded hover:bg-gray-300">
                                        Email
                                    </button>
                                    <button type="button" onclick="insertVariable('site_name')" class="text-sm bg-gray-200 px-2 py-1 rounded hover:bg-gray-300">
                                        Site Name
                                    </button>
                                </div>
                                <button type="button" onclick="showVariables()" class="text-sm text-blue-600 hover:text-blue-800">
                                    More Variables
                                </button>
                            </div>
                            <textarea id="templateContent" name="content" rows="12" required
                                      class="w-full px-4 py-2 border-0 focus:ring-0"
                                      placeholder="Enter email content here..."></textarea>
                        </div>
                        <p class="text-sm text-gray-500 mt-1">Use variables like {username}, {email}, {site_name} for dynamic content</p>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Available Variables (JSON)</label>
                        <textarea id="templateVariables" name="variables" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                  placeholder='["username", "email", "site_name"]'></textarea>
                        <p class="text-sm text-gray-500 mt-1">List variables as JSON array for reference</p>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Status</label>
                        <select id="templateStatus" name="status" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    
                    <div class="border-t pt-6">
                        <div class="flex justify-between">
                            <button type="button" onclick="cancelEdit()" 
                                    class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                                Cancel
                            </button>
                            <button type="submit" 
                                    class="px-6 py-2 bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold rounded-lg hover:opacity-90">
                                <i class="fas fa-save mr-2"></i>Save Template
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            
            <!-- Available Variables -->
            <div class="mt-6 bg-gray-50 rounded-xl p-6">
                <h4 class="font-bold mb-3">Available Variables</h4>
                <div class="space-y-3">
                    <?php foreach ($default_variables as $category => $vars): ?>
                    <div>
                        <p class="text-sm font-semibold text-gray-700 mb-1"><?php echo $category; ?></p>
                        <div class="flex flex-wrap gap-1">
                            <?php foreach ($vars as $var): ?>
                            <button type="button" onclick="insertVariable('<?php echo trim($var, '{}'); ?>')"
                                    class="text-xs bg-white border px-2 py-1 rounded hover:bg-gray-100">
                                <?php echo $var; ?>
                            </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Quick Templates -->
        <div id="quickTemplates" class="<?php echo !isset($_GET['edit']) ? '' : 'hidden'; ?>">
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Quick Templates</h3>
                <div class="space-y-4">
                    <button onclick="loadTemplate('welcome')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-user-plus text-purple-600 text-xl mb-2"></i>
                        <p class="font-semibold">Welcome Email</p>
                        <p class="text-sm text-gray-600">For new user registrations</p>
                    </button>
                    
                    <button onclick="loadTemplate('deposit')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-money-bill-wave text-green-600 text-xl mb-2"></i>
                        <p class="font-semibold">Deposit Confirmation</p>
                        <p class="text-sm text-gray-600">When user makes deposit</p>
                    </button>
                    
                    <button onclick="loadTemplate('withdrawal')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-hand-holding-usd text-blue-600 text-xl mb-2"></i>
                        <p class="font-semibold">Withdrawal Notification</p>
                        <p class="text-sm text-gray-600">Withdrawal request updates</p>
                    </button>
                    
                    <button onclick="loadTemplate('investment')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-chart-line text-yellow-600 text-xl mb-2"></i>
                        <p class="font-semibold">Investment Started</p>
                        <p class="text-sm text-gray-600">When investment begins</p>
                    </button>
                    
                    <button onclick="loadTemplate('profit')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-coins text-red-600 text-xl mb-2"></i>
                        <p class="font-semibold">Daily Profit Added</p>
                        <p class="text-sm text-gray-600">Daily profit notification</p>
                    </button>
                    
                    <button onclick="loadTemplate('password_reset')" class="w-full bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                        <i class="fas fa-key text-purple-600 text-xl mb-2"></i>
                        <p class="font-semibold">Password Reset</p>
                        <p class="text-sm text-gray-600">Password reset instructions</p>
                    </button>
                </div>
            </div>
            
            <!-- Template Statistics -->
            <div class="mt-6 bg-white rounded-xl shadow p-6">
                <h4 class="font-bold mb-3">Template Usage</h4>
                <div class="space-y-3">
                    <div>
                        <p class="text-sm text-gray-600">Most Used Template</p>
                        <p class="font-semibold">Welcome Email</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Last Modified</p>
                        <p class="font-semibold">
                            <?php 
                            $last_stmt = $db->query("SELECT name, updated_at FROM email_templates ORDER BY updated_at DESC LIMIT 1");
                            $last = $last_stmt->fetch();
                            echo $last ? htmlspecialchars($last['name']) . ' (' . date('M d', strtotime($last['updated_at'])) . ')' : 'None';
                            ?>
                        </p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Preview Emails</p>
                        <button onclick="sendTestEmail()" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 text-sm">
                            Send Test Email
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div id="previewModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-4xl">
            <div class="p-6 border-b">
                <h3 id="previewTitle" class="text-xl font-bold"></h3>
            </div>
            <div class="p-6 max-h-[70vh] overflow-y-auto">
                <div class="mb-4">
                    <p class="text-sm text-gray-600">Subject:</p>
                    <p id="previewSubject" class="font-semibold"></p>
                </div>
                <div class="border rounded-lg p-4 bg-gray-50">
                    <div id="previewContent"></div>
                </div>
            </div>
            <div class="p-6 border-t flex justify-between">
                <button onclick="closePreview()" 
                        class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700">
                    Close
                </button>
                <button onclick="editCurrentTemplate()" 
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-edit mr-2"></i>Edit
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Variables Modal -->
<div id="variablesModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl">
            <div class="p-6 border-b">
                <h3 class="text-xl font-bold">Available Variables</h3>
            </div>
            <div class="p-6 max-h-[60vh] overflow-y-auto">
                <div class="space-y-4">
                    <?php foreach ($default_variables as $category => $vars): ?>
                    <div>
                        <h4 class="font-semibold text-gray-700 mb-2"><?php echo $category; ?></h4>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                            <?php foreach ($vars as $var): ?>
                            <button type="button" onclick="insertVariableAndClose('<?php echo trim($var, '{}'); ?>')"
                                    class="text-sm bg-gray-100 hover:bg-gray-200 px-3 py-2 rounded text-left">
                                <code class="text-blue-600"><?php echo $var; ?></code>
                                <p class="text-xs text-gray-500 mt-1"><?php echo str_replace(['{', '}', '_'], ['', '', ' '], $var); ?></p>
                            </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="p-6 border-t">
                <button onclick="closeVariablesModal()" 
                        class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentTemplateId = 0;

// Show new template form
function showNewTemplateForm() {
    document.getElementById('editorTitle').textContent = 'New Email Template';
    document.getElementById('templateId').value = '';
    document.getElementById('templateName').value = '';
    document.getElementById('templateSubject').value = '';
    document.getElementById('templateContent').value = '';
    document.getElementById('templateVariables').value = '';
    document.getElementById('templateStatus').value = 'active';
    
    document.getElementById('templateEditor').classList.remove('hidden');
    document.getElementById('quickTemplates').classList.add('hidden');
    
    // Scroll to editor
    document.getElementById('templateEditor').scrollIntoView({ behavior: 'smooth' });
}

// Edit template
function editTemplate(id) {
    $.ajax({
        url: '../api/get-template.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            const template = JSON.parse(response);
            currentTemplateId = id;
            
            document.getElementById('editorTitle').textContent = 'Edit Template: ' + template.name;
            document.getElementById('templateId').value = template.id;
            document.getElementById('templateName').value = template.name;
            document.getElementById('templateSubject').value = template.subject;
            document.getElementById('templateContent').value = template.content;
            document.getElementById('templateVariables').value = template.variables || '';
            document.getElementById('templateStatus').value = template.status;
            
            document.getElementById('templateEditor').classList.remove('hidden');
            document.getElementById('quickTemplates').classList.add('hidden');
            
            // Scroll to editor
            document.getElementById('templateEditor').scrollIntoView({ behavior: 'smooth' });
        }
    });
}

// Cancel edit
function cancelEdit() {
    document.getElementById('templateEditor').classList.add('hidden');
    document.getElementById('quickTemplates').classList.remove('hidden');
}

// Preview template
function previewTemplate(id) {
    $.ajax({
        url: '../api/get-template.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            const template = JSON.parse(response);
            currentTemplateId = id;
            
            document.getElementById('previewTitle').textContent = 'Preview: ' + template.name;
            document.getElementById('previewSubject').textContent = template.subject;
            document.getElementById('previewContent').innerHTML = template.content.replace(/\n/g, '<br>');
            
            document.getElementById('previewModal').classList.remove('hidden');
        }
    });
}

function closePreview() {
    document.getElementById('previewModal').classList.add('hidden');
}

function editCurrentTemplate() {
    closePreview();
    editTemplate(currentTemplateId);
}

// Insert variable into content
function insertVariable(variable) {
    const textarea = document.getElementById('templateContent');
    const cursorPos = textarea.selectionStart;
    const textBefore = textarea.value.substring(0, cursorPos);
    const textAfter = textarea.value.substring(cursorPos);
    
    textarea.value = textBefore + '{' + variable + '}' + textAfter;
    textarea.focus();
    textarea.selectionStart = cursorPos + variable.length + 2;
    textarea.selectionEnd = cursorPos + variable.length + 2;
}

function insertVariableAndClose(variable) {
    insertVariable(variable);
    closeVariablesModal();
}

// Show variables modal
function showVariables() {
    document.getElementById('variablesModal').classList.remove('hidden');
}

function closeVariablesModal() {
    document.getElementById('variablesModal').classList.add('hidden');
}

// Load quick template
function loadTemplate(type) {
    const templates = {
        welcome: {
            name: 'Welcome Email',
            subject: 'Welcome to {site_name}!',
            content: `Dear {username},

Welcome to {site_name}! Your account has been successfully created.

Account Details:
• Username: {username}
• Email: {email}
• Account Status: Active

Get started by making your first deposit and exploring our investment plans.

If you have any questions, please contact our support team.

Best regards,
The {site_name} Team`,
            variables: '["username", "email", "site_name", "site_url"]'
        },
        deposit: {
            name: 'Deposit Confirmation',
            subject: 'Deposit Received - {amount}',
            content: `Dear {username},

Your deposit of {amount} has been successfully received.

Transaction Details:
• Amount: {amount}
• Method: {method}
• Reference: {reference}
• Date: {date}
• New Balance: {balance}

Thank you for choosing {site_name}.

Best regards,
The {site_name} Team`,
            variables: '["username", "amount", "method", "reference", "date", "balance", "site_name"]'
        },
        withdrawal: {
            name: 'Withdrawal Notification',
            subject: 'Withdrawal Request - {amount}',
            content: `Dear {username},

Your withdrawal request has been {status}.

Transaction Details:
• Amount: {amount}
• Method: {method}
• Reference: {reference}
• Status: {status}
• Processed Date: {date}

{status == "approved" ? "The funds have been sent to your account." : "Please contact support for more information."}

Best regards,
The {site_name} Team`,
            variables: '["username", "amount", "method", "reference", "status", "date", "site_name"]'
        },
        investment: {
            name: 'Investment Started',
            subject: 'Investment Started - {plan_name}',
            content: `Dear {username},

Your investment in {plan_name} has been successfully started.

Investment Details:
• Plan: {plan_name}
• Amount: {amount}
• Daily Return: {daily_return}%
• Duration: {duration} days
• Expected Profit: {expected_profit}
• Start Date: {start_date}
• End Date: {end_date}

You will receive daily profits directly to your account.

Best regards,
The {site_name} Team`,
            variables: '["username", "plan_name", "amount", "daily_return", "duration", "expected_profit", "start_date", "end_date", "site_name"]'
        },
        profit: {
            name: 'Daily Profit Added',
            subject: 'Daily Profit Added - {amount}',
            content: `Dear {username},

Your daily profit has been added to your account.

Profit Details:
• Amount: {amount}
• Investment: {investment_name}
• Date: {date}
• Total Profit So Far: {total_profit}
• New Balance: {balance}

Keep investing to grow your wealth!

Best regards,
The {site_name} Team`,
            variables: '["username", "amount", "investment_name", "date", "total_profit", "balance", "site_name"]'
        },
        password_reset: {
            name: 'Password Reset',
            subject: 'Password Reset Request',
            content: `Dear {username},

You have requested to reset your password.

Click the link below to reset your password:
{reset_link}

This link will expire in 24 hours.

If you did not request this, please ignore this email or contact support.

Best regards,
The {site_name} Team`,
            variables: '["username", "reset_link", "site_name"]'
        }
    };
    
    const template = templates[type];
    if (template) {
        showNewTemplateForm();
        document.getElementById('templateName').value = template.name;
        document.getElementById('templateSubject').value = template.subject;
        document.getElementById('templateContent').value = template.content;
        document.getElementById('templateVariables').value = template.variables;
    }
}

// Delete template
function deleteTemplate(id, name) {
    if (confirm(`Delete template: ${name}?`)) {
        window.location.href = `?delete=${id}`;
    }
}

// Send test email
function sendTestEmail() {
    const email = prompt('Enter email address to send test to:');
    if (email && confirm(`Send test email to ${email}?`)) {
        $.ajax({
            url: '../api/send-test-email.php',
            method: 'POST',
            data: { email: email },
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
            }
        });
    }
}

// Auto-save draft
let saveTimer;
document.getElementById('templateContent').addEventListener('input', function() {
    clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
        const draft = {
            name: document.getElementById('templateName').value,
            subject: document.getElementById('templateSubject').value,
            content: this.value,
            variables: document.getElementById('templateVariables').value
        };
        localStorage.setItem('email_template_draft', JSON.stringify(draft));
    }, 2000);
});

// Load draft
window.addEventListener('load', function() {
    const draft = JSON.parse(localStorage.getItem('email_template_draft'));
    if (draft && confirm('Load saved draft?')) {
        document.getElementById('templateName').value = draft.name || '';
        document.getElementById('templateSubject').value = draft.subject || '';
        document.getElementById('templateContent').value = draft.content || '';
        document.getElementById('templateVariables').value = draft.variables || '';
    }
});
</script>

<?php require_once 'footer.php'; ?>