<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PayToYetFixController 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://127.0.0.1:8000') {
            $this->callbackurl      = 'http://127.0.0.1:8000/admin/bkash-yetFix-callback';
        } else {
            $this->callbackurl      = url('/') . '/admin/bkash-yetFix-callback';
        }

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

    public function invWisePayToYetFixExecute(Request $request)
    {
        if ($request->payment_method == 'bkash') {
            return $this->createPayment($request);
        }
    }

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

        $re['intent'] = 'sale';
        $re['currency'] = 'BDT';
        $re['merchantInvoiceNumber'] = now()->timestamp . $request->invoice_id;
        $re['mode'] = "0011";
        $re['payerReference'] = $this->payerReference;
        $re['callbackURL'] = $this->callbackurl . "?merchantInvoiceNumber=" . $re['merchantInvoiceNumber'] . "&invoice_id=" . $request->invoice_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);

        //sett reseller id in session
        session()->put('invoice_id', $request->invoice_id);

        return json_decode($resultdata, true);
    }

    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 bkashYetFixCallback(Request $request, $status = 'error')
    {
        if ($request->paymentID == null || $request->status == 'cancel' || $request->status == 'failure') {
            Toastr::error('UnSuccessful', 'Faild');
            return redirect()->route('portal-invoice');
        }

        // dd($request->all());
        DB::beginTransaction();

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

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

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

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

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

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

            DB::commit();

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

            return redirect()->route('portal-invoice');
        } catch (\Throwable $th) {
            dd($th);
        }
    }

    public function recharge($reseller_id, $paid_amount, $gateway_transaction_id, $transaction_id, $payment_method, $remark)
    {
        // $user_id = User::onlinePaymentUser($payment_method)->id;
        // $reseller = Reseller::find($reseller_id);

        // $paid_amount = $this->getRechargeAmount($reseller, $payment_method, $paid_amount);

        // if ($reseller->reseller_type == 'other') {
        //     $actions = 'Reseller payment received from ' . $reseller->name . ' ' . $reseller->contact;
        //     UserAccounting::userAcStore($paid_amount, $actions, null, $payment_method, $payment_method, $user_id);
        // }

        // $status = Balance::balanceUpdate('reseller', $reseller_id, $paid_amount, $remark, $paid_amount, $user_id, $payment_method, $payment_method, $gateway_transaction_id, $transaction_id);
        // clearCache('reseller');

        // if ($status == 'success') {
        //     $this->resellerSms($reseller->id, $paid_amount);
            return response()->json(['status' => 'success', 'message' => 'Successfull']);
        // } else {
        //     return response()->json(['status' => 'error', 'message' => 'UnSuccessfull']);
        // }
    }

    public function executePayment(Request $request)
    {
        $paymentID = $request->paymentID;
        $token = session()->get('bkash_token');

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