<?php

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/vessel_selection.php';
require_once __DIR__ . '/../services/VesselAdminService.php';
require_once __DIR__ . '/../services/PermissionService.php';

function current_vessel_context(): ?array
{
    $user = current_user();
    if (!$user) {
        return null;
    }

    $userId = (int)$user['id'];
    $selectedVesselId = get_selected_vessel_id();
    $userVessels = VesselAdminService::getVesselsForUser($userId);

    foreach ($userVessels as $v) {
        if ($selectedVesselId && (int)$v['id'] === (int)$selectedVesselId) {
            return $v;
        }
    }

    if (!empty($userVessels)) {
        return $userVessels[0];
    }

    return null;
}

function current_user_roles_for_current_vessel(): array
{
    $user = current_user();
    $vessel = current_vessel_context();

    if (!$user || !$vessel) {
        return [];
    }

    $userId = (int)$user['id'];
    $roles = [];

    if (PermissionService::isSuperadmin($userId)) {
        $roles[] = 'superadmin';
    }

    $orgRole = PermissionService::getDirectOrganizationRole(
        $userId,
        (int)$vessel['organization_id']
    );

    if ($orgRole) {
        $roles[] = $orgRole;
    }

    $roles = array_values(array_unique($roles));

    $order = array_flip(['org_user', 'org_manager', 'org_admin', 'superadmin']);
    usort($roles, static function (string $a, string $b) use ($order): int {
        return ($order[$a] ?? 999) <=> ($order[$b] ?? 999);
    });

    return $roles;
}

function user_can_view_segment(array $allowedRoles): bool
{
    if (empty($allowedRoles)) {
        return true;
    }

    $roles = current_user_roles_for_current_vessel();

    foreach ($roles as $role) {
        if (in_array($role, $allowedRoles, true)) {
            return true;
        }
    }

    return false;
}

function user_is_superadmin_for_current_vessel(): bool
{
    return user_can_view_segment(['superadmin']);
}

function user_is_superadmin(): bool
{
    $user = current_user();
    if (!$user) {
        return false;
    }

    return PermissionService::isSuperadmin((int)$user['id']);
}
