<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/mailer.php';
auth_require_admin();

$id     = (int)($_GET['id'] ?? 0);
$action = $_GET['action'] ?? ($id ? 'edit' : '');
$is_add = ($action === 'add');

$template = null;
$errors   = [];
$test_result = null;

if (!$is_add) {
    $template = db_row('SELECT * FROM email_templates WHERE id=:id', ['id'=>$id]);
    if (!$template) { http_response_code(404); echo 'Template not found.'; exit; }
}
if ($is_add) {
    $template = [
        'slug'=>'','name'=>'','description'=>'','subject'=>'',
        'from_name'=>'','from_email'=>'','html_body'=>'','text_body'=>'',
        'enabled'=>1,'merge_vars'=>'','is_system'=>0,
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? 'save';

    if ($do === 'send_test') {
        $to = trim($_POST['test_to'] ?? '');
        if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
            $test_result = ['ok'=>false, 'error'=>'Enter a valid email address.'];
        } else {
            $test_result = email_send_test($template['slug'], $to);
        }
    } else {
        // Save
        $slug        = trim($_POST['slug']        ?? '');
        $name        = trim($_POST['name']        ?? '');
        $description = trim($_POST['description'] ?? '');
        $subject     = trim($_POST['subject']     ?? '');
        $from_name   = trim($_POST['from_name']   ?? '');
        $from_email  = trim($_POST['from_email']  ?? '');
        $html_body   = (string)($_POST['html_body'] ?? '');
        $text_body   = (string)($_POST['text_body'] ?? '');
        $merge_vars  = trim($_POST['merge_vars']  ?? '');
        $enabled     = !empty($_POST['enabled']) ? 1 : 0;

        if (!preg_match('/^[a-z0-9_]+$/', $slug)) $errors[] = 'Slug must be lowercase letters, numbers, and underscores only.';
        if ($name === '')    $errors[] = 'Name is required.';
        if ($subject === '') $errors[] = 'Subject is required.';
        if ($from_email !== '' && !filter_var($from_email, FILTER_VALIDATE_EMAIL)) $errors[] = 'From email must be a valid address (or blank to use default).';

        // Slug uniqueness
        if (!$errors) {
            $exists = db_row(
                'SELECT id FROM email_templates WHERE slug=:s AND id <> :id',
                ['s'=>$slug, 'id'=>$is_add ? 0 : $id]
            );
            if ($exists) $errors[] = 'A template with that slug already exists.';
        }

        // System templates: don't let slug change
        if (!$is_add && (int)$template['is_system'] === 1 && $slug !== $template['slug']) {
            $errors[] = 'System templates can\'t have their slug changed.';
        }

        if (!$errors) {
            $data = [
                'slug'        => $slug,
                'name'        => $name,
                'description' => $description ?: null,
                'subject'     => $subject,
                'from_name'   => $from_name  ?: null,
                'from_email'  => $from_email ?: null,
                'html_body'   => $html_body,
                'text_body'   => $text_body,
                'merge_vars'  => $merge_vars ?: null,
                'enabled'     => $enabled,
            ];
            if ($is_add) {
                $new_id = db_insert('email_templates', $data);
                app_log("Email template created: $slug (id $new_id)");
                header('Location: email-template-edit.php?id='.$new_id.'&msg=created'); exit;
            } else {
                db_update('email_templates', $id, $data);
                app_log("Email template updated: $slug");
                header('Location: email-template-edit.php?id='.$id.'&msg=saved'); exit;
            }
        }
        // Repopulate on error
        $template = array_merge($template, $data ?? []);
    }
}

$page_title = $is_add ? 'New email template' : 'Edit — ' . $template['name'];
require __DIR__ . '/_guard.php';

// Parse merge vars list for the helper
$var_list = [];
if (!empty($template['merge_vars'])) {
    $var_list = array_filter(array_map('trim', explode(',', $template['merge_vars'])));
}
?>

