<?php
$adminTitle = 'Email Templates';
require_once __DIR__ . '/includes/header.php';

// ── Save template ──────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $id      = (int)$_POST['id'];
    $subject = sanitize($_POST['subject'] ?? '');
    $body    = $_POST['body'] ?? '';
    // Allow full HTML in template body
    Database::execute("UPDATE email_templates SET subject=?, body=?, updated_at=NOW() WHERE id=?", [$subject, $body, $id]);
    $_SESSION['flash']['success'] = 'Template saved.';
    header('Location: /admin/email-templates.php?edit=' . $id); exit;
}

// ── Send test ──────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_test'])) {
    $id   = (int)$_POST['id'];
    $dest = sanitize($_POST['test_email'] ?? '');
    if ($dest && filter_var($dest, FILTER_VALIDATE_EMAIL)) {
        $tpl = Database::fetchOne("SELECT * FROM email_templates WHERE id=?", [$id]);
        if ($tpl) {
            $demoVars = [
                'customer_name'  => 'Test Customer',
                'company_name'   => setting('company_name','Rig N Dig'),
                'quote_number'   => 'RFQ-00001',
                'estimate_number'=> 'EST-00001',
                'invoice_number' => 'INV-00001',
                'request_number' => 'WS-00001',
                'total'          => 'PKR 125,000.00',
                'subtotal'       => 'PKR 106,838.00',
                'due_date'       => date('d M Y', strtotime('+30 days')),
                'valid_until'    => date('d M Y', strtotime('+15 days')),
                'paid_date'      => date('d M Y'),
                'amount_paid'    => 'PKR 125,000.00',
                'balance_due'    => 'PKR 0.00',
                'equipment'      => 'API 6A Gate Valve 3" 5000PSI',
                'status'         => 'In Progress',
                'message'        => 'Your equipment has been inspected. Parts ordered and repair underway.',
                'email'          => $dest,
                'temp_password'  => 'Temp@1234',
                'portal_url'     => (defined('SITE_URL') ? rtrim(SITE_URL,'/') : '') . '/portal/login.php',
                'reset_link'     => (defined('SITE_URL') ? rtrim(SITE_URL,'/') : '') . '/portal/reset-password.php?token=SAMPLE',
                'subject'        => 'New Arrivals — API Flanges & Valves',
                'content'        => '<p>We are pleased to introduce our latest stock of <strong>API 6A Flanges</strong> and <strong>Cameron Gate Valves</strong> now available for immediate delivery.</p><p>Contact us today for competitive pricing.</p>',
                'site_url'       => defined('SITE_URL') ? SITE_URL : '',
                'year'           => date('Y'),
            ];
            $subject = $tpl['subject'];
            $body    = $tpl['body'];
            foreach ($demoVars as $k => $v) {
                $subject = str_replace('{{' . $k . '}}', $v, $subject);
                $body    = str_replace('{{' . $k . '}}', $v, $body);
            }
            $wrapped = emailHtmlWrapper($body);
            sendEmail($dest, '[TEST] ' . $subject, $wrapped);
            $_SESSION['flash']['success'] = "Test email sent to {$dest}";
        }
    } else {
        $_SESSION['flash']['error'] = 'Invalid email address.';
    }
    header('Location: /admin/email-templates.php?edit=' . $id); exit;
}

$templates = Database::fetchAll("SELECT * FROM email_templates ORDER BY name");
$editId    = (int)($_GET['edit'] ?? 0);
$current   = $editId ? Database::fetchOne("SELECT * FROM email_templates WHERE id=?", [$editId]) : null;

