<?php
require_once __DIR__ . '/../includes/functions.php';
requireAdmin();
require __DIR__ . '/includes/ui.php';
$pageTitle = 'Testimonials';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrfVerify($_POST['csrf_token'] ?? null)) {
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $fields = [
            trim($_POST['name'] ?? ''),
            trim($_POST['company'] ?? ''),
            trim($_POST['message'] ?? ''),
            max(1, min(5, (int) ($_POST['rating'] ?? 5))),
            (int) ($_POST['sort_order'] ?? 0),
            isset($_POST['is_active']) ? 1 : 0,
        ];
        if ($id > 0) {
            db()->prepare('UPDATE testimonials SET name=?,company=?,message=?,rating=?,sort_order=?,is_active=? WHERE id=?')->execute([...$fields, $id]);
        } else {
            db()->prepare('INSERT INTO testimonials (name,company,message,rating,sort_order,is_active) VALUES (?,?,?,?,?,?)')->execute($fields);
        }
        flash('success', 'Testimonial saved.');
    } elseif ($action === 'delete') {
        db()->prepare('DELETE FROM testimonials WHERE id = ?')->execute([(int) ($_POST['id'] ?? 0)]);
        flash('success', 'Testimonial deleted.');
    }
    redirect('testimonials.php');
}

require __DIR__ . '/includes/admin-header.php';
adminFlashBox();
$items = db()->query('SELECT * FROM testimonials ORDER BY sort_order ASC, id ASC')->fetchAll();
$editId = (int) ($_GET['edit'] ?? 0);
$editing = null;
foreach ($items as $i) { if ((int) $i['id'] === $editId) $editing = $i; }
?>
<div class="grid lg:grid-cols-3 gap-6">
  <div class="lg:col-span-2 space-y-3">
    <?php foreach ($items as $i): ?>
      <div class="bg-white rounded-2xl border border-gray-100 p-5 flex items-start gap-4">
        <div class="flex-1 min-w-0">
          <p class="font-semibold text-sm"><?= e($i['name']) ?> <span class="text-gray-400 font-normal">· <?= e($i['company']) ?></span></p>
          <p class="text-xs text-gray-500 mt-1"><?= e($i['message']) ?></p>
          <p class="text-xs text-amber-500 mt-1"><?= str_repeat('★', (int) $i['rating']) . str_repeat('☆', 5 - (int) $i['rating']) ?></p>
        </div>
        <a href="?edit=<?= (int) $i['id'] ?>" class="text-primary font-semibold text-sm">Edit</a>
        <form method="post" onsubmit="return confirm('Delete this testimonial?');">
          <input type="hidden" name="csrf_token" value="<?= e(csrfToken()) ?>" />
          <input type="hidden" name="action" value="delete" />
          <input type="hidden" name="id" value="<?= (int) $i['id'] ?>" />
          <button class="text-red-600 font-semibold text-sm">Delete</button>
        </form>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="bg-white rounded-2xl border border-gray-100 p-6 h-fit">
    <h2 class="font-heading font-semibold mb-4"><?= $editing ? 'Edit Testimonial' : 'Add Testimonial' ?></h2>
    <form method="post">
      <input type="hidden" name="csrf_token" value="<?= e(csrfToken()) ?>" />
      <input type="hidden" name="action" value="save" />
      <input type="hidden" name="id" value="<?= (int) ($editing['id'] ?? 0) ?>" />
      <?php inputField('Client Name', 'name', $editing['name'] ?? '', 'text', true); ?>
      <?php inputField('Company', 'company', $editing['company'] ?? ''); ?>
      <?php textareaField('Message', 'message', $editing['message'] ?? '', 4, true); ?>
      <?php numberField('Rating (1-5)', 'rating', $editing['rating'] ?? 5); ?>
      <?php numberField('Sort Order', 'sort_order', $editing['sort_order'] ?? 0); ?>
      <?php checkboxField('Active', 'is_active', $editing ? !empty($editing['is_active']) : true); ?>
      <button class="btn-primary-brand bg-primary text-white px-5 py-2.5 rounded-lg font-semibold w-full"><?= $editing ? 'Update' : 'Add Testimonial' ?></button>
      <?php if ($editing): ?><a href="testimonials.php" class="block text-center text-sm text-gray-500 mt-3">Cancel edit</a><?php endif; ?>
    </form>
  </div>
</div>
<?php require __DIR__ . '/includes/admin-footer.php'; ?>
