<?php

require_once __DIR__ . '/../vendor/autoload.php';

use ones\oidc\OnesOidc;

// Check required environment variables
$resourceUri = getenv('OIDC_RESOURCE_URI');

if (!$resourceUri) {
    die("Error: OIDC_RESOURCE_URI environment variable must be set\n");
}

try {
    // Create an instance of OnesOidc
    $oidc = new OnesOidc();

    // Get device properties
    $deviceProps = $oidc->get_device_properties(
        '/etc/px-device-identity/device.yml',         // Update path as needed
        '/root/.local/share/px-device-identity/private.pem'     // Update path as needed
    );

    // Get OpenID configuration
    $openidInfo = $oidc->get_openid_info($deviceProps['host']);

    // Create QR auth session
    $qrSession = $oidc->make_qr_auth_session(
        $deviceProps['host'],
        $deviceProps['clientId'],
        $deviceProps['privateKey'],
        $openidInfo['providerMetadata'],
    );

    // Generate QR code
    echo "\nPlease scan the QR code using your mobile device.\n";
    echo "Session ID:   " . $qrSession['sessionId'] . "\n";
    echo "Callback URL: " . $qrSession['cbUrl'] . " \n\n";

    $authRequestId = null;

    // Poll QR auth session until completion or timeout
    echo "Polling QR Auth Session...\n";
    while (true) {
        $result = $oidc->poll_qr_auth_session(
            $qrSession['sessionId'],
            $deviceProps['clientId'],
            $deviceProps['privateKey'],
            $openidInfo['providerMetadata'],
            // $openidInfo['providerJwks'],
            $resourceUri,
            $deviceProps['host'],
            "Please authorize this request",
            "openid profile"
        );

        if ($result && isset($result['authRequestId'])) {
            $authRequestId = $result['authRequestId'];
            break;
        }

        sleep(3);
    }

    // Poll CIBA status
    echo "Polling CIBA Status with Auth Request ID: $authRequestId...\n";
    while (true) {
        $result = $oidc->check_ciba_status_loop(
            $openidInfo['providerMetadata'],
            $openidInfo['providerJwks'],
            $authRequestId,
            $deviceProps['clientId'],
            $deviceProps['privateKey']
        );

        // when access_token is set, break the loop
        if ($result && isset($result['access_token'])) {
            echo "CIBA Authentication Result:\n";
            break;
        }

        sleep(3);
    }

    exit(1);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}

?>