<?php

declare(strict_types=1);

$root = dirname(__DIR__);

$targets = [
    'app/Models/UserModel.php',
    'app/Models/RoleModel.php',
    'app/Models/PermissionModel.php',
    'app/Models/RolePermissionModel.php',
    'app/Models/UserRoleModel.php',
    'app/Models/SettingsModel.php',
    'app/Models/ConfigurationModel.php',
    'app/Models/ParentModel.php',
    'app/Models/TeacherModel.php',
    'app/Models/StaffModel.php',
];

$patterns = [
    '/->where\(\s*[\'"][^\'"]*school_year[\'"]/',
    '/\b(users|roles|permissions|role_permissions|user_roles|configuration|settings|parents|teachers|staff)\.school_year\b/i',
];

$errors = [];

foreach ($targets as $relativePath) {
    $path = $root . DIRECTORY_SEPARATOR . $relativePath;

    if (! is_file($path)) {
        continue;
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES);

    foreach ($lines as $index => $line) {
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $line) === 1) {
                $errors[] = sprintf(
                    '%s:%d: suspicious school-year filter on a global/identity model: %s',
                    $relativePath,
                    $index + 1,
                    trim($line)
                );
            }
        }
    }
}

if ($errors !== []) {
    fwrite(STDERR, implode(PHP_EOL, $errors) . PHP_EOL);
    exit(1);
}

echo 'No suspicious global/identity school-year filters found.' . PHP_EOL;
