<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_admin();

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id']) && csrf_verify($_POST['csrf'] ?? null)) {
    $id = (int)$_POST['delete_id'];
    if ($id > 0) {
        db()->prepare('DELETE FROM services WHERE id = ?')->execute([$id]);
        admin_flash_set('success', 'Service deleted successfully.');
    }
    header('Location: services.php');
    exit;
}

$perPage = 12;
$q = trim((string)($_GET['q'] ?? ''));
$pageNum = max(1, (int)($_GET['page'] ?? 1));

$where = '';
$params = [];
if ($q !== '') {
    $where = 'WHERE title LIKE ? OR slug LIKE ? OR short_description LIKE ?';
    $params = ['%' . $q . '%', '%' . $q . '%', '%' . $q . '%'];
}

$countSql = 'SELECT COUNT(*) FROM services ' . $where;
$stc = db()->prepare($countSql);
$stc->execute($params);
$total = (int)$stc->fetchColumn();

$pages = max(1, (int)ceil($total / $perPage));
if ($pageNum > $pages) {
    $pageNum = $pages;
}
$offset = ($pageNum - 1) * $perPage;

$sql = 'SELECT * FROM services ' . $where . ' ORDER BY sort_order ASC, id ASC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
$st = db()->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll();

$page = 'services';
$pageTitle = 'Services';
$pageSubtitle = 'Create, edit, or remove services. Slugs power public URLs (service-detail.php?slug=…).';
$breadcrumbs = [
    ['label' => 'Dashboard', 'href' => 'index.php'],
    ['label' => 'Services', 'href' => null],
];
$headerActions = '<a href="service-edit.php" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add service</a>';

require __DIR__ . '/includes/layout-header.php';
?>
<div class="admin-card rounded mb-3">
  <div class="card-body py-3">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-6 col-lg-4">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Title, slug, or short description…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary"><i class="bi bi-search me-1"></i>Search</button>
        <?php if ($q !== ''): ?><a href="services.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
      </div>
    </form>
  </div>
</div>

<div class="admin-card rounded">
  <div class="card-header py-3 d-flex justify-content-between align-items-center">
    <span>All services (<?= $total ?>)</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Image</th>
          <th>Title</th>
          <th>Slug</th>
          <th>Order</th>
          <th>Created</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td class="text-muted"><?= (int)$r['id'] ?></td>
            <td>
              <?php if (!empty($r['image_path'])): ?>
                <img src="../<?= h((string)$r['image_path']) ?>" alt="" class="admin-thumb">
              <?php else: ?>
                <span class="text-muted small">—</span>
              <?php endif; ?>
            </td>
            <td class="fw-semibold"><?= h((string)$r['title']) ?></td>
            <td><code class="small"><?= h((string)$r['slug']) ?></code></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td class="small text-muted"><?= h((string)$r['created_at']) ?></td>
            <td class="text-end text-nowrap">
              <a href="service-view.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-secondary" title="View">View</a>
              <a href="service-edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary" title="Edit">Edit</a>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete “<?= h(addslashes((string)$r['title'])) ?>”? This cannot be undone.');">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="delete_id" value="<?= (int)$r['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if (!$rows): ?>
    <div class="card-body text-center text-muted py-5">No services found. <a href="service-edit.php">Add your first service</a>.</div>
  <?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>

<?php require __DIR__ . '/includes/layout-footer.php'; ?>
