<?php

namespace App\Http\Controllers\OnlinePayment;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use App\Models\ResellerRechargeReport;
use App\Http\Controllers\Reseller\ResellerRechargeController;
use Illuminate\Support\Facades\Log;
use Cookie;

class BkashResellerController 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 generateToken()
    {
        session()->forget('bkash_token');

        $post_token = array(
            'app_key' => $this->app_key,
            'app_secret' => $this->app_secret
        );
        $url = curl_init("$this->base_url/tokenized/checkout/token/grant");

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

        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);

        $response = json_decode($resultdata, true);

        // dd($response);
        session()->put('bkash_token', $response['id_token']);

        return $response['id_token'];
    }



    public function createPayment(Request $request)
    {

        $token = getTokenForBkash();

        $re['intent'] = 'sale';
        $re['currency'] = 'BDT';
        $re['merchantInvoiceNumber'] = now()->timestamp . $request->reseller_id;
        $re['mode'] = "0011";
        $re['payerReference'] = $this->payerReference;
        $re['callbackURL'] = $this->callbackurl . "?merchantInvoiceNumber=" . $re['merchantInvoiceNumber'] . "&reseller_id=" . $request->reseller_id;
        $re['amount'] = $request->amount;


        // dd($re['callbackURL']);

        $url = curl_init("$this->base_url/tokenized/checkout/create");
        $request_data_json = json_encode($re);

        // dd($request_data_json);

        $header = array(
            'Content-Type:application/json',
            "authorization: $token",
            "x-app-key: $this->app_key"
        );

        curl_setopt($url, CURLOPT_HTTPHEADER, $header);
        curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
        curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        $resultdata = curl_exec($url);
        curl_close($url);

        $request->session()->put('reseller_id', $request->reseller_id);

        $decode_data = json_decode($resultdata, true);
        $decode_data["reseller_id"] =  $request->reseller_id;
        $decode_data["token"] =  $token;
        return  $decode_data;
    }

    public function bkashResellerCallback(Request $request, $status = 'error')
    {


        // dd($request->cookies->all(),$request->all());
        if ($request->paymentID == null || $request->status == 'cancel' || $request->status == 'failure') {
            Toastr::error('Recharge UnSuccessfull', 'Recharge Faild');
            return redirect()->route('onlineManagerRecharge', $request->reseller_id);
        }

        // dd($request->all());

        DB::beginTransaction();

        try {
            $recharge_report = ResellerRechargeReport::where('payment_gateway_transaction_id', $request->paymentID)->count();

            $reseller_id = $request->cookie('online_reseller_recharge_reseller_id');


            if ($request->status == 'success' && $recharge_report == 0 && $reseller_id == $request->reseller_id) {

                $result = $this->executePayment($request);

                if (in_array($result['statusCode'], $this->error)) {
                    Toastr::error($result['statusMessage'], 'Recharge Faild');
                    return redirect()->route('onlineManagerRecharge', $request->reseller_id);
                }

                if ($result['statusCode'] == 2062) {
                    $result = $this->queryPayment($request);
                }

                if ($result['transactionStatus'] == 'Completed') {
                    $status =   (new ResellerRechargeController)->recharge(
                        $request->reseller_id,
                        $result['amount'],
                        $result['paymentID'],
                        $result['trxID'],
                        'Bkash-Online',
                        'Payment from Online using Bkash Payment Gateway. Payment Process By: ' . auth()->user()->email,
                    );
                }
            }

            DB::commit();



            if ($status == 'error') {
                Toastr::error('Recharge UnSuccessfull', 'Recharge UnSuccessfull or already Recharged or duplicate transaction');
            } else {
                Toastr::success('Recharge Successfull', 'Recharge Successfull');
            }

            return redirect()->route('onlineManagerRecharge', $request->reseller_id);
        } catch (\Throwable $th) {
            dd($th);
        }
    }


    public function executePayment(Request $request)
    {
        $paymentID = $request->paymentID;
        $token = $request->cookie('online_reseller_recharge_token_id');

        $request_body = array(
            'paymentID' => $paymentID
        );
        $url = curl_init("$this->base_url/tokenized/checkout/execute");

        $request_body_json = json_encode($request_body);

        $header = array(
            'Content-Type:application/json',
            'Authorization:' . $token,
            "x-app-key:$this->app_key"
        );
        curl_setopt($url, CURLOPT_HTTPHEADER, $header);
        curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($url, CURLOPT_POSTFIELDS, $request_body_json);
        curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        $resultdata = curl_exec($url);

        curl_close($url);

        //   Storage::put('executepayment.txt',$resultdata); //this is for store execute payment response in txt file for debug


        return json_decode($resultdata, true);
    }

    public function queryPayment(Request $request)
    {
        $paymentID = $request->paymentID;
        $token = $this->generateToken();

        $request_body = array(
            'paymentID' => $paymentID
        );
        $url = curl_init("$this->base_url/tokenized/checkout/payment/status");

        $request_body_json = json_encode($request_body);

        $header = array(
            'Content-Type:application/json',
            'Authorization:' . $token,
            "x-app-key:$this->app_key"
        );
        curl_setopt($url, CURLOPT_HTTPHEADER, $header);
        curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($url, CURLOPT_POSTFIELDS, $request_body_json);
        curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        $resultdata = curl_exec($url);

        curl_close($url);
        //   Storage::put('querypayment.txt',$resultdata);  //this is for store query payment response in txt file for debug
        return json_decode($resultdata, true);
    }
}
