<?php
/**
 * STH NRMS — Scope Helper
 * File: include/scope_helper.php
 *
 * Provides ready-to-use SQL fragments and bind params for scoping
 * nurse and student queries to the current user's department or unit.
 *
 * USAGE — include at the top of any listing page after auth_guard.php:
 *
 *   require_once '../include/scope_helper.php';
 *
 * Then use any of the functions below when building queries.
 *
 * ─────────────────────────────────────────────────────────────────────
 * SCOPE RULES:
 *   Admin / Chief_Preceptor → no filter (all data)
 *   Preceptor               → filter by $_SESSION['department_id']
 *   Nurse_Manager           → filter by $_SESSION['department_id']
 *   In_Charge               → filter by $_SESSION['unit_ids'] (array)
 * ─────────────────────────────────────────────────────────────────────
 */

// ── scopeNurseWhere ───────────────────────────────────────────────────────────
/**
 * Returns a WHERE clause fragment that scopes rotation nurse queries.
 *
 * Joins through nurse_rotation_schedules which has both department_id
 * and unit_id. Pass the alias used in your query for that table.
 *
 * Example:
 *   $where = 'WHERE rn.status = "Active"';
 *   $scope = scopeNurseWhere('nrs');
 *   if ($scope['sql']) $where .= ' AND ' . $scope['sql'];
 *   // bind $scope['types'] and $scope['params'] in bind_param
 */
function scopeNurseWhere(string $alias = 'nrs'): array
{
    return _buildScope($alias, 'department_id', 'unit_id');
}

// ── scopeStudentWhere ─────────────────────────────────────────────────────────
/**
 * Returns a WHERE clause fragment that scopes clinical student queries.
 *
 * Joins through student_rotation_details which has unit_id and can be
 * joined to departments via units.department_id.
 *
 * For Preceptor / Nurse_Manager (department scope):
 *   Needs a JOIN to units:
 *     JOIN units u ON srd.unit_id = u.id
 *   Then filters on u.department_id.
 *
 * Pass $alias = alias for student_rotation_details,
 *      $unit_alias = alias for units table (needed for dept scope).
 */
function scopeStudentWhere(string $alias = 'srd', string $unit_alias = 'u'): array
{
    $usertype = $_SESSION['usertype'] ?? '';

    if (in_array($usertype, ['Admin', 'Chief_Preceptor'], true)) {
        return ['sql' => '', 'types' => '', 'params' => [], 'needs_unit_join' => false];
    }

    if (in_array($usertype, ['Preceptor', 'Nurse_Manager'], true)) {
        $dept_id = (int)($_SESSION['department_id'] ?? 0);
        if ($dept_id) {
            return [
                'sql'             => "{$unit_alias}.department_id = ?",
                'types'           => 'i',
                'params'          => [$dept_id],
                'needs_unit_join' => true,   // caller must JOIN units u ON srd.unit_id = u.id
            ];
        }
        return ['sql' => '1 = 0', 'types' => '', 'params' => [], 'needs_unit_join' => false];
    }

    if ($usertype === 'In_Charge') {
        $unit_ids = array_filter(array_map('intval', (array)($_SESSION['unit_ids'] ?? [])));
        if (!empty($unit_ids)) {
            $ph = implode(',', array_fill(0, count($unit_ids), '?'));
            return [
                'sql'             => "{$alias}.unit_id IN ({$ph})",
                'types'           => str_repeat('i', count($unit_ids)),
                'params'          => array_values($unit_ids),
                'needs_unit_join' => false,
            ];
        }
        return ['sql' => '1 = 0', 'types' => '', 'params' => [], 'needs_unit_join' => false];
    }

    return ['sql' => '1 = 0', 'types' => '', 'params' => [], 'needs_unit_join' => false];
}

