<?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)) {
    db()->prepare('DELETE FROM team_members WHERE id = ?')->execute([(int)$_POST['delete_id']]);
    admin_flash_set('success', 'Team member removed.');
    header('Location: team.php');
    exit;
}
$perPage = 15;
$q = trim((string)($_GET['q'] ?? ''));
$pageNum = max(1, (int)($_GET['page'] ?? 1));
$where = '';
$params = [];
if ($q !== '') {
    $where = 'WHERE name LIKE ? OR designation LIKE ? OR bio LIKE ?';
    $qq = '%' . $q . '%';
    $params = [$qq, $qq, $qq];
}
$stc = db()->prepare('SELECT COUNT(*) FROM team_members ' . $where);
$stc->execute($params);
$total = (int)$stc->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));
if ($pageNum > $pages) {
    $pageNum = $pages;
}
$offset = ($pageNum - 1) * $perPage;
$st = db()->prepare('SELECT * FROM team_members ' . $where . ' ORDER BY sort_order ASC, id ASC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset);
$st->execute($params);
$rows = $st->fetchAll();

$page = 'team';
$pageTitle = 'Team';
$pageSubtitle = 'People shown on the Teams page.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Team', 'href' => null]];
$headerActions = '<a href="team-edit.php" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add member</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-5">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Name, role, bio…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary">Search</button>
        <?php if ($q !== ''): ?><a href="team.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">Team members (<?= $total ?>)</div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead><tr><th>ID</th><th>Photo</th><th>Name</th><th>Role</th><th>Order</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']) ?>" class="admin-thumb rounded-circle" alt=""><?php else: ?>—<?php endif; ?></td>
            <td class="fw-semibold"><?= h((string)$r['name']) ?></td>
            <td><?= h((string)($r['designation'] ?? '—')) ?></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td class="text-end text-nowrap">
              <a href="team-view.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-secondary">View</a>
              <a href="team-edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete?');">
                <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-4">No team members. <a href="team-edit.php">Add one</a>.</div><?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
