<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Session;

class VeriffController extends Controller
{
    public function upload(){
        return view('veriff.uploadPage');
    }
    public function createSession()
    {
        // Initialize HTTP Client
        $client = new Client();
        $url = env('VERIFF_API_URL') . '/sessions';
        $apiKey = env('VERIFF_API_KEY');
        $kboData = Session::get('api-data');
        if(!$kboData){
            return redirect()->route('veriff.error_page');
        }
        try {
            // Create Veriff session
            $response = $client->post($url, [
                'headers' => [
                    'X-AUTH-CLIENT' => $apiKey,
                    'Content-Type' => 'application/json',
                ],
                'json' => [
                    'verification'=> [
                        // 'callback' => route('pdfs'),
                        "person" => [
                            'firstName' => $kboData['function'][0]['person']['surname'],
                            'lastName' => $kboData['function'][0]['person']['givenName'],
                            "idNumber" => '',                        ]
                    ]
                ]
            ]);

            $sessionData = json_decode($response->getBody(), true);

            // Get session ID and URL
            $sessionId = $sessionData['verification']['id'];
            $verificationUrl = $sessionData['verification']['url'];
            Session::put('veriff_active_session',$sessionId);
            return redirect()->away($verificationUrl);
            // return response()->json([
            //     'session_id' => $sessionId,
            //     'verification_url' => $verificationUrl,
            // ]);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
        }
    }

    public function getSessionStatus($sessionId)
    {
        $client = new Client();
        $url = env('VERIFF_API_URL') . "/sessions/{$sessionId}";
        $apiKey = env('VERIFF_API_KEY');

        try {
            $response = $client->get($url, [
                'headers' => [
                    'X-AUTH-CLIENT' => $apiKey,
                    'Content-Type' => 'application/json',
                ],
            ]);

            $sessionStatus = json_decode($response->getBody(), true);

            return response()->json($sessionStatus);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
        }
    }
    public function getPersonData($sessionId){
        $client = new Client();
        $url = env('VERIFF_API_URL') . "/sessions/{$sessionId}/person";
        $apiKey = env('VERIFF_API_KEY');
        $secretKey = env('VERIFF_SECRET_KEY');
        $hmacSignature = hash_hmac('sha256', $sessionId, $secretKey);

        try {
            $response = $client->get($url, [
                'headers' => [
                    'X-AUTH-CLIENT' => $apiKey,
                    'Content-Type' => 'application/json',
                    'X-HMAC-SIGNATURE' => $hmacSignature
                ],
            ]);

            $sessionStatus = json_decode($response->getBody(), true);

            return response()->json($sessionStatus);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
        }
    }
    public function handleCallback()
    {
        $sessionId =  Session::get('veriff_active_session');
        // $sessionId =  '9ae6257d-4e53-4920-89a9-a1c50f586dd9';
        if($sessionId){
            $decision = json_decode($this->getDecision($sessionId)->getContent());
            if($decision->verification->status === 'approved'){
                $kboData = Session::get('api-data');
                if(strtolower($kboData['function'][0]['person']['givenName']) == strtolower($decision->verification->person->firstName) && strtolower($kboData['function'][0]['person']['surname']) == strtolower($decision->verification->person->lastName)){
                    Session::put('veriff_active_person',$decision);
                    return redirect()->route('pdfs');
                }else{
                    return redirect()->route('veriff.error_page')->with("error" , "We have an error please try later");
                    // return response()->json(['givenName' => strtolower($kboData['function'][0]['person']['givenName']),'firstName' => strtolower($decision->verification->person->firstName)], 500);
                }
            }
        return redirect()->route('veriff.error_page')->with('error' , "Oops! It looks like we couldn't verify your ID. This might be due to a blurry photo, incorrect details, or an unsupported ID type. No worries—please double-check your document and try again. If you need help, feel free to reach out to our support team!");
        }
        return redirect()->route('veriff.error_page')->with("error" , "We have an error can you try later");
    }
    public function getDecision($sessionId){
        $client = new Client();
        $url = env('VERIFF_API_URL') . "/sessions/{$sessionId}/decision";
        $apiKey = env('VERIFF_API_KEY');
        $secretKey = env('VERIFF_SECRET_KEY');
        $hmacSignature = hash_hmac('sha256', $sessionId, $secretKey);

        try {
            $response = $client->get($url, [
                'headers' => [
                    'X-AUTH-CLIENT' => $apiKey,
                    'Content-Type' => 'application/json',
                    'X-HMAC-SIGNATURE' => $hmacSignature
                ],
            ]);

            $sessionStatus = json_decode($response->getBody(), true);

            return response()->json($sessionStatus);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
        }
    }
    // route for display not found page 
    public function notFoundPage(){
        return view('veriff.not_found');
    }
    // route for display verification declined page 
    public function veriffDeclinedPage(){
        return view('veriff.verification_declined');
    }
    public function errorPage(){
        return view('veriff.error_page');
    }
    public function getPersonMedia($sessionId){
        $client = new Client();
        $url = env('VERIFF_API_URL') . "/sessions/{$sessionId}/media";
        $apiKey = env('VERIFF_API_KEY');
        $secretKey = env('VERIFF_SECRET_KEY');
        $hmacSignature = hash_hmac('sha256', $sessionId, $secretKey);
    
        try {
            $response = $client->get($url, [
                'headers' => [
                    'X-AUTH-CLIENT' => $apiKey,
                    'Content-Type' => 'application/json',
                    'X-HMAC-SIGNATURE' => $hmacSignature
                ],
            ]);
    
            $sessionStatus = json_decode($response->getBody(), true);
            return response()->json($sessionStatus);
            // $this->getMediaContent($sessionStatus['images'][0]['id']);
            
    
        } catch (\Exception $e) {
            return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
        }
    }


    public function getMediaContent($mediaId)
{
    $client = new Client();
    $url = env('VERIFF_API_URL') . "/media/{$mediaId}";
    $apiKey = env('VERIFF_API_KEY');
    $secretKey = env('VERIFF_SECRET_KEY');
    $hmacSignature = hash_hmac('sha256', $mediaId, $secretKey);

    try {
        $response = $client->get($url, [
            'headers' => [
                'X-AUTH-CLIENT' => $apiKey,
                'X-HMAC-SIGNATURE' => $hmacSignature,
            ],
        ]);

        return response($response->getBody(), 200)
            ->header('Content-Type', $response->getHeader('Content-Type')[0]);

    } catch (\Exception $e) {
        return response()->json(['error' => 'Veriff API error: ' . $e->getMessage()], 500);
    }
}

}