<style>
.b-grid{display:grid;grid-template-columns:1fr 280px;gap:1.25rem;align-items:start;}
@media(max-width:1000px){.b-grid{grid-template-columns:1fr;}}
.b-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;margin-bottom:1rem;}
.b-card h3{margin:0 0 .75rem;font-size:1rem;}
.b-card label{font-weight:600;font-size:.85rem;}
textarea.code-area{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:.85rem;line-height:1.5;}
.var-tag{display:inline-block;background:#f3f4f6;border:1px solid var(--line);padding:.25em .55em;border-radius:4px;font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer;margin:.15em;}
.var-tag:hover{background:#e5e7eb;}
.preview-tabs{display:flex;gap:.5rem;border-bottom:1px solid var(--line);margin-bottom:.75rem;}
.preview-tabs button{background:none;border:none;padding:.5rem 1rem;cursor:pointer;font-size:.85rem;font-weight:600;color:var(--ink-muted);border-bottom:2px solid transparent;font-family:inherit;}
.preview-tabs button.active{color:var(--ink);border-bottom-color:var(--brand-primary);}
.preview-pane{display:none;}
.preview-pane.active{display:block;}
</style>

<section class="section">
<div class="container">

<p class="muted" style="margin:0;"><a href="email-templates.php">← Email templates</a></p>
<h1 style="margin:.25rem 0 1.25rem;"><?= $is_add ? 'New email template' : 'Edit template' ?></h1>

<?php if (isset($_GET['msg']) && $_GET['msg']==='saved'): ?>
    <div class="alert alert-success" data-autohide>Template saved.</div>
<?php elseif (isset($_GET['msg']) && $_GET['msg']==='created'): ?>
    <div class="alert alert-success" data-autohide>Template created.</div>
<?php endif; ?>

<?php if ($test_result): ?>
    <div class="alert <?= $test_result['ok']?'alert-success':'alert-error' ?>">
        <?php if ($test_result['ok']): ?>
            ✓ Test email sent. Check your inbox (and spam folder) within a minute.
        <?php else: ?>
            ✗ Test failed: <?= htmlspecialchars($test_result['error'] ?? 'unknown') ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-error">
        <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
    </div>
<?php endif; ?>

<form method="post">
    <?= csrf_field() ?>
    <input type="hidden" name="do" value="save">

    <div class="b-grid">
        <div>
            <div class="b-card">
                <h3>Identity</h3>

                <label>Template name *</label>
                <input type="text" name="name" required value="<?= htmlspecialchars($template['name']) ?>"
                       placeholder="e.g. Welcome — new member signup">

                <label>Slug *</label>
                <input type="text" name="slug" required <?= !$is_add && (int)$template['is_system']===1 ? 'readonly' : '' ?>
                       pattern="[a-z0-9_]+"
                       value="<?= htmlspecialchars($template['slug']) ?>"
                       placeholder="e.g. member_welcome">
                <p class="muted" style="font-size:.78rem;margin-top:-.5rem;">
                    Code uses this slug to find the template. Lowercase, underscores only.
                    <?php if (!$is_add && (int)$template['is_system']===1): ?>System templates can't change their slug.<?php endif; ?>
                </p>

                <label>Description (internal)</label>
                <textarea name="description" rows="2"><?= htmlspecialchars($template['description'] ?? '') ?></textarea>

                <label style="display:flex;align-items:center;gap:.5rem;font-weight:normal;cursor:pointer;margin-top:.5rem;">
                    <input type="checkbox" name="enabled" value="1" <?= $template['enabled']?'checked':'' ?>>
                    <span>Enabled (sends emails using this template)</span>
                </label>
            </div>

            <div class="b-card">
                <h3>Sender</h3>
                <p class="muted" style="font-size:.85rem;margin-top:0;">Leave both blank to use site-wide defaults from Settings → Email.</p>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem;">
                    <div>
                        <label>From name</label>
                        <input type="text" name="from_name"
                               placeholder="<?= htmlspecialchars(setting_get('email.from_name', '')) ?>"
                               value="<?= htmlspecialchars($template['from_name'] ?? '') ?>">
                    </div>
                    <div>
                        <label>From email</label>
                        <input type="email" name="from_email"
                               placeholder="<?= htmlspecialchars(setting_get('email.from_email', '')) ?>"
                               value="<?= htmlspecialchars($template['from_email'] ?? '') ?>">
                    </div>
                </div>
            </div>

            <div class="b-card">
                <h3>Subject *</h3>
                <input type="text" name="subject" required
                       value="<?= htmlspecialchars($template['subject']) ?>"
                       placeholder="e.g. Welcome to Buy Local Lowveld, {{first_name}}!">
            </div>

            <div class="b-card">
                <h3>HTML body</h3>
                <p class="muted" style="font-size:.85rem;margin-top:0;">
                    Use <code>{{var_name}}</code> placeholders. The system wraps your content in a clean
                    branded frame automatically.
                </p>
                <textarea name="html_body" id="html_body" rows="14" class="code-area"><?= htmlspecialchars($template['html_body'] ?? '') ?></textarea>
            </div>

            <div class="b-card">
                <h3>Plain-text body</h3>
                <p class="muted" style="font-size:.85rem;margin-top:0;">
                    Sent alongside the HTML version for email clients that don't render HTML.
                    If you leave this blank, we'll auto-strip the HTML.
                </p>
                <textarea name="text_body" id="text_body" rows="8" class="code-area"><?= htmlspecialchars($template['text_body'] ?? '') ?></textarea>
            </div>

            <div class="b-card">
                <h3>Available merge variables</h3>
                <p class="muted" style="font-size:.85rem;margin-top:0;">
                    Comma-separated list of variables this template supports.
                    Just for reference — the actual variables passed in depend on the calling code.
                </p>
                <input type="text" name="merge_vars"
                       value="<?= htmlspecialchars($template['merge_vars'] ?? '') ?>"
                       placeholder="e.g. first_name, business_name, tier, amount, site_url">
            </div>

            <button type="submit" class="btn">Save changes</button>
            <a href="email-templates.php" class="btn btn-outline">Cancel</a>
        </div>

        <!-- Sidebar: variables + send test -->
        <aside>
            <div class="b-card" style="position:sticky;top:80px;">
                <h3>Variables</h3>
                <p class="muted" style="font-size:.78rem;margin-top:0;">Click to copy into the body.</p>
                <?php if ($var_list): ?>
                    <div>
                    <?php foreach ($var_list as $v): ?>
                        <span class="var-tag" onclick="insertVar('{{<?= htmlspecialchars($v) ?>}}')">{{<?= htmlspecialchars($v) ?>}}</span>
                    <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="muted" style="font-size:.85rem;">No variables listed yet. Add some in the merge variables field below.</p>
                <?php endif; ?>
                <p class="muted" style="font-size:.78rem;margin-top:.75rem;">
                    Always available: <span class="var-tag" onclick="insertVar('{{site_url}}')">{{site_url}}</span>
                </p>
            </div>

            <?php if (!$is_add && !empty($template['slug'])): ?>
            <form method="post" class="b-card">
                <?= csrf_field() ?>
                <input type="hidden" name="do" value="send_test">
                <h3>Send test email</h3>
                <p class="muted" style="font-size:.82rem;margin-top:0;">
                    Sends this template right now with sample data. Subject prefixed with [TEST].
                </p>
                <input type="email" name="test_to" required
                       placeholder="you@example.com"
                       value="<?= htmlspecialchars($admin['email']) ?>">
                <button type="submit" class="btn btn-outline" style="margin-top:.5rem;">Send test →</button>
            </form>
            <?php endif; ?>
        </aside>
    </div>
</form>

</div>
</section>

<script>
function insertVar(text) {
    const html = document.getElementById('html_body');
    const txt  = document.getElementById('text_body');
    // Insert into whichever is focused, or html_body by default
    const target = (document.activeElement === txt) ? txt : html;
    const start = target.selectionStart;
    const end   = target.selectionEnd;
    target.value = target.value.substring(0,start) + text + target.value.substring(end);
    target.focus();
    target.selectionStart = target.selectionEnd = start + text.length;
}
</script>

<?php require __DIR__ . '/_footer.php'; ?>