<?php

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

function generateTokenX(): bool|string
{
    $visaUrlSecurity = config('visa.payment.VISA_URL_SECURITY');
    $visaUser = config('visa.payment.VISA_USER');
    $visaPwd = config('visa.payment.VISA_PWD');

    $client = Http::withoutVerifying()->timeout(10)->withHeaders([
        'Accept' => '*/*',
        'Authorization' => 'Basic '.base64_encode($visaUser.':'.$visaPwd)
    ]);

    try {
        $response = $client->post($visaUrlSecurity);

        return $response->body();
    } catch (ConnectionException $exception) {
        Log::error($exception->getMessage());
        return false;
    }
}

function generateSesion($amount, $token, $recibo_)
{
    $session = [
        'amount' => $amount,
        'antifraud' => [
            'clientIp' => $_SERVER['REMOTE_ADDR'],
            'merchantDefineData' => [
                'MDD4' => "mail@domain.com",
                'MDD30' => $recibo_,
                'MDD33' => "DNI",
                'MDD34' => ""
            ],
        ],
        'channel' => 'web',
    ];

    $json = json_encode($session);
    $visaUrlSession = config('visa.payment.VISA_URL_SESSION');
    $response = json_decode(postRequest($visaUrlSession, $json, $token));

    return $response->sessionKey;
    //'87654321'
}

function generateAuthorization($amount, $purchaseNumber, $transactionToken, $token)
{
    $data = [
        'antifraud' => null,
        'captureType' => 'manual',
        'channel' => 'web',
        'countable' => true,
        'order' => [
            'amount' => $amount,
            'currency' => 'PEN',
            'purchaseNumber' => $purchaseNumber,
            'tokenId' => $transactionToken
        ],
        'recurrence' => null,
        'sponsored' => null
    ];

    $json = json_encode($data);
    $visaUrlAuthorization = config('visa.payment.VISA_URL_AUTHORIZATION');

    return json_decode(postRequest($visaUrlAuthorization, $json, $token));
}

function postRequest($url, $postData, $token): bool|string
{
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => [
            'Authorization: '.$token,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => $postData
    ]);
    $response = curl_exec($curl);
    curl_close($curl);

    return $response;
}

/*
function generatePurchaseNumber()
{
    $archivo = "assets/purchaseNumber.txt";
    $purchaseNumber = 222;
    $fp = fopen($archivo,"r");
    $purchaseNumber = fgets($fp, 100);
    fclose($fp);
    ++$purchaseNumber;
    $fp = fopen($archivo,"w+");
    fwrite($fp, $purchaseNumber, 100);
    fclose($fp);

    return $purchaseNumber;
}
*/
