<?php

namespace App\Services;

class SumsubService
{
    private string $appToken = 'prd:cNTsxsJYqEMfof01XgQQ56sC.RSQDPZvc5iXqsGywJq4NpLLjnpi4FlJU';
    private string $secretKey = 'TRTrROzbMQa8rlVmFmOLkokRHZCkNCKo';
    private string $apiUrl = 'https://api.sumsub.com/resources/accessTokens/sdk';

    public function getAccessToken(string $userId, string $levelName, ?string $email = '', ?string $phone = '', ?string $externalActionId = ''): array
    {
        $body = [
            'ttlInSecs' => 600,
            'userId' => $userId,
            'levelName' => $levelName,
            'applicantIdentifiers' => [
                'email' => $email ?? '',
                'phone' => $phone ?? ''
            ],
            'externalActionId' => $externalActionId ?? ''
        ];

        $jsonBody = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $ts = time();
        $signatureString = $ts . $jsonBody;
        $signature = hash_hmac('sha256', $signatureString, $this->secretKey);

        $headers = [
            "X-App-Token: {$this->appToken}",
            "Content-Type: application/json"
        ];

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $jsonBody,
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            return ['status' => 'error', 'message' => $err];
        } else {
            return ['status' => 'success', 'data' => json_decode($response, true)];
        }
    }
}