// Template variable reference
$varDocs = [
    'welcome'           => ['customer_name','company_name','email','temp_password','portal_url'],
    'rfq_received'      => ['customer_name','company_name','quote_number'],
    'estimate_sent'     => ['customer_name','company_name','estimate_number','valid_until','total'],
    'invoice_sent'      => ['customer_name','company_name','invoice_number','total','due_date'],
    'invoice_paid'      => ['customer_name','company_name','invoice_number','amount_paid','paid_date'],
    'payment_reminder'  => ['customer_name','company_name','invoice_number','total','due_date','balance_due'],
    'workshop_received' => ['customer_name','company_name','request_number','equipment'],
    'workshop_update'   => ['customer_name','company_name','request_number','equipment','status','message'],
    'quote_approved'    => ['customer_name','company_name','estimate_number'],
    'promotional'       => ['customer_name','company_name','subject','content'],
    'password_reset'    => ['customer_name','company_name','reset_link'],
];
$templateLabels = [
    'welcome'           => '👋 Customer Welcome',
    'rfq_received'      => '📋 RFQ Received',
    'estimate_sent'     => '📄 Estimate Sent',
    'invoice_sent'      => '💰 Invoice Issued',
    'invoice_paid'      => '✅ Payment Confirmed',
    'payment_reminder'  => '⏰ Payment Reminder',
    'workshop_received' => '🛠️ Workshop Received',
    'workshop_update'   => '🔧 Workshop Update',
    'quote_approved'    => '🤝 Quote Approved',
    'promotional'       => '📣 Promotional / Ad',
    'password_reset'    => '🔑 Password Reset',
];
?>

<div class="flex items-center justify-between mb-6">
  <h2 class="text-lg font-semibold">Email Templates</h2>
  <span class="text-xs text-gray-500">All outgoing emails use these templates with your branding applied automatically</span>
</div>

<div class="flex gap-5" style="align-items:flex-start;">

  <!-- Left: Template list -->
  <div style="width:260px;flex-shrink:0;">
    <div class="card-dark overflow-hidden">
      <?php foreach ($templates as $tpl): ?>
      <?php $active = ($current && $current['id'] == $tpl['id']); ?>
      <a href="?edit=<?= $tpl['id'] ?>"
         class="flex items-start gap-3 px-4 py-3 border-b border-navy-600 hover:bg-navy-700 <?= $active ? 'bg-navy-700 border-l-2 border-l-orange-500' : '' ?>">
        <div class="flex-1 min-w-0">
          <div class="text-sm font-medium <?= $active ? 'text-orange-400' : 'text-gray-200' ?> truncate">
            <?= $templateLabels[$tpl['name']] ?? e($tpl['name']) ?>
          </div>
          <div class="text-xs text-gray-500 truncate mt-0.5 font-mono"><?= e($tpl['name']) ?></div>
        </div>
        <?php if ($active): ?><div class="text-orange-500 text-xs mt-0.5">→</div><?php endif; ?>
      </a>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Right: Editor -->
  <div class="flex-1 min-w-0">
  <?php if ($current): ?>

    <!-- Info bar -->
    <div class="flex items-center gap-3 mb-4">
      <div class="text-sm font-semibold text-white"><?= $templateLabels[$current['name']] ?? e($current['name']) ?></div>
      <span class="text-xs text-gray-500 font-mono bg-navy-800 px-2 py-0.5 rounded"><?= e($current['name']) ?></span>
      <?php if ($current['updated_at']): ?>
      <span class="text-xs text-gray-600">Last saved: <?= date('d M Y H:i', strtotime($current['updated_at'])) ?></span>
      <?php endif; ?>
    </div>

    <!-- Available variables -->
    <?php $vars = $varDocs[$current['name']] ?? []; ?>
    <?php if ($vars): ?>
    <div class="card-dark px-4 py-3 mb-4 flex flex-wrap gap-2 items-center">
      <span class="text-xs text-gray-400 mr-1">Available variables:</span>
      <?php foreach ($vars as $v): ?>
      <button type="button" onclick="insertVar('{{<?= $v ?>}}')"
              class="text-xs bg-navy-700 text-orange-400 px-2 py-0.5 rounded font-mono hover:bg-navy-600 cursor-pointer border border-navy-500"
              title="Click to insert">{{<?= $v ?>}}</button>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="flex gap-4" style="align-items:flex-start;">
      <!-- Edit form -->
      <div class="flex-1">
        <form method="POST" id="tpl-form">
          <input type="hidden" name="save_template" value="1">
          <input type="hidden" name="id" value="<?= $current['id'] ?>">

          <div class="card-dark p-5 mb-4">
            <label class="text-xs text-gray-400 block mb-1.5">Email Subject</label>
            <input type="text" name="subject" id="tpl-subject"
                   value="<?= e($current['subject']) ?>"
                   class="w-full font-medium" placeholder="Subject line with {{variables}}">
          </div>

          <div class="card-dark p-5 mb-4">
            <div class="flex items-center justify-between mb-2">
              <label class="text-xs text-gray-400">Email Body HTML</label>
              <div class="flex gap-2">
                <button type="button" onclick="togglePreview()" class="text-xs text-blue-400 hover:underline" id="preview-btn">👁 Preview</button>
              </div>
            </div>
            <textarea name="body" id="tpl-body" rows="20"
                      style="font-family:'Courier New',monospace;font-size:11px;resize:vertical;"
                      placeholder="HTML email body... use {{variable}} placeholders"><?= htmlspecialchars($current['body'], ENT_QUOTES) ?></textarea>
          </div>

          <div class="flex gap-3 mb-4">
            <button type="submit" class="btn-primary">💾 Save Template</button>
            <button type="button" onclick="togglePreview()" class="btn-outline">👁 Preview Email</button>
          </div>
        </form>

        <!-- Test send -->
        <div class="card-dark p-5">
          <h4 class="text-xs font-semibold text-gray-300 mb-3">Send Test Email</h4>
          <form method="POST" class="flex gap-3 items-end">
            <input type="hidden" name="send_test" value="1">
            <input type="hidden" name="id" value="<?= $current['id'] ?>">
            <div class="flex-1">
              <label class="text-xs text-gray-400 block mb-1.5">Send test to</label>
              <input type="email" name="test_email"
                     value="<?= e(setting('email','')) ?>"
                     placeholder="admin@example.com">
            </div>
            <button type="submit" class="btn-outline text-xs py-2">📤 Send Test</button>
          </form>
          <p class="text-xs text-gray-600 mt-2">Uses demo data — variables are filled with sample values so you see exactly how the email looks.</p>
        </div>
      </div>

      <!-- Live preview panel -->
      <div id="preview-panel" style="display:none;width:480px;flex-shrink:0;">
        <div class="card-dark p-3 mb-2 flex items-center justify-between">
          <span class="text-xs text-gray-400">Email Preview</span>
          <button onclick="togglePreview()" class="text-xs text-gray-500 hover:text-white">✕ Close</button>
        </div>
        <iframe id="preview-frame"
                style="width:100%;height:660px;border:none;border-radius:8px;background:#f1f3f6;"
                src="/admin/email-preview.php?id=<?= $current['id'] ?>"></iframe>
      </div>
    </div>

  <?php else: ?>
    <div class="card-dark p-12 text-center text-gray-500">
      <div class="text-4xl mb-4">✉</div>
      <p class="text-sm">Select a template from the left to edit it</p>
      <p class="text-xs mt-2 text-gray-600">All emails are automatically wrapped in your branded header and footer — you only edit the body content here.</p>
    </div>
  <?php endif; ?>
  </div><!-- /right -->

