<?php

/**
 * This program is copyrighted by Franz Geffke (Softmax Co., Ltd.)
 */

namespace ones\oidc;
use Exception;
use GuzzleHttp;

/**
 * Make QR auth session
 * 
 * @param string $host The host URL
 * @param string $deviceAccessToken The device access token
 * 
 * @return array(
 *  'kind' => string,
 *  'sessionId' => string,
 *  'cbUrl' => string,
 *  'expIn' => int,
 *  'exp' => int,
 *  'interval' => int,
 *  'aud' => string,
 *  'authRequestId' => string,
 *  'cibaRequestInvoked' => bool,
 * )
 */
function make_qr_auth_session_request($host, $deviceAccessToken) {
    try {
        $client = new GuzzleHttp\Client();
        $response = $client->post($host . '/oidc/qr/make', [
            'headers' => [
                'Authorization' => 'Bearer ' . $deviceAccessToken,
                'Content-Type' => 'application/json'
            ],
            'timeout' => 3
        ]);

        return json_decode($response->getBody(), true);
    } catch (Exception $e) {
        throw new Exception("Error making QR auth session: " . $e->getMessage());
    }
}

/**
 * Verify QR auth session
 * 
 * @param string $host The host URL
 * @param string $sessionId The session ID
 * @param string $deviceAccessToken The device access token
 * 
 * @return array(
 *  'kind' => string,
 *  'sessionId' => string,
 *  'cbUrl' => string,
 *  'expIn' => int,
 *  'exp' => int,
 *  'interval' => int,
 *  'aud' => string,
 *  'authRequestId' => string,
 *  'cibaRequestInvoked' => bool,
 *  'loginHintToken' => string
 * )
 */
function verify_qr_auth_session($host, $sessionId, $deviceAccessToken) {
    try {
        $client = new GuzzleHttp\Client();
        $response = $client->post($host . '/oidc/qr/status', [
            'headers' => [
                'Authorization' => 'Bearer ' . $deviceAccessToken,
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'sessionId' => $sessionId
            ],
            'timeout' => 3
        ]);

        $result = json_decode($response->getBody(), true);
        return empty($result) ? null : $result;
    } catch (Exception $e) {
        throw new Exception("Error verifying QR auth session: " . $e->getMessage());
    }
}

?>