<?php

namespace App\Http\Controllers\Reseller;

use App\Models\User;
use App\Models\Balance;
use App\Models\Reseller;
use Illuminate\Http\Request;
use App\Models\UserAccounting;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use App\Models\ResellerRechargeReport;
use App\Classes\SMS\ResellerAccountRechargeSms;
use App\Http\Controllers\OnlinePayment\UpayController;
use App\Http\Controllers\OnlinePayment\BkashResellerController;
use App\Http\Controllers\OnlinePayment\NagadResellerController;
use App\Models\Billpayment;
use Illuminate\Support\Facades\Log;

class ResellerRechargeController extends Controller
{


    public function store(request $request)
    {

        if ($request->amount == 0  && $request->paid_amount == 0) {
            Toastr::error('Recharge UnSuccessfull', 'Recharge UnSuccessfull');
            return redirect()->back()->with('modalopen', 'true');
        }


        $txn_id = now()->format('YmdHis');


        if (ResellerRechargeReport::where('txn_id', $txn_id)->count() > 0 && checkSettings('reseller-recharge-duplicate-protect') == 'enable') {
            Toastr::error('Duplicate Transaction', 'Error');
            return redirect()->back();
        }

        if (checkSettings('reseller-recharge-paid-option') == 'disable') {
            $paid_amount = $request->amount;
        } else {
            $paid_amount = $request->paid_amount;
        }

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


        DB::beginTransaction();
        try {


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

            $status = Balance::balanceUpdate('reseller', $request->reseller_id, $request->amount, $request->remark, $paid_amount, null, 'cash', 'cash', null, now()->format('YmdHi'));

            if ($status === 'success') {

                DB::commit();
                $sms_setting = json_decode(getSmsMessage()->where('tamplate_name', 'reseller_balance_recharge_sms')->first()->tamplate_body, true);
                if ($sms_setting["sendsms"] == "Yes") {
                    $totalRecharge = ResellerRechargeReport::with('reseller', 'user', 'balance')->where('reseller_id', $reseller->id)->sum('amount');
                    (new ResellerAccountRechargeSms())->sendSms($reseller->id, $request->amount, $totalRecharge);
                }
                $commissionReturnResult = 'success';
                Toastr::success('Recharge Successfull', 'Reseller Recharge Successfull');
                // return redirect()->back()->with('modalopen', 'true');
                return redirect()->back()->with([
                    'modalopen' => 'true',
                    'commissionReturnResult' => $commissionReturnResult,
                ]);
            }
        } catch (\Throwable $th) {
            Toastr::error('Recharge UnSuccessfull', 'Recharge UnSuccessfull');
            return redirect()->back()->with('modalopen', 'true');
        }
    }


    public function onlineManagerRecharge(Request $rquest, $id)
    {

        $reseller = Reseller::find($id);
        $rechargeList = ResellerRechargeReport::with('reseller', 'user', 'balance')
            ->where('reseller_id', $id)
            ->orderBy('id', 'desc')
            ->take(10);
        $min_recharge_amount = (isset(siteinfo()->min_recharge_amount) ? siteinfo()->min_recharge_amount : 0);

        return view('reseller.resellerRechargeOnline', [
            'page_title'   => 'Manager Recharge',
            'reseller'     => $reseller,
            'rechargeList' =>  $rechargeList->get(),
            'paid_amount' => false,
            'min_recharge_amount' => $min_recharge_amount
        ]);
    }

    public function onlineManagerRechargeExecute(Request $request)
    {
        if ($request->payment_method == 'upay') {
            return (new UpayController())->createPayment($request);
        } elseif ($request->payment_method == 'bkash') {
            return (new BkashResellerController())->createPayment($request);
        } else if($request->payment_method == 'nagad'){
            return (new NagadResellerController())->createPayment($request);
        }
    }

    public function resellerSms($reseller_id, $amount, $totalRecharge = null)
    {
        $sms_setting = json_decode(getSmsMessage()->where('tamplate_name', 'reseller_balance_recharge_sms')->first()->tamplate_body, true);

        if ($sms_setting["sendsms"] == "Yes") {
            (new ResellerAccountRechargeSms())->sendSms($reseller_id, $amount, $totalRecharge);
        }
    }

