<?php
session_start();
require_once '../config/database.php';
require_once '../includes/email_service.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

emailEnsureDefaults($pdo);
$events = emailGetEventDefinitions();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_smtp') {
        $settings = [
            'email_smtp_host' => trim($_POST['email_smtp_host'] ?? ''),
            'email_smtp_port' => trim($_POST['email_smtp_port'] ?? '465'),
            'email_smtp_secure' => trim($_POST['email_smtp_secure'] ?? 'ssl'),
            'email_smtp_username' => trim($_POST['email_smtp_username'] ?? ''),
            'email_smtp_password' => trim($_POST['email_smtp_password'] ?? ''),
            'email_from_email' => trim($_POST['email_from_email'] ?? ''),
            'email_from_name' => trim($_POST['email_from_name'] ?? 'MemberX'),
            'email_smtp_enabled' => isset($_POST['email_smtp_enabled']) ? '1' : '0'
        ];

        foreach ($settings as $key => $value) {
            $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, ?, 'Email setting') ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            $stmt->execute([$key, $value]);
        }
        $success = 'تنظیمات SMTP با موفقیت ذخیره شد.';
    }

    if ($action === 'save_template') {
        $eventKey = $_POST['event_key'] ?? '';
        if (isset($events[$eventKey])) {
            $enabled = isset($_POST['enabled']) ? '1' : '0';
            $subject = trim($_POST['subject'] ?? '');
            $body = trim($_POST['body'] ?? '');

            $pairs = [
                "email_{$eventKey}_enabled" => $enabled,
                "email_{$eventKey}_subject" => $subject,
                "email_{$eventKey}_body" => $body
            ];

            foreach ($pairs as $key => $value) {
                $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, ?, 'Email template setting') ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
                $stmt->execute([$key, $value]);
            }
            $success = 'قالب ایمیل ذخیره شد.';
        } else {
            $error = 'رویداد ایمیل نامعتبر است.';
        }
    }

    if ($action === 'send_test') {
        $eventKey = $_POST['event_key'] ?? '';
        $testEmail = trim($_POST['test_email'] ?? '');
        if (!isset($events[$eventKey])) {
            $error = 'رویداد ایمیل نامعتبر است.';
        } elseif (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
            $error = 'ایمیل تست معتبر نیست.';
        } else {
            $ok = sendSystemEmail(
                $pdo,
                $eventKey,
                $testEmail,
                [
                    'full_name' => 'کاربر تست',
                    'username' => 'test_user',
                    'order_id' => 'TST-' . date('His'),
                    'product_name' => 'محصول تست',
                    'quantity' => '1',
                    'total_coins' => '120',
                    'item_name' => 'خرید تستی',
                    'amount_text' => '120 سکه'
                ],
                [
                    'force' => true,
                    'triggered_by' => 'admin_test',
                    'context' => ['source' => 'admin/email_settings.php', 'admin_id' => $_SESSION['admin_id']]
                ]
            );
            $success = $ok ? 'ایمیل تست با موفقیت ارسال شد.' : 'ارسال تست انجام نشد. لاگ ایمیل را بررسی کنید.';
        }
    }
}

