<?php
declare(strict_types=1);

require_once __DIR__ . '/_cors.php';
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/conn.php';

function respond(int $status, array $payload): void {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

function roleIs(array $user, array $roles): bool {
  $r = strtolower((string)($user['role'] ?? ''));
  foreach ($roles as $x) {
    if ($r === strtolower($x)) return true;
  }
  return false;
}

session_start();
$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) {
  respond(401, ['error' => 'Not authenticated']);
}

/** Load current user */
$userStmt = $db->prepare("
  SELECT id, role, county_id, constituency_id, ward_id
  FROM users
  WHERE id = :uid
  LIMIT 1
");
$userStmt->execute([':uid' => $userId]);
$currentUser = $userStmt->fetch(PDO::FETCH_ASSOC);

if (!$currentUser) {
  respond(401, ['error' => 'User not found']);
}

/** Build hierarchy-based filter */
$where = "id <> :uid";
$params = [':uid' => $userId];

if (roleIs($currentUser, ['super_admin','superadmin'])) {
  // sees everyone
}
elseif (roleIs($currentUser, ['national','national_leader'])) {
  // sees everyone except super admins (optional)
  $where .= " AND role NOT IN ('super_admin','superadmin')";
}
elseif (roleIs($currentUser, ['county','county_rep'])) {
  $where .= " AND county_id = :county_id";
  $params[':county_id'] = $currentUser['county_id'];
}
elseif (roleIs($currentUser, ['constituency','constituency_rep'])) {
  $where .= " AND constituency_id = :const_id";
  $params[':const_id'] = $currentUser['constituency_id'];
}
elseif (roleIs($currentUser, ['ward','ward_rep'])) {
  $where .= " AND ward_id = :ward_id";
  $params[':ward_id'] = $currentUser['ward_id'];
}
else {
  // agents can see only their ward (you can adjust policy)
  $where .= " AND ward_id = :ward_id";
  $params[':ward_id'] = $currentUser['ward_id'];
}

/** Fetch users */
$stmt = $db->prepare("
  SELECT id, name, email, role
  FROM users
  WHERE $where
  ORDER BY name ASC
  LIMIT 200
");

$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$users = array_map(function ($u) {
  return [
    'id'    => (string)$u['id'],
    'name'  => $u['name'],
    'email' => $u['email'],
    'role'  => $u['role'],
  ];
}, $rows);

respond(200, ['users' => $users]);
