<?php
/**
 * perms.php – role/permission helpers.
 *
 * Roles:
 *   super_admin  – global owner; everything across all facilities
 *   coordinator  – per-facility manager; CRUD within facility
 *   examiner     – grader; read-only candidates, edits own attempts
 *   facility     – legacy alias for examiner (kept for v1 users)
 */

function perms_role(array $user): string
{
    // Legacy 'facility' rows behave as 'examiner'
    return $user['role'] === 'facility' ? 'examiner' : (string)$user['role'];
}

function perms_is_super(?array $user): bool       { return $user && perms_role($user) === 'super_admin'; }
function perms_is_coordinator(?array $user): bool { return $user && perms_role($user) === 'coordinator'; }
function perms_is_examiner(?array $user): bool    { return $user && perms_role($user) === 'examiner'; }

// Mid-level: any user who can manage things inside a facility
function perms_can_manage(?array $user): bool
{
    return $user && in_array(perms_role($user), ['super_admin','coordinator'], true);
}

// Capabilities -------------------------------------------------------------

function perms_can_view_candidates(?array $user): bool         { return $user !== null; }
function perms_can_manage_candidates(?array $user): bool       { return perms_can_manage($user); }
function perms_can_import_candidates(?array $user): bool       { return perms_can_manage($user); }
function perms_can_export_candidates(?array $user): bool       { return perms_can_manage($user); }

function perms_can_manage_forms(?array $user): bool            { return perms_can_manage($user); }
function perms_can_manage_exams(?array $user): bool            { return perms_can_manage($user); }
function perms_can_manage_assignments(?array $user): bool      { return perms_can_manage($user); }
function perms_can_run_round(?array $user): bool               { return perms_can_manage($user); }

function perms_can_view_live_dashboard(?array $user): bool     { return perms_can_manage($user); }
function perms_can_view_analytics(?array $user): bool          { return perms_can_manage($user); }

function perms_can_manage_users(?array $user): bool            { return perms_can_manage($user); }
function perms_can_manage_facilities(?array $user): bool       { return perms_is_super($user); }
function perms_can_view_audit(?array $user): bool              { return perms_can_manage($user); }
function perms_can_delete_attempts(?array $user): bool         { return perms_is_super($user); }
function perms_can_delete_candidates(?array $user): bool       { return perms_is_super($user); }
function perms_can_delete_forms(?array $user): bool            { return perms_can_manage($user); }
function perms_can_delete_exams(?array $user): bool            { return perms_can_manage($user); }

/**
 * Returns ['WHERE fragment', [params]] to scope a query to the user's facility.
 * Pass the column name that contains facility_id, e.g. 'c.facility_id'.
 *
 *   [$where, $params] = perms_facility_scope($user, 'c.facility_id');
 *   if ($where) $sql .= " AND $where";
 *
 * Super admins see everything (empty fragment).
 */
function perms_facility_scope(?array $user, string $col): array
{
    if (!$user) return ['1=0', []];
    if (perms_is_super($user)) return ['', []];
    if (empty($user['facility_id'])) return ['1=0', []];
    return ["$col = ?", [(int)$user['facility_id']]];
}

/**
 * Check whether the user may operate on this facility-scoped entity.
 *
 *   if (!perms_owns_facility($user, $row['facility_id'])) abort 403;
 */
function perms_owns_facility(?array $user, $facilityId): bool
{
    if (!$user) return false;
    if (perms_is_super($user)) return true;
    if ($facilityId === null) return false;   // global rows are super-only
    return (int)$user['facility_id'] === (int)$facilityId;
}

/** For the user role <select> dropdown. */
function perms_role_options(bool $includeLegacy = false): array
{
    $r = [
        'super_admin' => 'Super Admin',
        'coordinator' => 'Coordinator',
        'examiner'    => 'Examiner',
    ];
    if ($includeLegacy) $r['facility'] = 'Facility (legacy)';
    return $r;
}

/** What roles can a given user CREATE? */
function perms_creatable_roles(array $user): array
{
    if (perms_is_super($user)) return perms_role_options();
    if (perms_is_coordinator($user)) {
        return ['examiner' => 'Examiner']; // coordinators may only add examiners
    }
    return [];
}

function perms_require_super(): void
{
    require_login();
    if (!perms_is_super(current_user())) { http_response_code(403); echo 'Forbidden'; exit; }
}

function perms_require(string $capability): void
{
    require_login();
    $fn = 'perms_can_' . $capability;
    if (!function_exists($fn) || !$fn(current_user())) {
        http_response_code(403);
        echo 'Forbidden';
        exit;
    }
}
