<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_template') {
        $key = $_POST['template_key'] ?? '';
        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');
        
        if ($key && $subject && $body) {
            updateEmailTemplate($key, $subject, $body);
            $message = "Template updated successfully!";
            $messageType = 'success';
        } else {
            $message = "Subject and Body cannot be empty.";
            $messageType = 'error';
        }
    }
}

$templates = getAllEmailTemplates();
$selectedKey = $_GET['key'] ?? (count($templates) > 0 ? $templates[0]['template_key'] : '');

$activeTemplate = null;
foreach ($templates as $t) {
    if ($t['template_key'] === $selectedKey) {
        $activeTemplate = $t;
        break;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Email Templates — Admin Control Panel"; include __DIR__ . '/admin-style.php'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#template_body',
    plugins: 'preview anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
    toolbar: 'undo redo | preview | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
    height: 400,
    branding: false,
    promotion: false
  });
</script>
<style>
.template-selector {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    background: #fff;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    border: 1px solid var(--color-border);
    align-items: center;
}
.template-badge {
    background: #f3f4f6;
    border: 1px solid #d1d5db;
    padding: 2px 6px;
    border-radius: 4px;
    font-family: monospace;
    font-size: 12px;
    color: #4b5563;
}
</style>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">

      <div style="margin-bottom:24px;">
        <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
          <i data-lucide="layout-template" style="color:#0ea5e9;width:24px;height:24px;"></i> Email Templates
        </h1>
        <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Customize the HTML emails sent by the system (Welcome, Password Reset, etc).</p>
      </div>

      <?php if ($message): ?>
        <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>" style="margin-bottom:20px;">
          <?= htmlspecialchars($message) ?>
        </div>
      <?php endif; ?>

      <div class="template-selector">
          <label style="font-weight:600; font-size:14px; color:var(--color-ink);">Select Template to Edit:</label>
          <select class="form-input" style="width: auto; margin-bottom: 0;" onchange="window.location.href='email-templates.php?key='+this.value">
              <?php foreach ($templates as $t): ?>
                  <option value="<?= htmlspecialchars($t['template_key']) ?>" <?= $t['template_key'] === $selectedKey ? 'selected' : '' ?>>
                      <?= htmlspecialchars(ucwords(str_replace('_', ' ', $t['template_key']))) ?>
                  </option>
              <?php endforeach; ?>
          </select>
      </div>

      <?php if ($activeTemplate): ?>
      <div class="dashboard-bottom-grid">

        <!-- Editor Card -->
        <div class="card" style="margin-bottom:0;">
          <form method="POST">
            <input type="hidden" name="action" value="save_template">
            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
            <input type="hidden" name="template_key" value="<?= htmlspecialchars($activeTemplate['template_key']) ?>">
            
            <div class="form-group">
              <label class="form-label">Email Subject</label>
              <input type="text" name="subject" class="form-input" value="<?= htmlspecialchars($activeTemplate['subject']) ?>" required>
            </div>
            
            <div class="form-group">
              <label class="form-label">Email Body (HTML)</label>
              <textarea id="template_body" name="body" style="visibility:hidden; height:400px; width:100%; box-sizing:border-box;"><?= htmlspecialchars($activeTemplate['body']) ?></textarea>
            </div>
            
            <button type="submit" class="btn btn-primary" style="width:100%;margin-top:10px;"><i data-lucide="save" style="width:15px;height:15px;"></i> Save Template</button>
          </form>
        </div>

        <!-- Available Variables Sidebar -->
        <div class="card" style="margin-bottom:0; height: fit-content;">
            <div class="card-title" style="margin-bottom:6px;"><i data-lucide="info" style="width:18px;height:18px;color:#3b82f6;"></i> Available Variables</div>
            <div class="card-sub" style="margin-bottom:15px;">You can use these placeholders in your subject or body. They will be automatically replaced with the user's details.</div>
            
            <div style="display:flex; flex-direction:column; gap:8px;">
                <?php 
                $vars = array_map('trim', explode(',', $activeTemplate['variables']));
                foreach ($vars as $var): 
                    if (empty($var)) continue;
                ?>
                <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #eaeaea; padding-bottom:8px;">
                    <span class="template-badge"><?= htmlspecialchars($var) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div style="margin-top:20px; font-size:12px; color:var(--color-ink-mute); line-height:1.5;">
                <strong>Tip:</strong> You can copy and paste the placeholders directly into the editor.
            </div>
        </div>

      </div>
      <?php else: ?>
        <div class="card">
            <p>No templates available.</p>
        </div>
      <?php endif; ?>

    </div>
  </main>
</div>
<script>if (window.lucide) { lucide.createIcons(); }</script>
</body>
</html>
