<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'FAQ Management';
$success = $error = '';
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM faqs WHERE id=?", [$id]);
  header('Location: /admin/faq.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE faqs SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/faq.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $question = trim($_POST['question'] ?? '');
  $answer   = trim($_POST['answer'] ?? '');
  $category = trim($_POST['category'] ?? 'General');
  $sort     = (int)($_POST['sort_order'] ?? 0);
  if (!$question || !$answer) { $error = 'Question and answer are required.'; }
  else {
    if ($id) {
      Database::execute("UPDATE faqs SET question=?,answer=?,category=?,sort_order=? WHERE id=?", [$question,$answer,$category,$sort,$id]);
      $success = 'FAQ updated.';
    } else {
      Database::insert("INSERT INTO faqs (question,answer,category,sort_order,is_active) VALUES (?,?,?,?,1)", [$question,$answer,$category,$sort]);
      $success = 'FAQ added.'; $id = db()->lastInsertId(); $action = 'edit';
    }
  }
}
$faq = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM faqs WHERE id=?",[$id]) : null;
$faqs = $action==='list' ? Database::fetchAll("SELECT * FROM faqs ORDER BY sort_order,id") : [];
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">❓ FAQ Management</h1>
    <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Add FAQ</a>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">FAQ deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="data-table">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">#</th><th class="px-4 py-3 text-left">Question</th><th class="px-4 py-3 text-left">Category</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$faqs): ?><tr><td colspan="5" class="px-4 py-8 text-center text-gray-500">No FAQs yet. <a href="?action=new" class="text-orange-400">Add first FAQ →</a></td></tr><?php endif; ?>
        <?php foreach ($faqs as $f): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 text-gray-500"><?= $f['sort_order'] ?></td>
          <td class="px-4 py-3 font-medium max-w-sm truncate"><?= e($f['question']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($f['category']) ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $f['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $f['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $f['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $f['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $f['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete this FAQ?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/faq.php" class="text-gray-400 hover:text-white text-sm">← All FAQs</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit FAQ' : 'New FAQ' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>
  <form method="POST" class="card-dark p-6 max-w-2xl">
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Question *</label>
      <input type="text" name="question" value="<?= e($faq['question'] ?? '') ?>" class="input-field" required placeholder="What is your typical lead time?">
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Answer *</label>
      <textarea name="answer" rows="6" class="input-field" required placeholder="Detailed answer..."><?= e($faq['answer'] ?? '') ?></textarea>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Category</label>
        <input type="text" name="category" value="<?= e($faq['category'] ?? 'General') ?>" class="input-field" list="faq-cats">
        <datalist id="faq-cats"><option>General</option><option>Sourcing</option><option>Quality</option><option>Payment</option><option>Technical</option><option>Services</option></datalist>
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Sort Order</label>
        <input type="number" name="sort_order" value="<?= e($faq['sort_order'] ?? 0) ?>" class="input-field" min="0">
      </div>
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save FAQ</button>
      <a href="/admin/faq.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>
</div>

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