<?php

namespace App\Http\Controllers;

use App\Models\OnlinePaymentGetwayToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OnlinePaymentGetwayTokenController extends Controller
{
    private $base_url;
    private $app_key;
    private $app_secret;
    private $username;
    private $password;
    private $error;
    private $payerReference;
    private $callbackurl;


    public function __construct()
    {
        $this->app_key          = config('app.bkash_app_key');
        $this->app_secret       = config('app.bkash_app_secret');
        $this->username         = config('app.bkash_username');
        $this->password         = config('app.bkash_password');
        $this->base_url         = config('app.bksh_base_url');
        $this->payerReference   = config('app.bkash_payerReference');
        if (url('/') == 'http://radius-circle.test') {
            $this->callbackurl      = 'https://demo.yetfix.net/admin/bkashResellerCallback';
        } else {
            $this->callbackurl      = url('/') . '/admin/bkashResellerCallback';
        }

        for ($i = 2001; $i <= 2069; $i++) {
            $this->error[] = $i;
        }

    }
    public function storeToken()
    {
        Log::error('Bkash Token Generate');
        $post_token = array(
            'app_key' => $this->app_key,
            'app_secret' => $this->app_secret
        );



        $post_token = json_encode($post_token);
        $header = array(
            "Accept: application/json",
            'Content-Type:application/json',
            "password:$this->password",
            "username:$this->username"
        );

        if($this->app_key == null || $this->app_secret == null || $this->username == null || $this->password == null){
            return;
        }

        $url = curl_init("$this->base_url/tokenized/checkout/token/grant");

        curl_setopt($url, CURLOPT_HTTPHEADER, $header);
        curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($url, CURLOPT_ENCODING, "");
        curl_setopt($url, CURLOPT_MAXREDIRS, 10);
        curl_setopt($url, CURLOPT_TIMEOUT, 30);
        curl_setopt($url, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($url, CURLOPT_POSTFIELDS, $post_token);
        curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
        $resultdata = curl_exec($url);
        curl_close($url);

        Log::error('Bkash Token Generate Response: '.$resultdata);

        $response = json_decode($resultdata, true);


        OnlinePaymentGetwayToken::updateOrCreate(
            ['payment_gateway' => 'bkash'],
            ['token' => $response['id_token']]
        );
    }
}
