<?php

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

namespace ones\oidc;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Exception;

/**
 * Make a consent request
 * 
 * @param string $userId
 * @param string $resourceUri
 * @param string $host
 * @param string $deviceAccessToken
 * @param array {
 *   ones_auth_consent_content_first_name: bool,
 *   ones_auth_consent_content_last_name: bool,
 *   ones_auth_consent_content_date_of_birth: bool,
 *   ones_auth_consent_content_localized_first_name: bool,
 *   ones_auth_consent_content_localized_last_name: bool,
 *   ones_auth_consent_content_identity_document_number: bool,
 *   ones_auth_consent_content_email: bool,
 *   ones_auth_consent_content_phone_number: bool
 * }
 * @return array{
 *     id: string
 * }
 * @throws Exception if the request fails
 */
function make_consent_request(
    string $userId,
    string $resourceUri,
    string $host,
    string $deviceAccessToken,
    array $consentSettings,
    string $consentReason
) {

    $content = [];
    $fieldMap = [
        'ones_auth_consent_content_first_name' => 'firstName',
        'ones_auth_consent_content_last_name' => 'lastName',
        'ones_auth_consent_content_localized_first_name' => 'localizedFirstName',
        'ones_auth_consent_content_localized_last_name' => 'localizedLastName',
        'ones_auth_consent_content_identity_document_number' => 'identityDocumentNumber',
        'ones_auth_consent_content_identity_document_issue_date' => 'identityDocumentIssueDate',
        'ones_auth_consent_content_identity_document_expiry_date' => 'identityDocumentExpiryDate',
        'ones_auth_consent_content_date_of_birth' => 'dateOfBirth',
        'ones_auth_consent_content_email' => 'email',
        'ones_auth_consent_content_phone_number' => 'phoneNumber',
    ];

    foreach ($fieldMap as $settingKey => $apiField) {
        if (isset($consentSettings[$settingKey]) && $consentSettings[$settingKey] === true) {
            $content[] = ['name' => $apiField];
        }
    }

    $consentPayload = [
        'reason' => $consentReason,
        'resource' => $resourceUri,
        'userId' => $userId,
        'content' => $content
    ];

    $client = new Client();
    $url = $host . '/consent';

    try {
        $response = $client->request('POST', $url, [
            'json' => $consentPayload,
            'headers' => [
                'Authorization' => 'Bearer ' . $deviceAccessToken,
            ],
            'timeout' => 3,
        ]);
        $body = json_decode($response->getBody(), true);
        return [
            'id' => $body['id'],
        ];
    } catch (RequestException $e) {
        // Handle the exception or rethrow it
        throw new Exception('Failed to make consent request: ' . $e->getMessage());
    }
}

function make_consent_status_request(
    string $consentRequestId,
    string $host,
    string $deviceAccessToken
) {
    $url = $host . '/consent/' . $consentRequestId . '/status';

    $client = new Client();
    $response = $client->request('GET', $url, [
        'headers' => [
            'Authorization' => 'Bearer ' . $deviceAccessToken,
        ],
        'timeout' => 3,
    ]);
    $body = json_decode($response->getBody(), true);

    return [
        'status' => $body['status'],
        'content' => $body['content'] ?? null
    ];
}