<?php

namespace App\Services;

use DateTime;
use GuzzleHttp\Client;
use App\Models\ClientSecretKeyModel;

class JSpaymentService
{
    private $clientId;
    private $organizationId;
    private $jsPublicKey;

    public function __construct()
    {
        // Loading JS API credentials .env file
        $this->clientId = getenv('JS_CLIENT_ID');
        $this->organizationId = getenv('JS_ORGANIZATION_ID');
        $this->jsPublicKey = getenv('JSBL_PUBLIC_KEY_RSA');
    }


    public function debitInquirys($input)
    {
        $JsApiUrl = "https://z-sandbox.jsbl.com/zconnect/api/v2/debitinquiry2-blb2";

        $requestData = [
            "DebitInqRequest" => [
                "processingCode" => 'DebitInquiry',
                "merchantType" => $input['merchantType'],
                "traceNo" =>      $input['traceNo'],
                "companyName" => $input['companyName'],
                "dateTime" =>  date('YmdHis'),
                "mobileNo" => $input['mobileNo'],
                "channelId" => $input['channelId'],
                "terminalId" => $input['terminalId'],
                "productId" => $input['productId'],
                "pinType" => $input['pinType'],
                "transactionAmount" =>  $input['transactionAmount'],
                "reserved1" => $input['reserved1'],
                "reserved2" => "",
                "reserved3" => "",
                "reserved4" => "",
                "reserved5" => "",
                "reserved6" => "",
                "reserved7" => "",
                "reserved8" => "",
                "reserved9" => "",
                "reserved10" => ""
            ],
        ];

        $curlOptions = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'clientId' => $this->clientId,
                'clientSecret' => $this->getAccessToken(),
                'organizationId' => $this->organizationId,
            ],
            'json' => $requestData,
            'verify' => false,
        ];


        $client = new Client([
            'verify' => false,
        ]);
        $response = $client->post($JsApiUrl, $curlOptions);

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

        return $responseData;
    }


    public function debitPayments($input, $package)
    {
        $JsApiUrl = "https://z-sandbox.jsbl.com/zconnect/api/v2/debitpayment-blb2";

        $requestData = [
            "DebitPaymentRequest" => [
                "processingCode" => 'DebitPayment',
                "merchantType" => $input['merchantType'],
                "traceNo" =>      $input['traceNo'],
                "companyName" => $input['companyName'],
                "dateTime" =>  date('YmdHis'),
                "mobileNo" => $input['mobileNo'],
                "channelId" => $input['channelId'],
                "terminalId" => $input['terminalId'],
                "productId" => $input['productId'],
                "otpPin" => RSAencryption($input['otpPin'], $this->jsPublicKey),
                "pinType" => $input['pinType'],
                "transactionAmount" =>  $package['Price'],
                "reserved1" => $input['reserved1'],
                "reserved2" => "",
                "reserved3" => "",
                "reserved4" => "",
                "reserved5" => "",
                "reserved6" => "",
                "reserved7" => "",
                "reserved8" => "",
                "reserved9" => "",
                "reserved10" => ""
            ],
        ];

        $curlOptions = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'clientId' => $this->clientId,
                'clientSecret' => $this->getAccessToken(),
                'organizationId' => $this->organizationId,
            ],
            'json' => $requestData,
            'verify' => false,
        ];


        $client = new Client([
            'verify' => false,
        ]);
        $response = $client->post($JsApiUrl, $curlOptions);

        $responseData = json_decode($response->getBody(), true);
        return $responseData;
    }

    private function getAccessToken()
    {
        $currentTime = new DateTime();
        $clientSecretKeyModel = new ClientSecretKeyModel();
        $result = $clientSecretKeyModel->select('*')->first();

        $updatedTimestamp = new DateTime($result['Updated_timestamp']);
        $interval = $currentTime->diff($updatedTimestamp);
        if ($interval->h < 12 && $interval->days == 0) {
            return $result['Client_Secret_key'];
        } else {
            $reset = $this->resetSecret();
            $skey = $reset['clientSecret'];
            $data = [
                'Client_Secret_key' => $skey,
                'Updated_timestamp' =>  $currentTime->format('Y-m-d H:i:s'),
            ];
            $clientSecretKeyModel->update($result['Id'], $data);
            return $skey;
        }
    }


    public function resetSecret()
    {
        $authApiUrl = "https://z-sandbox.jsbl.com/zconnect/client/reset-oauth-blb";

        $client = new Client([
            'verify' => false,
        ]);
        $response = $client->post($authApiUrl, [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'clientSecertId' => $this->clientId,
            ],
            'json' => [
                'clientSecretId' => $this->clientId,
            ],
        ]);

        $responseData = json_decode($response->getBody(), true);
        if (isset($responseData['responseCode']) && $responseData['responseCode'] === '0000') {
            return $responseData['payLoad'];
        } else {
            return null;
        }
    }
    
    // public function intiatePyament()
    // {
    //     $accessToken = $this->getAccessToken($this->clientId);
    //     $JsApiUrl = "https://z-sandbox.jsbl.com/zconnect/api/v2/w2wp-blb";

    //     $requestData = [
    //         "w2wpRequest" => [
    //             "MerchantType" => '0088', //$input['merchant_type'],
    //             "TraceNo" =>      '000014', //$input['trace_no'],
    //             "CompanyName" => 'NOVA', //$input['company_name'],
    //             "DateTime" =>  '20170706121213', // $input['date_time'],
    //             "TerminalId" => 'NOVA', // $input['terminal_id'],
    //             "ReceiverMobileNumber" =>  '03320354357', // $input['receiver_mobile_number'],
    //             "MobileNo" => '03320354357', //$input['sender_mobile_no'],
    //             "Amount" =>  '2', // $input['amount'],
    //             "Reserved1" => '01', // $input['reserved1'],
    //             "OtpPin" => '01', // $input['otp_pin'],
    //         ],
    //     ];

    //     $curlOptions = [
    //         'headers' => [
    //             'Content-Type' => 'application/json',
    //             'Accept' => 'application/json',
    //             'clientId' => $this->clientId,
    //             'clientSecret' => $accessToken['clientSecret'],
    //             'organizationId' => $this->organizationId,
    //         ],
    //         'json' => $requestData,
    //         'verify' => false,
    //     ];


    //     $client = new Client([
    //         'verify' => false,
    //     ]);
    //     $response = $client->post($JsApiUrl, $curlOptions);

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

    //     if (isset($responseData['code']) && $responseData['code'] === 1001) {
    //         echo 'Unlicensed JS Id';
    //         exit;
    //     }

    //     print_r($responseData);
    //     exit;
    //     return $responseData;
    // }


    // This would be used for getting first time client secret and organization 

    // private function getAccessToken()
    // {
    //     // Make a call to the oauth-blb API to obtain the access token
    //     $authApiUrl = "https://z-sandbox.jsbl.com/zconnect/client/oauth-blb";

    //     $client = new Client([
    //         'verify' => false,
    //     ]);
    //     $response = $client->get($authApiUrl, [
    //         'headers' => [
    //             'Content-Type' => 'application/json',
    //             'Accept' => 'application/json',
    //             'clientId' => $this->clientId,
    //         ],
    //     ]);

    //     $responseData = json_decode($response->getBody(), true);
    //     if (isset($responseData['responseCode']) && $responseData['responseCode'] === '0000') {
    //         return $responseData['payLoad'];
    //     } else {
    //         return null;
    //     }
    // }

    public function accountVerification($input)
    {
        $JsApiUrl = "https://z-sandbox.jsbl.com/zconnect/api/v2/verifyacclinkacc-blb";

        $requestData = [
            "VerifyAccLinkAccRequest" => [
                "MerchantType" => '0088',
                "TraceNo" =>      '000009',
                "CNIC" => $input['CNIC'],
                "MobileNo" => $input['MobileNo'],
                "DateTime" =>  date('YmdHis'),
                "CompanyName" => 'WebDoc',
                "Reserved1" =>  '01',
                "Reserved2" =>  '01',
                "TransactionType" => '02',
            ],
        ];

        $curlOptions = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'clientId' => $this->clientId,
                'clientSecret' => $this->getAccessToken(),
                'organizationId' => $this->organizationId,
            ],
            'json' => $requestData,
        ];


        $client = new Client([
            'verify' => false,
        ]);
        $response = $client->post($JsApiUrl, $curlOptions);
        $responseData = json_decode($response->getBody(), true);
        return $responseData;
    }
}
