getConnection(); $schools = self::userSchools($pdo, $userId); // TEMPORANEO (fase monoscuola): utente senza scuola -> agganciato a Seregno if (empty($schools)) { $stmt = $pdo->prepare( "INSERT IGNORE INTO school_user (user_id, idschool, school_role) VALUES (?, ?, 'student')" ); $stmt->execute([$userId, self::DEFAULT_SCHOOL]); $schools = self::userSchools($pdo, $userId); } if (empty($schools)) { http_response_code(403); die('Nessuna scuola attiva associata a questo account.'); } // Scuola richiesta in sessione: accettata solo se l'utente ne fa parte $requested = isset($_SESSION['idschool']) ? (int) $_SESSION['idschool'] : 0; $selected = $schools[0]; foreach ($schools as $row) { if ((int) $row['idschool'] === $requested) { $selected = $row; break; } } $selected['idschool'] = (int) $selected['idschool']; $_SESSION['idschool'] = $selected['idschool']; self::$school = $selected; return self::$school; } /** ID della scuola corrente */ public static function id(): int { if (self::$school === null) { throw new RuntimeException('SchoolContext::resolve() non ancora chiamato'); } return self::$school['idschool']; } /** Dati completi della scuola corrente */ public static function get(): array { if (self::$school === null) { throw new RuntimeException('SchoolContext::resolve() non ancora chiamato'); } return self::$school; } /** Ruolo dell'utente nella scuola corrente: student|teacher|admin|owner */ public static function role(): string { return self::get()['school_role']; } /** Scuole attive a cui l'utente รจ iscritto */ private static function userSchools(PDO $pdo, int $userId): array { $stmt = $pdo->prepare( "SELECT s.*, su.school_role FROM school_user su JOIN schools s ON s.idschool = su.idschool WHERE su.user_id = ? AND su.active = 'Y' AND s.status <> 'suspended' ORDER BY su.idschool" ); $stmt->execute([$userId]); return $stmt->fetchAll(); } }