<?php

require_once "config.php";

$user = roomAuth();

$roomId = trim((string)($_GET["room_id"] ?? ""));

if ($roomId === "") {
    roomJson([
        "ok" => false,
        "message" => "room_id is required"
    ], 400);
}

try {

    /*
     * Check room.
     */
    $roomStmt = $pdo->prepare("
        SELECT
            room_id,
            owner_id,
            name,
            room_level,
            max_admins,
            status
        FROM rooms
        WHERE room_id = ?
        LIMIT 1
    ");

    $roomStmt->execute([$roomId]);

    $room = $roomStmt->fetch(PDO::FETCH_ASSOC);

    if (!$room) {
        roomJson([
            "ok" => false,
            "message" => "Room not found"
        ], 404);
    }

    /*
     * Only room members can view
     * room moderation information.
     */
    $memberStmt = $pdo->prepare("
        SELECT role
        FROM room_members
        WHERE room_id = ?
          AND user_id = ?
        LIMIT 1
    ");

    $memberStmt->execute([
        $roomId,
        $user["user_id"]
    ]);

    $member = $memberStmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        roomJson([
            "ok" => false,
            "message" => "You are not a member of this room"
        ], 403);
    }

    /*
     * Get moderators.
     */
    $stmt = $pdo->prepare("
        SELECT
            rm.id,
            rm.room_id,
            rm.user_id,
            rm.permissions,
            rm.created_at,
            u.name,
            u.avatar,
            u.status
        FROM room_moderators rm
        INNER JOIN users u
            ON u.user_id = rm.user_id
        WHERE rm.room_id = ?
        ORDER BY rm.id ASC
    ");

    $stmt->execute([$roomId]);

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

    $moderators = [];

    foreach ($rows as $row) {

        $permissions = [];

        if (!empty($row["permissions"])) {

            $decoded = json_decode(
                $row["permissions"],
                true
            );

            if (is_array($decoded)) {
                $permissions = $decoded;
            }
        }

        $moderators[] = [
            "id" => (int)$row["id"],
            "user_id" => $row["user_id"],
            "name" => $row["name"],
            "avatar" => $row["avatar"] ?? "",
            "status" => $row["status"],
            "role" => $permissions["role"] ?? "moderator",
            "permissions" => $permissions,
            "created_at" => $row["created_at"]
        ];
    }

    roomJson([
        "ok" => true,

        "room" => [
            "room_id" => $room["room_id"],
            "name" => $room["name"],
            "room_level" => (int)$room["room_level"],
            "max_admins" => (int)$room["max_admins"]
        ],

        "count" => count($moderators),

        "moderators" => $moderators
    ]);

} catch (Throwable $e) {

    roomJson([
        "ok" => false,
        "message" => "Unable to load moderators",
        "error" => $e->getMessage()
    ], 500);
}