<?php

namespace App\Http\Controllers\OnlinePayment;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Reseller\ResellerRechargeController;
use App\Library\SslCommerz\SslCommerzNotificationReseller;
use App\Models\Reseller;
use App\Models\ResellerRechargeReport;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SSLResellerController extends Controller
{
    public function exampleEasyCheckout()
    {
        return view('exampleEasycheckout');
    }

    public function exampleHostedCheckout()
    {
        return view('exampleHosted');
    }

    public function index(Request $request)
    {
        # Here you have to receive all the order data to initate the payment.
        # Let's say, your oder transaction informations are saving in a table called "orders"
        # In "orders" table, order unique identity is "transaction_id". "status" field contain status of the transaction, "amount" is the order amount to be paid and "currency" is for storing Site Currency which will be checked with paid currency.

        $post_data = array();
        $post_data['total_amount'] = '10'; # You cant not pay less than 10
        $post_data['currency'] = "BDT";
        $post_data['tran_id'] = uniqid(); // tran_id must be unique

        # CUSTOMER INFORMATION
        $post_data['cus_name'] = 'Customer Name';
        $post_data['cus_email'] = 'customer@mail.com';
        $post_data['cus_add1'] = 'Customer Address';
        $post_data['cus_add2'] = "";
        $post_data['cus_city'] = "";
        $post_data['cus_state'] = "";
        $post_data['cus_postcode'] = "";
        $post_data['cus_country'] = "Bangladesh";
        $post_data['cus_phone'] = '8801XXXXXXXXX';
        $post_data['cus_fax'] = "";

        # SHIPMENT INFORMATION
        $post_data['ship_name'] = "Store Test";
        $post_data['ship_add1'] = "Dhaka";
        $post_data['ship_add2'] = "Dhaka";
        $post_data['ship_city'] = "Dhaka";
        $post_data['ship_state'] = "Dhaka";
        $post_data['ship_postcode'] = "1000";
        $post_data['ship_phone'] = "";
        $post_data['ship_country'] = "Bangladesh";

        $post_data['shipping_method'] = "NO";
        $post_data['product_name'] = "Computer";
        $post_data['product_category'] = "Goods";
        $post_data['product_profile'] = "physical-goods";

        # OPTIONAL PARAMETERS
        $post_data['value_a'] = "ref001";
        $post_data['value_b'] = "ref002";
        $post_data['value_c'] = "ref003";
        $post_data['value_d'] = "ref004";

        #Before  going to initiate the payment order status need to insert or update as Pending.
        $update_product = DB::table('orders')
            ->where('transaction_id', $post_data['tran_id'])
            ->updateOrInsert([
                'name' => $post_data['cus_name'],
                'email' => $post_data['cus_email'],
                'phone' => $post_data['cus_phone'],
                'amount' => $post_data['total_amount'],
                'status' => 'Pending',
                'address' => $post_data['cus_add1'],
                'transaction_id' => $post_data['tran_id'],
                'currency' => $post_data['currency']
            ]);

        $sslc = new SslCommerzNotificationReseller();
        # initiate(Transaction Data , false: Redirect to SSLCOMMERZ gateway/ true: Show all the Payement gateway here )
        $payment_options = $sslc->makePayment($post_data, 'hosted');

        try {
            $new_post_data = json_encode($payment_options);
            DB::table('orders')
                ->where('transaction_id', $post_data['tran_id'])
                ->update(['post_data' => $new_post_data]);
        } catch (\Exception $e) {
        }

        if (!is_array($payment_options)) {
            print_r($payment_options);
            $payment_options = array();
        }
    }

    public function payViaAjax(Request $request)
    {

        $info = (array)json_decode($request->cart_json);
        $reseller = Reseller::where('id', $info['reseller_id'])->first();

        # Here you have to receive all the order data to initate the payment.
        # Lets your oder trnsaction informations are saving in a table called "orders"
        # In orders table order uniq identity is "transaction_id","status" field contain status of the transaction, "amount" is the order amount to be paid and "currency" is for storing Site Currency which will be checked with paid currency.

        $post_data = array();
        $post_data['total_amount'] = $info['enteredAmount']; # You cant not pay less than 10
        $post_data['currency'] = "BDT";
        $post_data['tran_id'] = uniqid(); // tran_id must be unique

        # CUSTOMER INFORMATION
        $post_data['cus_name'] =  $reseller->name;
        $post_data['cus_email'] = Auth::user()->email;
        $post_data['cus_add1'] = $reseller->address;
        $post_data['cus_add2'] = $reseller->remark;
        $post_data['cus_city'] = "";
        $post_data['cus_state'] = "";
        $post_data['cus_postcode'] = "";
        $post_data['cus_country'] = "Bangladesh";
        $post_data['cus_phone'] = $reseller->contact;
        $post_data['cus_fax'] = "";

        # SHIPMENT INFORMATION
        $post_data['ship_name'] = "Store Test";
        $post_data['ship_add1'] = "Dhaka";
        $post_data['ship_add2'] = "Dhaka";
        $post_data['ship_city'] = "Dhaka";
        $post_data['ship_state'] = "Dhaka";
        $post_data['ship_postcode'] = "1000";
        $post_data['ship_phone'] = "";
        $post_data['ship_country'] = "Bangladesh";

        $post_data['shipping_method'] = "NO";
        $post_data['product_name'] = "Internet Package";
        $post_data['product_category'] = "Package";
        $post_data['product_profile'] = "Virtual-products";

        # OPTIONAL PARAMETERS
        $post_data['value_a'] = $info['reseller_id'];
        $post_data['value_b'] = "ref002";
        $post_data['value_c'] = "ref003";
        $post_data['value_d'] = "ref004";

        #Before  going to initiate the payment order status need to update as Pending.
        $update_product = DB::table('orders')
            ->where('transaction_id', $post_data['tran_id'])
            ->updateOrInsert([
                'name' => $post_data['cus_name'],
                'email' => $post_data['cus_email'],
                'phone' => $post_data['cus_phone'],
                'amount' => $post_data['total_amount'],
                'status' => 'Pending',
                'address' => 'ResellerRecharge', // $post_data['cus_add1'],
                'transaction_id' => $post_data['tran_id'],
                'currency' => $post_data['currency'],
                'customer_id' => $post_data['value_a'],
                'created_at' => now(),
                'updated_at' => now()
            ]);

        $sslc = new SslCommerzNotificationReseller();
        # initiate(Transaction Data , false: Redirect to SSLCOMMERZ gateway/ true: Show all the Payement gateway here )
        $payment_options = $sslc->makePayment($post_data, 'checkout', 'json');

        try {
            $new_post_data = json_encode($payment_options);
            DB::table('orders')
                ->where('transaction_id', $post_data['tran_id'])
                ->update(['post_data' => $new_post_data]);
        } catch (\Exception $e) {
        }

        if (!is_array($payment_options)) {
            print_r($payment_options);
            $payment_options = array();
        }
    }

    public function success(Request $request)
    {
        // dd($request['val_id']);
        Log::error(json_encode($request->all()));
        $tran_id = $request->input('tran_id');
        $amount = $request->input('amount');
        $currency = $request->input('currency');
        $reseller_id = $request->input('value_a');

        $sslc = new SslCommerzNotificationReseller();
        $post_data = json_encode($request->all());

        try {

            $update_order_page = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->update(['post_data' => $post_data,]);

            if (isset($request['val_id']) && $request['val_id'] != null) {
                DB::table('orders')
                    ->where('transaction_id', $request->input('tran_id'))
                    ->update(['val_id' => $request['val_id']]);
            }

            #Check order status in order tabel against the transaction id or order id.
            $order_detials = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->select('transaction_id', 'status', 'currency', 'amount')->first();
        } catch (\Exception $e) {
        }

        Log::error($order_detials->status);

        $validation = $sslc->orderValidate($request->all(), $tran_id, $amount, $currency);
        Log::error($validation);
        if ($validation == TRUE) {

            $update_product = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->update(['status' => 'Processing']);
            DB::beginTransaction();
            try {

                $recharge_report = ResellerRechargeReport::where('payment_gateway_transaction_id', $tran_id)->count();

                if ($recharge_report == 0) {
                    $status =   (new ResellerRechargeController)->recharge(
                        $reseller_id,
                        $amount,
                        $tran_id,
                        $request['val_id'],
                        'SSL-Commerz',
                        'Payment from Online useing SSL-Commerz. Payment Process By: ' . auth()->user()->email,
                    );
                }

                DB::commit();
            } catch (\Exception $e) {
                Log::error("error in ssl payment");
            }

            Toastr::success('Payment Successfull', 'Success');
            return redirect()->route('onlineManagerRecharge', $reseller_id);
        } else {

            $update_product = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->update(['status' => 'Failed']);

            return redirect()->route('onlineManagerRecharge', $reseller_id)->with('error_message', 'Validation Faild');
        }
    }

    public function fail(Request $request)
    {
        // dd($request->all());
        $tran_id = $request->input('tran_id');
        $post_data = json_encode($request->all());

        $update_order_page = DB::table('orders')
            ->where('transaction_id', $tran_id)
            ->update(['post_data' => $post_data]);

        if (isset($request['val_id']) && $request['val_id'] != null) {
            DB::table('orders')
                ->where('transaction_id', $request->input('tran_id'))
                ->update(['val_id' => $request['val_id']]);
        }

        $order_detials = DB::table('orders')
            ->where('transaction_id', $tran_id)
            ->select('transaction_id', 'status', 'currency', 'amount')->first();

        if ($order_detials->status == 'Pending') {
            $update_product = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->update(['status' => 'Failed']);
            Toastr::error('Payment Falied', 'Falied');
            return redirect()->route('resellers.index')->with('error_message', 'Transaction is Falied');

        } else if ($order_detials->status == 'Processing' || $order_detials->status == 'Complete') {

            Toastr::error('Transaction is already Successful', 'Falied');
            return redirect()->route('resellers.index')->with('success_message', 'Transaction is already Successful');
        } else {

            Toastr::error('Transaction is Invalid', 'Falied');
            return redirect()->route('resellers.index')->with('error_message', 'Transaction is Invalid');
        }
    }

    public function cancel(Request $request)
    {
        // dd($request->all());
        $tran_id = $request->input('tran_id');
        $post_data = json_encode($request->all());

        $update_order_page = DB::table('orders')
            ->where('transaction_id', $tran_id)
            ->update(['post_data' => $post_data]);

        if (isset($request['val_id']) && $request['val_id'] != null) {
            DB::table('orders')
                ->where('transaction_id', $request->input('tran_id'))
                ->update(['val_id' => $request['val_id']]);
        }

        $order_detials = DB::table('orders')
            ->where('transaction_id', $tran_id)
            ->select('transaction_id', 'status', 'currency', 'amount')->first();

        if ($order_detials->status == 'Pending') {
            $update_product = DB::table('orders')
                ->where('transaction_id', $tran_id)
                ->update(['status' => 'Canceled']);

            return redirect()->route('resellers.index')->with('error_message', 'Transaction is Canceled');

        } else if ($order_detials->status == 'Processing' || $order_detials->status == 'Complete') {
            return redirect()->route('resellers.index')->with('success_message', 'Transaction is already Successful');

        } else {
            return redirect()->route('resellers.index')->with('success_message', 'Transaction is Invalid');

        }
    }

    public function sslVarification()
    {
        $orders = DB::table('orders')
            ->where('status', 'Pending')
            ->whereBetween('created_at', [today()->firstOfMonth(), today()->endOfMonth()])
            ->get();

        foreach ($orders as $order) {
            $result =  (new SslCommerzNotificationReseller())->orderVarification($order);

            dd($result);
        }
        dd($orders);
    }
}
