<?php

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

use ones\oidc\OnesOidc;

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

if (!$loginHint || !$resourceUri) {
    die("Error: OIDC_LOGIN_HINT and OIDC_RESOURCE_URI environment variables 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']);

    // Test CIBA authentication
    $result = $oidc->user_ciba_auth(
        $loginHint,
        $deviceProps['clientId'],
        $deviceProps['privateKey'],
        $openidInfo['providerMetadata'],
        $openidInfo['providerJwks'],
        $resourceUri,
        "Please authorize this request",
        "openid profile"
    );

    // Print result
    echo "CIBA Authentication Result:\n";
    echo json_encode($result, JSON_PRETTY_PRINT) . "\n";

    // Test consent flow
    $consentSettings = [
        'ones_auth_consent_content_first_name' => true,
        'ones_auth_consent_content_last_name' => true,
        'ones_auth_consent_content_email' => true,
        'ones_auth_consent_content_phone_number ' => true
    ];

    $consentReason = 'Requesting access';

    $consentResult = $oidc->user_consent_flow(
        $result['access_token_content']['sub'],
        $deviceProps['clientId'],
        $deviceProps['privateKey'],
        $openidInfo['providerMetadata'],
        $resourceUri,
        $deviceProps['host'],
        $consentSettings,
        $consentReason
    );

    // Print consent flow result
    echo "\nConsent Flow Result:\n";
    echo json_encode($consentResult, JSON_PRETTY_PRINT) . "\n";

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

?>