<?php

/**
 * Progress Analytics — access context resolution.
 *
 * Turns the current session into the role scoping that progress_query.php
 * enforces. Kept separate from the query library so the three front doors
 * (admin page, teacher portal, parent portal) can each build their own context
 * while sharing one query layer.
 *
 * The return contract:
 *   allowed_classes  ?string[]  NULL = unrestricted (admin-tier roles);
 *                               array = the ONLY classes this session may read.
 *   force_student_id ?int       when set, EVERY scope is pinned to this one
 *                               student regardless of the request (parent view).
 */

if (!function_exists('getDBConnection')) {
    require_once dirname(__DIR__, 2) . '/config.php';
}

/** Roles that see the whole school with no class restriction. */
const PROGRESS_UNRESTRICTED_ROLES = ['admin', 'headteacher', 'supervisor', 'director'];

/**
 * Resolve the admin-app access context from $_SESSION.
 *
 * A tutor reaching the admin endpoint is still confined to their assigned
 * classes — the restriction lives here, not only in the teacher portal, so no
 * entry point can bypass it.
 *
 * @return array{allowed_classes:?array, force_student_id:?int}
 */
function progressAccessContext(): array
{
    $role = $_SESSION['role'] ?? '';

    if (in_array($role, PROGRESS_UNRESTRICTED_ROLES, true)) {
        return ['allowed_classes' => null, 'force_student_id' => null];
    }

    if ($role === 'tutor') {
        $classes = $_SESSION['teacher_classes'] ?? [];
        $classes = is_array($classes)
            ? array_values(array_filter(array_map('strval', $classes), 'strlen'))
            : [];
        return ['allowed_classes' => $classes, 'force_student_id' => null];
    }

    // Any other role that slipped past the module role gate sees nothing.
    return ['allowed_classes' => [], 'force_student_id' => null];
}

/**
 * Merge an access context into raw request input, then normalise.
 * force_student_id (parent portal) overrides level+student and drops class
 * restrictions to that one child.
 */
function progressBuildScope(array $requestInput, array $context): array
{
    if (($context['force_student_id'] ?? null)) {
        $requestInput['level'] = 'student';
        $requestInput['student_id'] = (int) $context['force_student_id'];
        // A pinned student needs no class allow-list — the student id is the gate.
        return progressNormalizeScope($requestInput, null);
    }
    return progressNormalizeScope($requestInput, $context['allowed_classes']);
}
