<?php
ob_start();
requireAdmin();

// 仅超级管理员可访问
$user = currentUser();
if ($user['role'] !== 'admin') {
    header('Location: /admin.php');
    exit;
}

$message = '';
$error = '';

// 确保邮件模板表存在
$db->query("CREATE TABLE IF NOT EXISTS `email_templates` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `type` VARCHAR(50) NOT NULL UNIQUE,
    `name` VARCHAR(100) NOT NULL,
    `subject` VARCHAR(255) NOT NULL,
    `content` TEXT NOT NULL,
    `variables` TEXT,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// 插入默认模板
$check = $db->fetchOne("SELECT id FROM email_templates LIMIT 1");
if (!$check) {
    $db->query("INSERT INTO `email_templates` (`type`, `name`, `subject`, `content`, `variables`) VALUES
    ('recharge', '充值成功通知', '【{site_name}】充值成功通知', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #10b981, #059669); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">✅ 充值成功</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您的账户已成功充值：</p><div style=\"text-align: center; margin: 30px 0;\"><span style=\"font-size: 36px; font-weight: bold; color: #10b981;\">¥{amount}</span></div><p>订单号：{order_no}</p><p>当前余额：<strong>¥{balance}</strong></p><hr style=\"margin: 30px 0;\"><p style=\"color: #9ca3af; font-size: 12px;\">此邮件由系统自动发送，请勿回复。</p></div></div></body></html>', '{site_name}, {username}, {amount}, {order_no}, {balance}'),
    ('card_recharge', '卡密充值成功通知', '【{site_name}】卡密充值成功通知', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #f59e0b, #ef4444); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">🎫 卡密充值成功</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您已通过卡密成功充值：</p><div style=\"text-align: center; margin: 30px 0;\"><span style=\"font-size: 36px; font-weight: bold; color: #f59e0b;\">¥{amount}</span></div><p>卡密：{card_code}</p><p>当前余额：<strong>¥{balance}</strong></p><hr style=\"margin: 30px 0;\"><p style=\"color: #9ca3af; font-size: 12px;\">此邮件由系统自动发送，请勿回复。</p></div></div></body></html>', '{site_name}, {username}, {amount}, {card_code}, {balance}'),
    ('login_alert', '登录提醒', '【{site_name}】登录提醒', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">🔐 登录提醒</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您的账号刚刚登录：</p><div style=\"margin: 20px 0; padding: 15px; background: #f3f4f6; border-radius: 12px;\"><p>📅 登录时间：{login_time}</p><p>📍 登录位置：{city}</p><p>📱 设备信息：{device}</p><p>🌐 IP地址：{ip}</p></div><p>如果这是您本人操作，请忽略此邮件。</p><p style=\"color: #ef4444;\">⚠️ 如果不是您本人操作，请立即修改密码。</p></div></div></body></html>', '{site_name}, {username}, {login_time}, {city}, {device}, {ip}'),
    ('purchase', '购买成功通知', '【{site_name}】购买成功通知', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">🎉 购买成功</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您已成功购买：<strong>{product_name}</strong></p><p>支付金额：<strong>¥{amount}</strong></p><p>有效期至：{expire_date}</p><hr style=\"margin: 30px 0;\"><p style=\"color: #9ca3af; font-size: 12px;\">此邮件由系统自动发送，请勿回复。</p></div></div></body></html>', '{site_name}, {username}, {product_name}, {amount}, {expire_date}')");
}

// 处理保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $type = $_POST['type'];
    $subject = addslashes($_POST['subject']);
    $content = addslashes($_POST['content']);
    $db->query("UPDATE email_templates SET subject = '$subject', content = '$content' WHERE type = '$type'");
    $message = '模板保存成功';
}

// 获取所有模板
$templates = $db->fetchAll("SELECT * FROM email_templates ORDER BY id");
$current_type = $_GET['template_type'] ?? ($templates[0]['type'] ?? 'recharge');
$current = $db->fetchOne("SELECT * FROM email_templates WHERE type = '$current_type'");
?>

<div class="mail-template-container">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:email-edit.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            邮件模板管理
        </h2>
        <p class="page-desc">自定义邮件通知内容，支持HTML和变量替换</p>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <!-- 模板切换标签 -->
    <div class="template-tabs">
        <?php foreach ($templates as $tpl): ?>
            <a href="?page=mail_template&template_type=<?php echo $tpl['type']; ?>" 
               class="template-tab <?php echo $current_type == $tpl['type'] ? 'active' : ''; ?>">
                <?php echo htmlspecialchars($tpl['name']); ?>
            </a>
        <?php endforeach; ?>
    </div>
    
    <!-- 编辑表单 -->
    <div class="form-card">
        <form method="POST">
            <input type="hidden" name="type" value="<?php echo $current['type']; ?>">
            <input type="hidden" name="save_template" value="1">
            
            <div class="form-group">
                <label>模板名称</label>
                <input type="text" value="<?php echo htmlspecialchars($current['name']); ?>" disabled>
                <small>模板名称不可修改</small>
            </div>
            
            <div class="form-group">
                <label>邮件主题</label>
                <input type="text" name="subject" value="<?php echo htmlspecialchars($current['subject']); ?>" required>
            </div>
            
            <div class="form-group">
                <label>邮件内容 (HTML)</label>
                <textarea name="content" rows="12" id="emailContent"><?php echo htmlspecialchars($current['content']); ?></textarea>
                <small>支持HTML代码，可使用下方变量</small>
            </div>
            
            <div class="form-group">
                <label>可用变量</label>
                <div class="variables-box">
                    <?php 
                    $vars = explode(',', $current['variables']);
                    foreach ($vars as $var):
                        $var = trim($var);
                    ?>
                        <code onclick="insertVariable('{<?php echo $var; ?>}')">{<?php echo $var; ?>}</code>
                    <?php endforeach; ?>
                </div>
                <small>点击变量可插入到内容中</small>
            </div>
            
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" id="previewBtn">
                    <img src="https://api.iconify.design/mdi:eye.svg?color=currentColor" width="16" height="16" style="margin-right: 6px;" alt="">
                    预览邮件
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="16" height="16" style="margin-right: 6px;" alt="">
                    保存模板
                </button>
            </div>
        </form>
    </div>
    
    <!-- 预览弹窗 -->
    <div id="previewModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>邮件预览</h3>
                <button type="button" class="modal-close" onclick="closePreview()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="previewContent"></div>
            </div>
        </div>
    </div>
</div>

<style>
.mail-template-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 4px;
}

.page-header {
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.page-desc {
    color: var(--text-muted);
    font-size: 14px;
    margin-left: 36px;
}

.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: 12px;
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-success {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}

.template-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
}
.template-tab {
    padding: 8px 20px;
    background: var(--bg-secondary);
    border-radius: 20px;
    text-decoration: none;
    color: var(--text-primary);
    font-size: 13px;
    transition: all 0.2s;
}
.template-tab:hover {
    background: var(--border-color);
}
.template-tab.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.form-card {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 32px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}

.form-group {
    margin-bottom: 24px;
}
.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: var(--text-primary);
}
.form-group input,
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group input[disabled] {
    background: var(--bg-secondary);
    cursor: not-allowed;
}
.form-group textarea {
    resize: vertical;
    font-family: monospace;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}

.variables-box {
    background: var(--bg-secondary);
    padding: 14px 16px;
    border-radius: 10px;
}
.variables-box code {
    display: inline-block;
    background: rgba(102, 126, 234, 0.1);
    color: var(--primary-color);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    margin: 4px;
    cursor: pointer;
    transition: all 0.2s;
}
.variables-box code:hover {
    background: var(--primary-color);
    color: white;
}

.form-actions {
    display: flex;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px 24px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-secondary);
    color: var(--text-primary);
    border: 1.5px solid var(--border-color);
}
.btn-secondary:hover {
    background: var(--border-color);
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    max-width: 600px;
    width: 90%;
    max-height: 80vh;
    overflow: auto;
}
.modal-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    margin: 0;
    font-size: 18px;
}
.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
}
.modal-body {
    padding: 24px;
}

