<?php
declare(strict_types=1);

// =========================
// CORS + HEADERS
// =========================
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

header("Vary: Origin");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");

if ($origin && preg_match('#^https://([a-z0-9.-]+\.)?skizagroundsuite\.com$#i', $origin)) {
    header("Access-Control-Allow-Origin: {$origin}");
} else {
    header("Access-Control-Allow-Origin: https://skizagroundsuite.com");
}

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

if ($method === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($method !== 'GET') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Only GET allowed"]);
    exit;
}

// =========================
// Helpers
// =========================
function respond(int $code, array $payload): void {
    http_response_code($code);
    echo json_encode($payload);
    exit;
}

// =========================
// DB
// =========================
require_once __DIR__ . '/conn.php';

if ($conn->connect_error) {
    respond(500, ["status" => "error", "message" => "Database connection failed"]);
}

// =========================
// JWT
// =========================
require __DIR__ . '/../../../../../API/jwt-api/vendor/autoload.php';


use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$secretKey = "0gak57yt8tfz1o0t8h9uoga3utxwwzd7";

// =========================
// AUTH
// =========================
$authHeader =
    $_SERVER['HTTP_AUTHORIZATION'] ??
    $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ??
    '';

preg_match('/Bearer\s+(\S+)/', $authHeader, $m);
$token = $m[1] ?? ($_COOKIE['token'] ?? '');

if (!$token) respond(401, ["status" => "error", "message" => "Missing token"]);

try {
    $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
} catch (Throwable $e) {
    respond(401, ["status" => "error", "message" => "Invalid token"]);
}

$userData = (array)($decoded->user_data ?? []);
$userId = (int)($userData['id'] ?? 0);

if ($userId <= 0) {
    respond(401, ["status" => "error", "message" => "Invalid session"]);
}

// =========================
// FETCH USER ROLE
// =========================
$u = $conn->prepare("SELECT id, role FROM users WHERE id = ?");
$u->bind_param("i", $userId);
$u->execute();
$res = $u->get_result();

if (!$res->num_rows) {
    respond(401, ["status" => "error", "message" => "User not found"]);
}

$user = $res->fetch_assoc();
$u->close();

$currentUserRole = strtoupper(trim((string)$user['role']));

// =========================
// DETECT ROLE COLUMN SAFELY
// =========================
$roleCol = null;
$cols = ['role_name', 'name', 'role'];

$colStmt = $conn->prepare("
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'roles'
      AND COLUMN_NAME = ?
    LIMIT 1
");

foreach ($cols as $c) {
    $colStmt->bind_param("s", $c);
    $colStmt->execute();
    if ($colStmt->get_result()->num_rows) {
        $roleCol = $c;
        break;
    }
}
$colStmt->close();

if (!$roleCol) {
    respond(500, ["status" => "error", "message" => "roles table misconfigured"]);
}

// =========================
// PERMISSION CHECK
// =========================
$permissionName = 'rooms.view';

$sqlPerm = "
    SELECT 1
    FROM roles r
    JOIN role_permissions rp ON rp.role_id = r.id
    JOIN permissions p ON p.permission_id = rp.permission_id
    WHERE UPPER(r.`$roleCol`) = ?
      AND LOWER(p.permission_name) = ?
    LIMIT 1
";

$ps = $conn->prepare($sqlPerm);
$permLower = strtolower($permissionName);
$ps->bind_param("ss", $currentUserRole, $permLower);
$ps->execute();
$hasPerm = $ps->get_result()->num_rows > 0;
$ps->close();

if (!$hasPerm) {
    respond(403, ["status" => "error", "message" => "Not authorised"]);
}

// =========================
// INPUT FILTERS
// =========================
$roomType   = trim($_GET['room_type'] ?? '');
$scopeLevel = trim($_GET['scope_level'] ?? '');

$allowedRoomTypes = ['group', 'dm', 'announcement'];
$allowedScopes    = ['polling_station', 'ward', 'constituency', 'county', 'national', 'custom'];

$where  = [];
$params = [];
$types  = '';

if ($roomType !== '') {
    if (!in_array($roomType, $allowedRoomTypes, true)) {
        respond(400, ["status" => "error", "message" => "Invalid room_type"]);
    }
    $where[] = "room_type = ?";
    $params[] = $roomType;
    $types .= 's';
}

if ($scopeLevel !== '') {
    if (!in_array($scopeLevel, $allowedScopes, true)) {
        respond(400, ["status" => "error", "message" => "Invalid scope_level"]);
    }
    $where[] = "scope_level = ?";
    $params[] = $scopeLevel;
    $types .= 's';
}

// =========================
// BUILD QUERY
// =========================
$sql = "
    SELECT
        id,
        room_key,
        room_name,
        room_type,
        scope_level,
        county_id,
        constituency_id,
        ward_id,
        polling_station_id,
        party_id,
        created_by,
        created_at
    FROM pth_party_room
";

if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY created_at DESC, id DESC";

// =========================
// EXECUTE
// =========================
$stmt = $conn->prepare($sql);

if ($params) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$rooms = [];

while ($r = $result->fetch_assoc()) {
    $rooms[] = [
        'id' => (string)$r['id'],
        'room_key' => $r['room_key'],
        'room_name' => $r['room_name'],
        'room_type' => $r['room_type'],
        'scope_level' => $r['scope_level'],
        'county_id' => $r['county_id'] !== null ? (int)$r['county_id'] : null,
        'constituency_id' => $r['constituency_id'] !== null ? (int)$r['constituency_id'] : null,
        'ward_id' => $r['ward_id'] !== null ? (int)$r['ward_id'] : null,
        'polling_station_id' => $r['polling_station_id'] !== null ? (int)$r['polling_station_id'] : null,
        'party_id' => $r['party_id'] !== null ? (int)$r['party_id'] : null,
        'created_by' => $r['created_by'] !== null ? (int)$r['created_by'] : null,
        'created_at' => $r['created_at'],
    ];
}

$stmt->close();

respond(200, [
    "status" => "success",
    "rooms" => $rooms
]);
