<?php

namespace App\Http\Controllers;


use App\Jobs\ClientSyncJobForSingle;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;


class UpayPaymentController extends Controller
{

    public function upayPaymenToken(Request $request)
    {
    //    dd($request->amount);

        $post = [
            // 'merchant_id' => config::get('UPAY_MERCHANT_ID'),
            'merchant_id' => Config::get('payment.UPAY_MERCHANT_ID'),
            'merchant_key' => Config::get('payment.UPAY_MERCHANT_KEY'),

        ];
        $base_url = Config::get('payment.UPAY_BASE_URL');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $base_url.'payment/merchant-auth/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $response = curl_exec($ch);
        curl_close($ch);
        $token_result = json_decode($response, true);

        if($token_result['message'] == 'Merchant Auth Success'){
            $token = $token_result['data']['token'];

            $redirect_url_with_id = Config::get('payment.UPAY_RDIRECT_URL')."?customer_id=".$request->customer_id;

            $invoice_id = time().$request->customer_id;
            $txn_id = 'up'.time().$request->customer_id;

            session(['upay_token' => $token]);
            session(['upay_txn_id' => $txn_id]);



            $data= [
                'date' => Carbon::parse(now())->format('Y-m-d'),
                'txn_id' => $txn_id,
                'invoice_id' => $invoice_id,
                'amount' => $request->amount,
                'merchant_id' => Config::get('payment.UPAY_MERCHANT_ID'),
                'merchant_name' => Config::get('payment.UPAY_MERCHANT_NAME'),
                'merchant_country_code' => 'BD',
                'merchant_city' => 'Dhaka',
                'merchant_category_code' => 'Merchant',
                'merchant_mobile' => Config::get('payment.UPAY_WALLET'),
                'transaction_currency_code' => 'BDT',
                'redirect_url' => $redirect_url_with_id,
                'additional_info' => '{Data: test}',
                'merchant_code' => Config::get('payment.UPAY_MERCHANT_CODE'),

            ];


            $header = "UPAY ".$token;
            $header_data = array(
                "Authorization:$header",
            );
            $ch_payment_inti = curl_init();
            curl_setopt($ch_payment_inti, CURLOPT_URL, $base_url.'payment/merchant-payment-init/');
            curl_setopt($ch_payment_inti, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_payment_inti, CURLOPT_HTTPHEADER,$header_data);
            curl_setopt($ch_payment_inti, CURLOPT_POSTFIELDS, http_build_query($data));
            $response_payment = curl_exec($ch_payment_inti);

            $response_payment = json_decode($response_payment, true);

            if($response_payment['message'] == "Merchant Payment Init Success"){
                $redirect_url = $response_payment['data']['gateway_url'];
                $data = [
                    'message' => $redirect_url,
                    'status' => 'success'
                ];
                return $data;
            }else{
                $data = [
                    'message' => $response_payment['message'],
                    'status' => 'error'
                ];
                return $data;
            }


        }else{
            $data = [
                'message' => $token_result['message'],
                'status' => 'error'
            ];
            return $data;
        }

    }


    public function upayCheckout(Request $request){


        $txn_id_session = session('upay_txn_id');
        $upay_token_id_session =session('upay_token');



        $post = [
            'merchant_id' => Config::get('payment.UPAY_MERCHANT_ID'),
            'merchant_key' => Config::get('payment.UPAY_MERCHANT_KEY'),

        ];
        $base_url = Config::get('payment.UPAY_BASE_URL');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $base_url.'payment/merchant-auth/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $response = curl_exec($ch);
        curl_close($ch);
        $token_result = json_decode($response, true);

        if($token_result['message'] == 'Merchant Auth Success'){
            $token = $token_result['data']['token'];

            $url = $base_url."payment/single-payment-status/".$txn_id_session."/";
            $data = array(

                'txn_id' => $txn_id_session,
            );

            $header = array(
                "Authorization: "."UPAY ".$token,
            );

            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => $header,
            ));

            $response = curl_exec($curl);

            curl_close($curl);

            $response_payment = json_decode($response, true);
                // dd($response_payment);

            if($response_payment['data']['status'] == 'success'){
                (new PaymentController)->UpaypaymentProcess($response_payment['data']['amount'], $request->customer_id, $response_payment['data']['trx_id']);
                if (checkAPI()) {
                    ClientSyncJobForSingle::dispatch($request->customer_id);
                }

                Toastr::success('Upay Payment is Successful');
                return redirect()->route('customerDashboard');
            }else{
                Toastr::error('Upay Payment is not Successful');
                return redirect()->route('customerDashboard');

            }
            Toastr::error('Upay Payment is not Successful');
            return redirect()->route('customerDashboard');
        }




    }

}
