<?php
final class SockChatAuth {
    public static function attempt(string $endPoint, string $secret, string $cookie): object {
        if(!empty($cookie)) {
            $decoded = str_pad(base64_decode(str_pad(strtr($cookie, '-_', '+/'), strlen($cookie) % 4, '=', STR_PAD_RIGHT)), 37, "\0");
            $unpacked = unpack('Cversion/Nuser/H*token', $decoded);

            if(isset($unpacked['version']) && $unpacked['version'] === 1
                && isset($unpacked['user']) && $unpacked['user'] > 0) {
                $loginRequest = [
                    'user_id' => $unpacked['user'],
                    'token' => 'SESS:' . $cookie,
                    'ip' => $_SERVER['REMOTE_ADDR'],
                ];
                $loginSignature = hash_hmac('sha256', implode('#', $loginRequest), $secret);

                $login = curl_init($endPoint);
                curl_setopt_array($login, [
                    CURLOPT_AUTOREFERER => false,
                    CURLOPT_FAILONERROR => false,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HEADER => false,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => json_encode($loginRequest),
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_TCP_FASTOPEN => true,
                    CURLOPT_CONNECTTIMEOUT => 2,
                    CURLOPT_MAXREDIRS => 2,
                    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
                    CURLOPT_TIMEOUT => 5,
                    CURLOPT_USERAGENT => 'AJAX Chat',
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json',
                        'X-SharpChat-Signature: ' . $loginSignature,
                    ],
                ]);
                $userInfo = json_decode(curl_exec($login));
                curl_close($login);
            }
        }

        if(empty($userInfo->success)) {
            $userInfo = new stdClass;
            $userInfo->success = false;
            $userInfo->user_id = 0;
            $userInfo->username = 'Anonymous';
            $userInfo->colour_raw = 0x40000000;
            $userInfo->rank = 0;
            $userInfo->hierarchy = 0;
            $userInfo->is_silenced = '1970-01-01T00:00:00+00:00';
            $userInfo->perms = 0;
        }

        return $userInfo;
    }
}