    public function getRechargeAmount($reseller, $payment_method, $paid_amount)
    {
        $charges = json_decode($reseller->payment_charges, true);

        if ($charges == null) {
            return $paid_amount;
        } elseif (isset($charges['bkash_charges']) && $charges['bkash_charges'] > 0 && $payment_method == 'Bkash-Online') {
            $paid_amount = $paid_amount - ($paid_amount * ($charges['bkash_charges'] / 100));
        } elseif (isset($charges['upay_charges']) && $charges['upay_charges'] > 0 && $payment_method == 'Upay-Online') {
            $paid_amount = $paid_amount - ($paid_amount * ($charges['upay_charges'] / 100));
        } elseif (isset($charges['rocket_charges']) && $charges['rocket_charges'] > 0 && $payment_method == 'Rocket-Online') {
            $paid_amount = $paid_amount - ($paid_amount * ($charges['rocket_charges'] / 100));
        } elseif (isset($charges['nagad_charges']) && $charges['nagad_charges'] > 0 && $payment_method == 'Nagad-Online') {
            $paid_amount = $paid_amount - ($paid_amount * ($charges['nagad_charges'] / 100));
        }

        return $paid_amount;
    }

    public function rechargeByOnlinePayment($reseller_id, $paid_amount , $client , $payment_method)
    {
        Log::error("comes in rechargeByOnlinePayment function");
        $payment = Billpayment::where('client_id',$client->id)->orderBy('id','desc')->first();
        $gateway_transaction_id = $payment->trx_id;
        $transaction_id = $payment->money_receipt_number;
        $payment_method = $payment->payment_method;
        $remark = 'Reseller Recharge By Online Payment. Customer '.$client->userid.' CID: '.$client->id;
        $this->recharge($reseller_id, $paid_amount, $gateway_transaction_id, $transaction_id, $payment_method, $remark);
    }

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


        $remark = $this->getRechargeRemark($remark, $reseller, $payment_method);

        $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' => 'Recharge Successfull']);
        } else {
            return response()->json(['status' => 'error', 'message' => 'Recharge UnSuccessfull']);
        }
    }


    public function upayResellerCallback(Request $request)
    {
        $data = (new UpayController())->validation($request);

        if ($data['data']['status'] == 'cancelled') {
            Toastr::error('Recharge Canceled', 'Recharge Canceled');
            return redirect()->back();
        }

        $paid_amount = $data['data']['amount'];
        $gateway_transaction_id = $data['data']['trx_id'];



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

        if ($request->status == 'successful' && $data['data']['txn_id'] == $request->transaction_id && $data['data']['status'] == 'success' && $recharge_report == 0) {


            $user_id = User::onlinePaymentUser('Upay-Online')->id;

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

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

            $status = Balance::balanceUpdate('reseller', $reseller->id, $paid_amount, $request->remark, $paid_amount, $user_id, 'Upay', 'Upay', $gateway_transaction_id, $request->transaction_id);
            clearCache('reseller');

            $totalRecharge = ResellerRechargeReport::with('reseller', 'user', 'balance')->where('reseller_id', $reseller->id)->sum('amount');

            if ($status === 'success') {

                $sms_setting = json_decode(getSmsMessage()->where('tamplate_name', 'reseller_balance_recharge_sms')->first()->tamplate_body, true);

                if ($sms_setting["sendsms"] == "Yes") {
                    (new ResellerAccountRechargeSms())->sendSms($reseller->id, $request->amount, $totalRecharge);
                }

                Toastr::success('Recharge Successfull', 'Recharge Successfull');
                return redirect()->route('resellers.index');
            } else {
                Toastr::error('Recharge UnSuccessfull', 'Recharge UnSuccessfull');
                return redirect()->route('resellers.index');
            }
        } else {
            Toastr::error('Recharge UnSuccessfull', 'Recharge UnSuccessfull');
            return redirect()->route('resellers.index');
        }
    }


    public function getRechargeRemark($remark, $reseller, $payment_method)
    {
        $charges = json_decode($reseller->payment_charges, true);

        if ($charges == null) {
            $remark = $remark . ' Online Charges: ' . 0 . '%';
            return $remark;
        } elseif (isset($charges['bkash_charges']) && $charges['bkash_charges'] > 0 && $payment_method == 'Bkash-Online') {
            $remark = $remark . ' Online Charges: ' . $charges['bkash_charges'] . '%';
        } elseif (isset($charges['upay_charges']) && $charges['upay_charges'] > 0 && $payment_method == 'Upay-Online') {
            $remark = $remark . ' Online Charges: ' . $charges['upay_charges'] . '%';
        } elseif (isset($charges['rocket_charges']) && $charges['rocket_charges'] > 0 && $payment_method == 'Rocket-Online') {
            $remark = $remark . ' Online Charges: ' . $charges['rocket_charges'] . '%';
        } elseif (isset($charges['nagad_charges']) && $charges['nagad_charges'] > 0 && $payment_method == 'Nagad-Online') {
            $remark = $remark . ' Online Charges: ' . $charges['nagad_charges'] . '%';
        }

        return $remark;
    }

}
