<?php
class Team {

    public $ID;
    public $NAME;

    public static function findAll($clientEndpoint, $accessToken, $cacheDurationInSeconds = 21600): array
{
    $cacheFile = __DIR__ . '/cache/bitrix_users_' . md5($clientEndpoint . $accessToken) . '.json';

    // Load from cache if valid
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheDurationInSeconds) {
        $json = file_get_contents($cacheFile);
        $cachedData = json_decode($json, true);

        if (json_last_error() === JSON_ERROR_NONE && is_array($cachedData)) {
            $users = [];
            foreach ($cachedData as $item) {
                if (!isset($item['NAME']) || trim($item['NAME']) === '') {
                    continue;
                }

                $user = new static;
                $user->ID = $item['ID'] ?? null;
                $user->NAME = $item['NAME'];
                $users[] = $user;
            }

            if (count($users) > 0) {
                return $users;
            }
        }
        // Delete corrupted or blank cache
        @unlink($cacheFile);
    }

    // Fetch fresh data
    $users = [];
    $start = 0;

    $baseUrl = $clientEndpoint . 'user.get.json?auth=' . $accessToken .
        '&FILTER[ACTIVE]=true' .
        '&SELECT[]=ID&SELECT[]=NAME';

    do {
        $url = $baseUrl . '&start=' . $start;
        $response = @file_get_contents($url);
        $data = json_decode($response, true);

        if (isset($data['result'])) {
            foreach ($data['result'] as $userData) {
                if (!isset($userData['NAME']) || trim($userData['NAME']) === '') {
                    continue;
                }

                $user = new static;
                $user->ID = $userData['ID'] ?? null;
                $user->NAME = $userData['NAME'];
                $users[] = $user;
            }
            $start = $data['next'] ?? null;
        } else {
            break;
        }
    } while ($start !== null);

    // Cache the result if not empty
    if (!empty($users)) {
        $dataToCache = array_map(function ($user) {
            return ['ID' => $user->ID, 'NAME' => $user->NAME];
        }, $users);

        // Ensure cache directory exists
        $cacheDir = dirname($cacheFile);
        if (!is_dir($cacheDir)) {
            mkdir($cacheDir, 0775, true);
        }

        $tempFile = $cacheFile . '.' . uniqid('tmp_', true);
        file_put_contents($tempFile, json_encode($dataToCache, JSON_PRETTY_PRINT));
        rename($tempFile, $cacheFile);
    }

    return $users;
}

}
