<?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 team_members WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $name = trim((string)($_POST['name'] ?? ''));
    $des = trim((string)($_POST['designation'] ?? ''));
    $bio = trim((string)($_POST['bio'] ?? ''));
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($name === '') {
        $error = 'Name is required.';
    } else {
        $img = $row['image_path'] ?? null;
        $up = admin_save_upload('image', 'team');
        if ($up) {
            $img = $up;
        }
        if ($id > 0) {
            db()->prepare('UPDATE team_members SET name=?, designation=?, bio=?, image_path=?, sort_order=? WHERE id=?')
                ->execute([$name, $des, $bio, $img, $sort, $id]);
            admin_flash_set('success', 'Updated.');
            header('Location: team-view.php?id=' . $id);
            exit;
        }
        db()->prepare('INSERT INTO team_members (name, designation, bio, image_path, sort_order) VALUES (?,?,?,?,?)')
            ->execute([$name, $des, $bio, $img, $sort]);
        $nid = (int)db()->lastInsertId();
        admin_flash_set('success', 'Team member added.');
        header('Location: team-view.php?id=' . $nid);
        exit;
    }
}
if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Not found.');
    header('Location: team.php');
    exit;
}
$page = 'team';
$pageTitle = $id ? 'Edit team member' : 'New team member';
$pageSubtitle = 'Photo, name, role, and bio for the public Teams page.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Team', 'href' => 'team.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="team.php" class="btn btn-outline-secondary btn-sm">Back</a>';
if ($id && $row) {
    $headerActions .= '<a href="team-view.php?id=' . $id . '" class="btn btn-outline-primary btn-sm">View</a>';
}
require __DIR__ . '/includes/layout-header.php';
$r = $row ?: ['name' => '', 'designation' => '', 'bio' => '', '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">
      <div class="card-header">Profile</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
          <input type="text" name="name" class="form-control" required value="<?= h((string)($_POST['name'] ?? $r['name'])) ?>">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Designation / role</label>
          <input type="text" name="designation" class="form-control" value="<?= h((string)($_POST['designation'] ?? $r['designation'])) ?>">
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Bio</label>
          <textarea name="bio" class="form-control" rows="8"><?= h((string)($_POST['bio'] ?? $r['bio'])) ?></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-3">
      <div class="card-header">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:120px;height:120px;object-fit:cover;" alt=""></div><?php endif; ?>
        <input type="file" name="image" class="form-control" accept="image/*">
      </div>
    </div>
    <div class="admin-card rounded mb-3">
      <div class="card-header">Order</div>
      <div class="card-body">
        <input type="number" name="sort_order" class="form-control" value="<?= (int)($_POST['sort_order'] ?? $r['sort_order']) ?>">
      </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="team.php" class="btn btn-outline-secondary w-100">Cancel</a>
  </div>
</form>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
