<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_once __DIR__ . '/includes/upload.php';
require_admin();
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
$id = (int)($_GET['id'] ?? 0);
$row = null;
if ($id > 0) {
    $st = db()->prepare('SELECT * FROM testimonials WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $name = trim((string)($_POST['client_name'] ?? ''));
    $content = trim((string)($_POST['content'] ?? ''));
    $rating = min(5, max(1, (int)($_POST['rating'] ?? 5)));
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($name === '' || $content === '') {
        $error = 'Client name and testimonial text are required.';
    } else {
        $img = $row['image_path'] ?? null;
        $up = admin_save_upload('image', 'testimonials');
        if ($up) {
            $img = $up;
        }
        if ($id > 0) {
            db()->prepare('UPDATE testimonials SET client_name=?, content=?, rating=?, image_path=?, sort_order=? WHERE id=?')
                ->execute([$name, $content, $rating, $img, $sort, $id]);
            admin_flash_set('success', 'Testimonial updated.');
        } else {
            db()->prepare('INSERT INTO testimonials (client_name, content, rating, image_path, sort_order) VALUES (?,?,?,?,?)')
                ->execute([$name, $content, $rating, $img, $sort]);
            admin_flash_set('success', 'Testimonial added.');
        }
        header('Location: testimonials.php');
        exit;
    }
}
if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Not found.');
    header('Location: testimonials.php');
    exit;
}
$page = 'testimonials';
$pageTitle = $id ? 'Edit testimonial' : 'New testimonial';
$pageSubtitle = 'Shown on the testimonials page and homepage section.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Testimonials', 'href' => 'testimonials.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="testimonials.php" class="btn btn-outline-secondary btn-sm">Back to list</a>';
require __DIR__ . '/includes/layout-header.php';
$r = $row ?: ['client_name' => '', 'content' => '', 'rating' => 5, 'image_path' => '', 'sort_order' => 0];
if ($error) {
    echo '<div class="alert alert-danger">' . h($error) . '</div>';
}
?>
<form method="post" enctype="multipart/form-data" class="row g-4">
  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
  <div class="col-lg-8">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Quote</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Client name <span class="text-danger">*</span></label>
          <input type="text" name="client_name" class="form-control" required value="<?= h((string)($_POST['client_name'] ?? $r['client_name'])) ?>">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Testimonial <span class="text-danger">*</span></label>
          <textarea name="content" class="form-control" rows="8" required><?= h((string)($_POST['content'] ?? $r['content'])) ?></textarea>
        </div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-semibold">Star rating (1–5)</label>
            <input type="number" name="rating" class="form-control" min="1" max="5" value="<?= (int)($_POST['rating'] ?? $r['rating']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Sort order</label>
            <input type="number" name="sort_order" class="form-control" value="<?= (int)($_POST['sort_order'] ?? $r['sort_order']) ?>">
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-3">
      <div class="card-header">Optional photo</div>
      <div class="card-body">
        <?php if (!empty($r['image_path'])): ?><div class="text-center mb-3"><img src="../<?= h((string)$r['image_path']) ?>" class="rounded-circle border" style="width:100px;height:100px;object-fit:cover;" alt=""></div><?php endif; ?>
        <input type="file" name="image" class="form-control" accept="image/*">
      </div>
    </div>
    <button type="submit" class="btn btn-primary btn-lg w-100 mb-2"><i class="bi bi-check-lg me-1"></i>Save</button>
    <a href="testimonials.php" class="btn btn-outline-secondary w-100">Cancel</a>
  </div>
</form>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