</div><!-- /flex -->

<script>
function insertVar(text) {
  const el = document.getElementById('tpl-body');
  if (!el) return;
  const start = el.selectionStart, end = el.selectionEnd;
  el.value = el.value.substring(0, start) + text + el.value.substring(end);
  el.selectionStart = el.selectionEnd = start + text.length;
  el.focus();
}

function togglePreview() {
  const panel = document.getElementById('preview-panel');
  const btn   = document.getElementById('preview-btn');
  if (panel.style.display === 'none') {
    panel.style.display = 'block';
    refreshPreview();
    if (btn) btn.textContent = '✕ Close Preview';
  } else {
    panel.style.display = 'none';
    if (btn) btn.textContent = '👁 Preview';
  }
}

function refreshPreview() {
  const body    = document.getElementById('tpl-body')?.value || '';
  const subject = document.getElementById('tpl-subject')?.value || '';
  const frame   = document.getElementById('preview-frame');
  if (!frame) return;
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = '/admin/email-preview.php';
  form.target = 'preview-frame';
  const addInput = (n,v) => { const i = document.createElement('input'); i.type='hidden'; i.name=n; i.value=v; form.appendChild(i); };
  addInput('body', body);
  addInput('subject', subject);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

// Auto-refresh preview when body changes (debounced)
let previewTimer;
document.getElementById('tpl-body')?.addEventListener('input', () => {
  clearTimeout(previewTimer);
  previewTimer = setTimeout(() => {
    if (document.getElementById('preview-panel')?.style.display !== 'none') refreshPreview();
  }, 800);
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