// ── scopeNurseJoin ────────────────────────────────────────────────────────────
/**
 * Returns the JOIN clause needed to scope nurse queries.
 * For scoped roles, nurses must have at least one rotation block
 * in the user's department or unit.
 *
 * Include this in your query and then add scopeNurseWhere() to WHERE.
 *
 * Example full query:
 *   SELECT DISTINCT rn.*
 *   FROM rotation_nurses rn
 *   JOIN nurse_rotations nr ON nr.rotation_nurse_id = rn.id
 *   JOIN nurse_rotation_schedules nrs ON nrs.nurse_rotation_id = nr.id
 *   {scopeNurseJoin()} ← only adds something for scoped roles
 *   WHERE rn.status = 'Active'
 *   AND {scopeNurseWhere()['sql']}
 */
function scopeNurseJoin(): string
{
    $usertype = $_SESSION['usertype'] ?? '';
    if (in_array($usertype, ['Admin', 'Chief_Preceptor'], true)) return '';
    // For scoped roles the JOIN to nurse_rotation_schedules is required
    // (caller must already have this join; this function is informational)
    return '';
}

// ── scopeStudentJoin ──────────────────────────────────────────────────────────
/**
 * Returns JOIN clause(s) needed when scopeStudentWhere needs_unit_join = true.
 * Call after checking $scope['needs_unit_join'].
 *
 * Example:
 *   $scope = scopeStudentWhere('srd');
 *   $join  = $scope['needs_unit_join'] ? scopeStudentJoin('srd') : '';
 *   $sql   = "SELECT cs.* FROM clinical_students cs
 *             JOIN student_rotation_details srd ON srd.clinical_student_id = cs.id
 *             {$join}
 *             WHERE cs.status = 'Active'";
 *   if ($scope['sql']) $sql .= ' AND ' . $scope['sql'];
 */
function scopeStudentJoin(string $srd_alias = 'srd'): string
{
    return "JOIN units u ON {$srd_alias}.unit_id = u.id";
}

// ── getScopeLabel ─────────────────────────────────────────────────────────────
/**
 * Returns a human-readable scope description for display in the UI.
 * Example: "Department: Maternity Ward" or "Units: ICU, HDU"
 */
function getScopeLabel(): string
{
    $usertype = $_SESSION['usertype'] ?? '';
    if (in_array($usertype, ['Admin', 'Chief_Preceptor'], true)) return 'All Departments & Units';
    if (in_array($usertype, ['Preceptor', 'Nurse_Manager'], true)) {
        return 'Department: ' . htmlspecialchars($_SESSION['department_name'] ?? 'Unassigned');
    }
    if ($usertype === 'In_Charge') {
        $names = $_SESSION['unit_names'] ?? [];
        return 'Unit' . (count($names) > 1 ? 's' : '') . ': ' . implode(', ', array_map('htmlspecialchars', $names));
    }
    return '';
}

// ── isFullAccess ──────────────────────────────────────────────────────────────
function isFullAccess(): bool
{
    return in_array($_SESSION['usertype'] ?? '', ['Admin', 'Chief_Preceptor'], true);
}

// ── _buildScope (internal) ────────────────────────────────────────────────────
function _buildScope(string $alias, string $dept_col, string $unit_col): array
{
    $usertype = $_SESSION['usertype'] ?? '';

    if (in_array($usertype, ['Admin', 'Chief_Preceptor'], true)) {
        return ['sql' => '', 'types' => '', 'params' => []];
    }

    if (in_array($usertype, ['Preceptor', 'Nurse_Manager'], true)) {
        $dept_id = (int)($_SESSION['department_id'] ?? 0);
        if ($dept_id) {
            return ['sql' => "{$alias}.{$dept_col} = ?", 'types' => 'i', 'params' => [$dept_id]];
        }
        return ['sql' => '1 = 0', 'types' => '', 'params' => []];
    }

    if ($usertype === 'In_Charge') {
        $unit_ids = array_filter(array_map('intval', (array)($_SESSION['unit_ids'] ?? [])));
        if (!empty($unit_ids)) {
            $ph = implode(',', array_fill(0, count($unit_ids), '?'));
            return [
                'sql'    => "{$alias}.{$unit_col} IN ({$ph})",
                'types'  => str_repeat('i', count($unit_ids)),
                'params' => array_values($unit_ids),
            ];
        }
        return ['sql' => '1 = 0', 'types' => '', 'params' => []];
    }

    return ['sql' => '1 = 0', 'types' => '', 'params' => []];
}