<?php
declare(strict_types=1);

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

function respond(int $status, array $payload): void {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}
function pickSessionName(): ?string {
  if (!empty($_COOKIE['PHPSESSADM'])) return 'PHPSESSADM';
  if (!empty($_COOKIE['PHPSESSCLI'])) return 'PHPSESSCLI';
  if (!empty($_COOKIE['PHPSESSAFF'])) return 'PHPSESSAFF';
  return null;
}

require_once __DIR__ . '/conn.php'; // expects $db (PDO)

/** Session */
$sessionName = pickSessionName();
if (!$sessionName) respond(401, ['error' => 'Not authenticated']);
session_name($sessionName);
session_start();

$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) $userId = (int)($_SESSION['SESS_MEMBER_ID'] ?? 0);

$isAdmin = (int)($_SESSION['is_admin'] ?? 0);

if ($userId <= 0) respond(401, ['error' => 'Not authenticated']);
// Admin access rule (keep as you had it)
if ($sessionName !== 'PHPSESSADM' && $isAdmin !== 1) respond(403, ['error' => 'Admin access required']);

/** Input */
$q = trim((string)($_GET['q'] ?? ''));
if ($q === '') respond(200, ['users' => []]);

$like = '%' . $q . '%';

try {
  $stmt = $db->prepare("
    SELECT id, name, email, username, role, county_id, constituency_id, ward_id, polling_station_id
    FROM users
    WHERE
      name LIKE :q
      OR email LIKE :q
      OR username LIKE :q
      OR mpesa_number LIKE :q
      OR voice_number LIKE :q
    ORDER BY name ASC
    LIMIT 30
  ");
  $stmt->execute([':q' => $like]);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  // Normalize types for frontend
  $users = array_map(function($u) {
    return [
      'id' => (string)$u['id'],
      'name' => $u['name'],
      'email' => $u['email'],
      'username' => $u['username'] ?? null,
      'role' => $u['role'] ?? null,
      'county_id' => isset($u['county_id']) ? (int)$u['county_id'] : null,
      'constituency_id' => isset($u['constituency_id']) ? (int)$u['constituency_id'] : null,
      'ward_id' => isset($u['ward_id']) ? (int)$u['ward_id'] : null,
      'polling_station_id' => isset($u['polling_station_id']) ? (int)$u['polling_station_id'] : null,
    ];
  }, $rows);

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

} catch (Throwable $e) {
  respond(500, [
    'error' => 'User search failed',
    'details' => $e->getMessage(), // remove in prod if desired
  ]);
}
