<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/mailer.php';
auth_require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($do === 'toggle' && $id) {
        db_exec('UPDATE email_templates SET enabled = 1 - enabled WHERE id=:id', ['id'=>$id]);
        header('Location: email-templates.php'); exit;
    }
    if ($do === 'delete' && $id) {
        // Don't allow deleting system templates
        $row = db_row('SELECT is_system FROM email_templates WHERE id=:id', ['id'=>$id]);
        if ($row && (int)$row['is_system'] !== 1) {
            db_exec('DELETE FROM email_templates WHERE id=:id', ['id'=>$id]);
            header('Location: email-templates.php?msg=deleted'); exit;
        }
    }
}

$templates = db_all('SELECT * FROM email_templates ORDER BY is_system DESC, name');

$page_title = 'Email Templates';
require __DIR__ . '/_guard.php';
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.7rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
.tag-sys{background:#dbeafe;color:#1e40af;display:inline-block;padding:.1em .5em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
.tag-on{background:#dcfce7;color:#166534;display:inline-block;padding:.1em .5em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
.tag-off{background:#fee2e2;color:#991b1b;display:inline-block;padding:.1em .5em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
</style>

<?php
$settings_section = 'email';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1>Email Templates</h1>
        <p class="crumb">All transactional emails sent by the system. Click to edit content, subject, or sender.</p>
    </div>
    <div style="display:flex;gap:.5rem;">
        <a href="email-template-edit.php?action=add" class="btn">+ New template</a>
        <a href="email-queue.php" class="btn btn-outline">Queue</a>
        <a href="email-log.php" class="btn btn-outline">Log</a>
    </div>
</div>

<?php if (isset($_GET['msg']) && $_GET['msg']==='deleted'): ?>
    <div class="alert alert-success" data-autohide>Template deleted.</div>
<?php endif; ?>

<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>Template</th>
                <th>Slug</th>
                <th>Subject</th>
                <th>Status</th>
                <th>Updated</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($templates as $t): ?>
            <tr>
                <td>
                    <strong><?= htmlspecialchars($t['name']) ?></strong>
                    <?php if ((int)$t['is_system'] === 1): ?>
                        <span class="tag-sys">system</span>
                    <?php endif; ?>
                    <?php if (!empty($t['description'])): ?>
                        <br><small class="muted"><?= htmlspecialchars($t['description']) ?></small>
                    <?php endif; ?>
                </td>
                <td><code style="font-size:.78rem;"><?= htmlspecialchars($t['slug']) ?></code></td>
                <td style="max-width:320px;"><span style="font-size:.85rem;"><?= htmlspecialchars($t['subject']) ?></span></td>
                <td>
                    <?php if ((int)$t['enabled'] === 1): ?>
                        <span class="tag-on">On</span>
                    <?php else: ?>
                        <span class="tag-off">Off</span>
                    <?php endif; ?>
                </td>
                <td class="muted" style="font-size:.78rem;white-space:nowrap;"><?= date('j M Y', strtotime($t['updated_at'])) ?></td>
                <td style="text-align:right;white-space:nowrap;">
                    <a href="email-template-edit.php?id=<?= $t['id'] ?>">Edit</a>
                    &nbsp;
                    <form method="post" style="display:inline;">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="toggle">
                        <input type="hidden" name="id" value="<?= $t['id'] ?>">
                        <button type="submit" style="background:none;border:none;color:var(--brand-primary);cursor:pointer;font-size:.85rem;font-family:inherit;">
                            <?= (int)$t['enabled'] === 1 ? 'Disable' : 'Enable' ?>
                        </button>
                    </form>
                    <?php if ((int)$t['is_system'] !== 1): ?>
                        &nbsp;
                        <form method="post" style="display:inline;" onsubmit="return confirm('Delete this template? Any pending queued emails using it will fail.');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="do" value="delete">
                            <input type="hidden" name="id" value="<?= $t['id'] ?>">
                            <button type="submit" style="background:none;border:none;color:#b91c1c;cursor:pointer;font-size:.85rem;font-family:inherit;">Delete</button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>