<?php

namespace App\Http\Controllers;

use App\Classes\SMS\ResellerAccountRechargeSms;
use App\Models\Balance;
use App\Models\PgwResponseLog;
use App\Models\Pop;
use App\Models\Reseller;
use App\Models\ResellerRechargeReport;
use App\Models\SubResellerRechargeReport;
use App\Models\User;
use App\Models\UserAccounting;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use App\Classes\Notification;
use App\Http\Controllers\OnlinePopRecharge\NagadPoprechargeController;
use App\Http\Controllers\Reseller\ResellerRechargeController;
use App\Models\Billpayment;

class NagadPgwPaymentSyncController extends Controller
{
    function headers()
    {
        return [
            "Content-Type"     => "application/json",
            "X-KM-IP-V4"       => request()->ip(),
            "X-KM-Api-Version" => "v-0.2.0",
            "X-KM-Client-Type" => "PC_WEB"
        ];
    }



    public function sync()
    {
        $start = today()->subDay(1);
        $end   = today()->endOfDay();
        $nagadPgwResponseLogs = PgwResponseLog::whereNull('status')->orWhere('status', '=','Failed')
                                            ->where('payment_method', 'Nagad')
                                            ->whereBetween('created_at',[$start,$end])->get();
        // dd($nagadPgwResponseLogs->count());
        foreach($nagadPgwResponseLogs as $nagadPgwResponseLog){


            $url      = config('app.nagad_base_url') . "verify/payment/{$nagadPgwResponseLog->payment_ref_id}";
            $response = Http::withHeaders($this->headers())->get($url);
            $response_payment = json_decode($response->body(), true);

            // dd($response_payment);

            if(isset($response_payment['status']) && ($response_payment['status'] == "Success" )){

                    $transaction_id = $response_payment['issuerPaymentRefNo'];
                    $actual_amount = $response_payment['amount'];

                    $paid_amount = $response_payment['amount'];
                    $gateway_transaction_id = $response_payment['issuerPaymentRefNo'];

                    $added_by = User::find($nagadPgwResponseLog->added_by);

                    if($nagadPgwResponseLog->payment_for == "Pop"){
                        $pop_online_recharge = SubResellerRechargeReport::where('payment_gateway_transaction_id', $gateway_transaction_id)->count();

                        if($pop_online_recharge == 0 ){

                            DB::beginTransaction();
                            try{
                                    $user_id = User::onlinePaymentUser('Nagad-Online')->id;
                                    $pop = Pop::find($nagadPgwResponseLog->user_id);
                                    $paid_amount = (new PopController)->getPaidAmountForOnlinePopRecharge($pop,'Nagad-Online',$paid_amount);
                                    $charge_remark = (new NagadPoprechargeController())->getChargeRemark($pop, 'Nagad-Online');

                                    $remark = 'Nagad-Online Recharge by ' . $added_by->email . ' Amount : ' . $paid_amount . " ".$charge_remark. " from Sync";
                                    $pop_recharge_status = Balance::balanceUpdate('pop', $pop->id, $paid_amount, $remark, $paid_amount, $user_id, 'online', 'Nagad', $gateway_transaction_id, $transaction_id);

                                    if ($pop_recharge_status === 'success') {
                                        (new Notification)->notify('Pop Recharge by by ' . $added_by->email . ' Amount : ' . $actual_amount . ' Remark: ' . $remark);
                                    }

                                    $reseller = Reseller::find($pop->reseller_id);

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

                                    $status = Balance::balanceUpdate('reseller', $reseller->id, $paid_amount, $remark, $paid_amount, $user_id, 'online', 'Nagad', $gateway_transaction_id, $transaction_id);
                                    $totalRecharge = ResellerRechargeReport::with('reseller', 'user', 'balance')->where('reseller_id', $reseller->id)->sum('amount');



                                    $nagadPgwResponseLog->status = 'Success';
                                    $nagadPgwResponseLog->error_massage = "Recharge Successfull";
                                    $nagadPgwResponseLog->save();

                                    // dd($nagadPgwResponseLog);
                                    DB::commit();

                                    if ($status === 'success') {
                                        $sms_setting = json_decode(getSmsMessage()->where('tamplate_name', 'reseller_balance_recharge_sms')->first()->tamplate_body, true);
                                        if ($sms_setting["sendsms"] == "Yes") {
                                            try{
                                                (new ResellerAccountRechargeSms())->sendSms($reseller->id, $actual_amount, $totalRecharge);
                                            }catch(\Exception $e){
                                            }
                                        }
                                    }

                            }catch(\Exception $e){
                                // dd($e);
                            }

                        }else if($pop_online_recharge > 0){

                            $nagadPgwResponseLog->status = 'Success';
                            $nagadPgwResponseLog->save();
                        }
                    }

                    if($nagadPgwResponseLog->payment_for == "Reseller"){

                        $order_no = $response_payment['orderId'];
                        $recharge_report = ResellerRechargeReport::where('payment_gateway_transaction_id', $order_no)->count();
                        if ( $recharge_report == 0 ) {
                            DB::beginTransaction();
                            try{


                                $status =   (new ResellerRechargeController)->recharge(
                                    $nagadPgwResponseLog->user_id,
                                    $response_payment['amount'],
                                    $order_no,
                                    $response_payment['issuerPaymentRefNo'],
                                    'Nagad-Online',
                                    'Payment from Online useing Nagad Payment Gateway. Payment Process By: '.$added_by->email. " from Sync",
                                );


                                $nagadPgwResponseLog->status = 'Success';
                                $nagadPgwResponseLog->save();

                                DB::commit();
                            }catch(\Exception $e){
                                // dd($e);
                            }
                        }else if($recharge_report > 0){

                            $nagadPgwResponseLog->status = 'Success';
                            $nagadPgwResponseLog->save();
                        }
                    }

                    if($nagadPgwResponseLog->payment_for == "Client" && globalPermission('nagad-client-payment-sync')){

                        DB::beginTransaction();
                        try{
                            $checkBillPayment = Billpayment::where('money_receipt_number',$response_payment['issuerPaymentRefNo'])->get()->count();

                            if($checkBillPayment > 0){

                                $nagadPgwResponseLog->status = 'Success';
                                $nagadPgwResponseLog->save();

                            }else{

                                (new PaymentController)->NagadClientCheckOutPaymentProcess(
                                    $response_payment['amount'],
                                    $nagadPgwResponseLog->user_id,
                                    $response_payment['issuerPaymentRefNo'],
                                    $response_payment['clientMobileNo'],
                                    $response_payment['paymentRefId'],
                                    $response_payment['issuerPaymentDateTime'],
                                );

                                $nagadPgwResponseLog->status = 'Success';
                                $nagadPgwResponseLog->save();
                            }

                            DB::commit();
                        }catch(\Exception $e){
                            DB::rollback();
                            // Toastr::error('Nagad Payment is not Successful');
                            // return redirect()->route('customerDashboard');
                        }
                    }


            }else{
                $nagadPgwResponseLog->status = 'Failed';
                $nagadPgwResponseLog->save();
            }
        }
    }
}
