<?php
declare(strict_types=1);

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

function respond(int $s, array $p): void {
  http_response_code($s);
  echo json_encode($p, 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';

/** ---------- Role helpers (adjust strings to match users.role) ---------- */
function roleIs(array $user, array $roles): bool {
  $r = strtolower((string)($user['role'] ?? ''));
  foreach ($roles as $x) if ($r === strtolower($x)) return true;
  return false;
}
function isSuperAdmin(array $u): bool { return roleIs($u, ['super_admin','superadmin']); }
function isNational(array $u): bool { return roleIs($u, ['national','national_leader']); }
function isCounty(array $u): bool { return roleIs($u, ['county','county_rep']); }
function isConstituency(array $u): bool { return roleIs($u, ['constituency','constituency_rep']); }
function isWard(array $u): bool { return roleIs($u, ['ward','ward_rep']); }

function isMember(PDO $db, int $roomId, int $userId): bool {
  $st = $db->prepare("SELECT 1 FROM pth_party_room_members WHERE room_id=:rid AND user_id=:uid LIMIT 1");
  $st->execute([':rid'=>$roomId, ':uid'=>$userId]);
  return (bool)$st->fetchColumn();
}

function canAccessScopeRoom(array $user, array $room): bool {
  if (isSuperAdmin($user)) return true;
  if (isNational($user)) return true;

  $scope = (string)($room['scope_level'] ?? '');

  // POLICY: allow everyone to access national rooms (recommended for ops)
  if ($scope === 'national') return true;

  $uCounty = (int)($user['county_id'] ?? 0);
  $uConst  = (int)($user['constituency_id'] ?? 0);
  $uWard   = (int)($user['ward_id'] ?? 0);
  $uPs     = (int)($user['polling_station_id'] ?? 0);

  $rCounty = (int)($room['county_id'] ?? 0);
  $rConst  = (int)($room['constituency_id'] ?? 0);
  $rWard   = (int)($room['ward_id'] ?? 0);
  $rPs     = (int)($room['polling_station_id'] ?? 0);

  if ($scope === 'county') return $uCounty > 0 && $uCounty === $rCounty;

  if ($scope === 'constituency') {
    if (isCounty($user)) return $uCounty > 0 && $uCounty === $rCounty;
    return $uConst > 0 && $uConst === $rConst;
  }

  if ($scope === 'ward') {
    if (isCounty($user)) return $uCounty > 0 && $uCounty === $rCounty;
    if (isConstituency($user)) return $uConst > 0 && $uConst === $rConst;
    return $uWard > 0 && $uWard === $rWard;
  }

  if ($scope === 'polling_station') {
    if (isCounty($user)) return $uCounty > 0 && $uCounty === $rCounty;
    if (isConstituency($user)) return $uConst > 0 && $uConst === $rConst;
    if (isWard($user)) return $uWard > 0 && $uWard === $rWard;
    return $uPs > 0 && $uPs === $rPs;
  }

  return false;
}

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

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

/** ---------- Input ---------- */
$roomIdRaw = trim((string)($_POST['roomId'] ?? ''));
if ($roomIdRaw === '' || !ctype_digit($roomIdRaw)) respond(400, ['error'=>'roomId required']);
$roomId = (int)$roomIdRaw;

/** ---------- Load room ---------- */
$roomStmt = $db->prepare("
  SELECT id, room_type, scope_level, county_id, constituency_id, ward_id, polling_station_id
  FROM pth_party_room
  WHERE id = :rid
  LIMIT 1
");
$roomStmt->execute([':rid'=>$roomId]);
$room = $roomStmt->fetch(PDO::FETCH_ASSOC);
if (!$room) respond(404, ['error'=>'Room not found']);

/** ---------- Load user context ---------- */
$userStmt = $db->prepare("
  SELECT id, role, county_id, constituency_id, ward_id, polling_station_id
  FROM users
  WHERE id = :uid
  LIMIT 1
");
$userStmt->execute([':uid'=>$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);
if (!$user) respond(401, ['error'=>'User not found']);

/** ---------- Authorization ---------- */
$roomType = (string)($room['room_type'] ?? '');
$scopeLevel = (string)($room['scope_level'] ?? '');

$allowed = false;
if ($roomType === 'dm' || $scopeLevel === 'custom') {
  $allowed = isMember($db, $roomId, $userId);
} else {
  $allowed = canAccessScopeRoom($user, $room);
}
if (!$allowed) respond(403, ['error'=>'Not allowed']);

/** ---------- Latest message id in this room ---------- */
$last = $db->prepare("SELECT COALESCE(MAX(id),0) FROM pth_party_messages WHERE room_id=:rid");
$last->execute([':rid'=>$roomId]);
$lastId = (int)$last->fetchColumn();

/** ---------- Upsert read state ---------- */
$up = $db->prepare("
  INSERT INTO pth_party_room_user_state (room_id, user_id, last_read_message_id, is_archived)
  VALUES (:rid, :uid, :mid, 0)
  ON DUPLICATE KEY UPDATE
    last_read_message_id = VALUES(last_read_message_id),
    is_archived = 0,
    updated_at = CURRENT_TIMESTAMP
");
$up->execute([':rid'=>$roomId, ':uid'=>$userId, ':mid'=>$lastId]);

respond(200, ['ok'=>true, 'lastReadMessageId'=>$lastId]);