@media (max-width: 768px) {
    .form-card {
        padding: 20px;
    }
    .form-actions {
        flex-direction: column;
    }
    .form-actions .btn {
        width: 100%;
    }
}
</style>

<script>
function insertVariable(varText) {
    const textarea = document.getElementById('emailContent');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    const newText = text.substring(0, start) + varText + text.substring(end);
    textarea.value = newText;
    textarea.focus();
    textarea.selectionStart = start + varText.length;
    textarea.selectionEnd = start + varText.length;
}

function closePreview() {
    document.getElementById('previewModal').style.display = 'none';
}

document.getElementById('previewBtn')?.addEventListener('click', function() {
    const subject = document.querySelector('input[name="subject"]').value;
    const content = document.getElementById('emailContent').value;
    const modal = document.getElementById('previewModal');
    const previewContent = document.getElementById('previewContent');
    
    previewContent.innerHTML = `
        <div style="background: #f0f0f0; padding: 10px; border-radius: 8px; margin-bottom: 15px;">
            <strong>主题：</strong> ${escapeHtml(subject)}
        </div>
        <div style="border: 1px solid #ddd; border-radius: 8px; padding: 15px;">
            ${content}
        </div>
        <div style="margin-top: 15px; font-size: 12px; color: #999; text-align: center;">
            ⚠️ 预览仅供参考，实际发送时会替换变量
        </div>
    `;
    
    modal.style.display = 'flex';
});

function escapeHtml(text) {
    return text.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

document.getElementById('previewModal')?.addEventListener('click', function(e) {
    if (e.target === this) closePreview();
});
</script>