$keys = [
    'email_smtp_host', 'email_smtp_port', 'email_smtp_secure', 'email_smtp_username', 'email_smtp_password',
    'email_from_email', 'email_from_name', 'email_smtp_enabled'
];
foreach (array_keys($events) as $eventKey) {
    $keys[] = "email_{$eventKey}_enabled";
    $keys[] = "email_{$eventKey}_subject";
    $keys[] = "email_{$eventKey}_body";
}
$settings = emailGetSettings($pdo, $keys);
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تنظیمات ایمیل - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <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=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
    <link href="assets/css/admin.css" rel="stylesheet">
    <style>
        .email-editor-shell {
            border: 1px solid #dee2e6;
            border-radius: 12px;
            overflow: hidden;
            background: #fff;
        }
        .email-editor-toolbar {
            display: flex;
            gap: 8px;
            padding: 10px 12px;
            border-bottom: 1px solid #e9ecef;
            background: #f8f9fa;
        }
        .email-editor-layout {
            display: grid;
            grid-template-columns: 1fr 1fr;
            min-height: 420px;
        }
        .email-editor-layout.preview-only {
            grid-template-columns: 1fr;
        }
        .email-editor-layout.code-only {
            grid-template-columns: 1fr;
        }
        .email-code-pane {
            border-left: 1px solid #e9ecef;
        }
        .email-editor-layout.code-only .email-code-pane {
            border-left: 0;
        }
        .email-editor-layout.preview-only .email-code-pane {
            display: none;
        }
        .email-editor-layout.code-only .email-preview-pane {
            display: none;
        }
        .CodeMirror {
            height: 420px;
            font-size: 13px;
        }
        .email-preview-pane {
            background: #f6f8fb;
        }
        .email-preview-frame {
            width: 100%;
            height: 420px;
            border: 0;
            background: #fff;
        }
        .placeholders-note {
            font-size: 12px;
            color: #6c757d;
            margin-top: 8px;
        }
    </style>
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
            <?php
            $admin_page_title = 'تنظیمات ایمیل';
            $admin_page_icon = 'fas fa-envelope';
            $admin_page_actions = '<a href="email_logs.php" class="btn btn-outline-primary btn-sm"><i class="fas fa-list ms-1"></i>لاگ ارسال ایمیل</a>';
            include 'includes/topbar.php';
            ?>

                <?php if (isset($success)): ?>
                    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                <?php endif; ?>
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>

                <div class="card mb-4">
                    <div class="card-header"><strong>تنظیمات SMTP</strong></div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="action" value="save_smtp">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">SMTP Host</label>
                                    <input type="text" class="form-control" name="email_smtp_host" value="<?= htmlspecialchars($settings['email_smtp_host'] ?? 'mail.memberx.app') ?>" required>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">SMTP Port</label>
                                    <input type="number" class="form-control" name="email_smtp_port" value="<?= htmlspecialchars($settings['email_smtp_port'] ?? '465') ?>" required>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Security</label>
                                    <select class="form-select" name="email_smtp_secure">
                                        <option value="ssl" <?= ($settings['email_smtp_secure'] ?? 'ssl') === 'ssl' ? 'selected' : '' ?>>SSL</option>
                                        <option value="tls" <?= ($settings['email_smtp_secure'] ?? '') === 'tls' ? 'selected' : '' ?>>TLS</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-control" name="email_smtp_username" value="<?= htmlspecialchars($settings['email_smtp_username'] ?? 'no-reply@memberx.app') ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Password</label>
                                    <input type="text" class="form-control" name="email_smtp_password" value="<?= htmlspecialchars($settings['email_smtp_password'] ?? '') ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">From Email</label>
                                    <input type="email" class="form-control" name="email_from_email" value="<?= htmlspecialchars($settings['email_from_email'] ?? 'no-reply@memberx.app') ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">From Name</label>
                                    <input type="text" class="form-control" name="email_from_name" value="<?= htmlspecialchars($settings['email_from_name'] ?? 'MemberX') ?>" required>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="email_smtp_enabled" name="email_smtp_enabled" <?= ($settings['email_smtp_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="email_smtp_enabled">فعال بودن ارسال ایمیل سیستم</label>
                                    </div>
                                </div>
                                <div class="col-12 text-end">
                                    <button class="btn btn-primary"><i class="fas fa-save me-1"></i>ذخیره SMTP</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php foreach ($events as $eventKey => $def): ?>
                    <div class="card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <strong><?= htmlspecialchars($def['title']) ?></strong>
                            <span class="badge <?= ($settings["email_{$eventKey}_enabled"] ?? '0') === '1' ? 'bg-success' : 'bg-secondary' ?>">
                                <?= ($settings["email_{$eventKey}_enabled"] ?? '0') === '1' ? 'فعال' : 'غیرفعال' ?>
                            </span>
                        </div>
                        <div class="card-body">
                            <form method="POST" class="mb-3">
                                <input type="hidden" name="action" value="save_template">
                                <input type="hidden" name="event_key" value="<?= htmlspecialchars($eventKey) ?>">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="<?= $eventKey ?>_enabled" name="enabled" <?= ($settings["email_{$eventKey}_enabled"] ?? '0') === '1' ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="<?= $eventKey ?>_enabled">ارسال خودکار این ایمیل فعال باشد</label>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Subject</label>
                                    <input type="text" class="form-control" name="subject" value="<?= htmlspecialchars($settings["email_{$eventKey}_subject"] ?? $def['subject']) ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">متن HTML</label>
                                    <div class="email-editor-shell" data-editor-shell>
                                        <div class="email-editor-toolbar">
                                            <button type="button" class="btn btn-sm btn-outline-primary" data-view-mode="split">Split</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" data-view-mode="code">Code</button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" data-view-mode="preview">Preview</button>
                                        </div>
                                        <div class="email-editor-layout" data-layout>
                                            <div class="email-preview-pane">
                                                <iframe class="email-preview-frame" data-preview-frame title="Email Preview"></iframe>
                                            </div>
                                            <div class="email-code-pane">
                                                <textarea
                                                    class="form-control html-template-editor"
                                                    name="body"
                                                    rows="8"
                                                    data-editor="html"
                                                    required
                                                ><?= htmlspecialchars($settings["email_{$eventKey}_body"] ?? $def['body']) ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="placeholders-note">
                                        Placeholders: {{app_name}}, {{full_name}}, {{username}}, {{order_id}}, {{product_name}}, {{quantity}}, {{total_coins}}, {{item_name}}, {{amount_text}}, {{date}}
                                    </div>
                                </div>
                                <div class="text-end">
                                    <button class="btn btn-success"><i class="fas fa-save me-1"></i>ذخیره قالب</button>
                                </div>
                            </form>

                            <form method="POST" class="border-top pt-3">
                                <input type="hidden" name="action" value="send_test">
                                <input type="hidden" name="event_key" value="<?= htmlspecialchars($eventKey) ?>">
                                <div class="row g-2 align-items-end">
                                    <div class="col-md-8">
                                        <label class="form-label">ارسال تست به ایمیل</label>
                                        <input type="email" class="form-control" name="test_email" placeholder="example@email.com" required>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <button class="btn btn-outline-primary w-100"><i class="fas fa-paper-plane me-1"></i>ارسال تست</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
        </div>
    </main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/admin_shell_scripts.php'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/css/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/htmlmixed/htmlmixed.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const editorBlocks = document.querySelectorAll('[data-editor-shell]');

    editorBlocks.forEach((shell) => {
        const textarea = shell.querySelector('textarea[data-editor="html"]');
        const frame = shell.querySelector('[data-preview-frame]');
        const layout = shell.querySelector('[data-layout]');
        const modeButtons = shell.querySelectorAll('[data-view-mode]');

        const cm = CodeMirror.fromTextArea(textarea, {
            mode: 'htmlmixed',
            theme: 'material-darker',
            lineNumbers: true,
            lineWrapping: true,
            tabSize: 2
        });

        const renderPreview = () => {
            const html = cm.getValue();
            const doc = frame.contentDocument || frame.contentWindow.document;
            doc.open();
            doc.write(html);
            doc.close();
        };

        cm.on('change', renderPreview);
        renderPreview();

        modeButtons.forEach((btn) => {
            btn.addEventListener('click', function () {
                const mode = btn.getAttribute('data-view-mode');
                modeButtons.forEach((b) => {
                    b.classList.remove('btn-primary');
                    b.classList.remove('btn-secondary');
                    b.classList.add('btn-outline-secondary');
                });
                btn.classList.remove('btn-outline-secondary');
                btn.classList.add('btn-primary');

                layout.classList.remove('code-only', 'preview-only');
                if (mode === 'code') {
                    layout.classList.add('code-only');
                } else if (mode === 'preview') {
                    layout.classList.add('preview-only');
                }
                setTimeout(() => cm.refresh(), 20);
            });
        });

        const splitBtn = shell.querySelector('[data-view-mode="split"]');
        if (splitBtn) {
            splitBtn.classList.remove('btn-outline-secondary');
            splitBtn.classList.add('btn-primary');
        }

        const form = shell.closest('form');
        if (form) {
            form.addEventListener('submit', function () {
                textarea.value = cm.getValue();
            });
        }
    });
});
</script>
</body>
</html>
