<?php

namespace App\Http\Controllers\User;

use App\Models\Agent;
use App\Models\Banks;
use App\Models\Beneficiaries;
use App\Models\TradeGiftCard;
use App\Models\TradingCardDetails;
use App\Models\TransactionHistory;
use App\Models\Wallet;
use App\Models\Currency;
use App\Models\Withdraw;
use App\Models\Transaction;
use App\Models\Withdrawals;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use KingFlamez\Rave\Facades\Rave as Flutterwave;



class WithdrawalController extends Controller
{
    public function withdrawForm()
    {
        $wallets = Wallet::where('user_id',auth()->id())->first();
        $beneficiary = Beneficiaries::where('user_id',Auth()->user()->id)->get();
        return view('user.withdraw.withdraw_form',compact('wallets','beneficiary'));
    }

    public function methods(Request $request)
    {
        $methods = Withdraw::where('currency_id',$request->currency)->where('status',1)->get();
        if($methods->isEmpty()){
            return response('empty');
        }
        return response($methods);
    }

    public function withdrawSubmit(Request $request)
    {

        $request->validate([
            'amount'    => 'required|numeric|gt:0',
            'beneficiary' => 'required',
            'password'=>'required',
            'wallet'=>'required'

        ]);


        $checkBeneficiary = getBeneficiaryByUser(Auth()->user()->id, $request['beneficiary']);

        if(!$checkBeneficiary){
            return response()->json([
                'status' => 'error',
                'message' => 'Beneficiary Not Found'
            ], 400);
           // return back()->with('error','Beneficiary Not Found');
        }

        $wallet = Auth()->user()->getMyWallet();
        if(!$wallet){
            return response()->json([
                'status' => 'error',
                'message' => 'Wallet Not Found'
            ], 400);
           // return back()->with('error','Wallet not found');
        }

        //if($request->amount < $method->min_amount || $request->amount > $method->max_amount){
        /* if($request->amount < $wallet->amount > $method->max_amount){
             return back()->with('error','Please follow the limit');
         }
 */
        // $charge = chargeCalc($method,$request->amount);
        $finalAmount = numFormat($request->amount + 50);
        $transferAmount =  numFormat($request->amount);
$walletType = $request->wallet;
if($walletType=='balance') {
    if ($wallet->balance < $finalAmount) {
        return response()->json([
            'status' => 'error',
            'message' => 'Insufficient balance'
        ], 400);
    }
    $wallet->balance -=  $finalAmount;
}else if($walletType=='bonus'){
    if ($wallet->refer_bonus_balance < $finalAmount) {
        return response()->json([
            'status' => 'error',
            'message' => 'Insufficient balance'
        ], 400);
    }
    $wallet->refer_bonus_balance -=  $finalAmount;
}else if($walletType=='registration'){//withdraw from registration bonus
    //check total transaction
    //check giftcard
    $totalTrade = TransactionHistory::select('trading_card_details.amount')
        ->join('trading_card_details', 'trading_card_details.trading_id', '=', 'transaction_histories.id')
        ->where('transaction_histories.user_id', Auth()->user()->id)
        ->where('transaction_histories.status', 'payout')
        ->sum('trading_card_details.amount');
    $toTrade = 1000-$totalTrade;
    if(!($totalTrade >=1000)){
        return response()->json([
            'status' => 'error',
            'message' => 'Your registration bonus is not available for withdrawal at this time. Trade just $'.$toTrade.' more with us to activate withdrawals and enjoy the sweet taste of financial freedom. Keep trading and watch your opportunities grow!'
        ], 400);
    }
    if ($wallet->registration_bonus < $finalAmount) {
        return response()->json([
            'status' => 'error',
            'message' => 'Insufficient balance'
        ], 400);
    }
    if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
        return response()->json([
            'status' => 'error',
            'message' => 'Invalid Password Please Retry'
        ], 400);
    }
    $wallet->registration_bonus -=  $finalAmount;
}
        $reference = Flutterwave::generateReference();

       // $wallet->save();

        $withdraw              = new Withdrawals();
        $withdraw->trx         = str_rand().time();
        $withdraw->user_id     = auth()->id();
        $withdraw->descriptions = 'Withdraw of '.toMoney($transferAmount).' to '. $checkBeneficiary->beneficiary_name.
            '-'.$checkBeneficiary->account_number.' ('.$checkBeneficiary->bank_name.')';
        $withdraw->beneficiary_name   = $checkBeneficiary->beneficiary_name;
        $withdraw->beneficiary_account = $checkBeneficiary->account_number;
        $withdraw->beneficiary_bank_code = $checkBeneficiary->bank_code;
        $withdraw->beneficiary_bank_name = $checkBeneficiary->bank_name;
        $withdraw->amount      = $request->amount;
        $withdraw->currency_id = 'NGN';
        $withdraw->charge      = '50';
        $withdraw->total_amount= $finalAmount;
        $withdraw->is_authenticated=1;
        $withdraw->flw_transfer_status ='NOT INITIATED';
        $withdraw->flw_reference_no= 'R2T-'.$reference;

        $withdraw->save();
        $wallet->save();


        $data = [
            'account_bank'=> $withdraw->beneficiary_bank_code,
            'account_number'=> $withdraw->beneficiary_account,
            'amount' => $transferAmount,
            'narration' => 'Refer2trade Withdraw',
            'currency' => $withdraw->currency_id,
            'reference' => $reference
        ];

        TransactionHistory::create([
            'descriptions' =>'Withdraw of '.toMoney($withdraw->amount).' to '. $withdraw->beneficiary_bank_name.' - '.$withdraw->beneficiary_account.' ('.$withdraw->beneficiary_name.')',
            'trade_id' => null,
            'request_id' =>$withdraw->trx,
            'tradedcard_details_id' => null,
            'transaction_ref' =>$withdraw->trx,
            'user_id' => $withdraw->user_id,
            'amount' =>$withdraw->amount,
            'exchange_rate'=>1,
            'transaction_amount_in_usd'=>1,
            'transaction_type' => 'Debit',
            'created_by' => auth()->user()->id,
            'source' => 'Withdraw',
            'status' => 'pending',
            'status_at' => now(),
            'status_by' => auth()->user()->id,
            'status_reason' => 'Transaction Initiate' ,

            'rate' => null,
            'currency' => "NGN",
        ]);
        /*
         $data = [
            'account_bank'=> '044',
            'account_number'=> '0690000040',
            'amount' => $transferAmount,
            'narration' =>  $withdraw->descriptions,
            'currency' => $withdraw->currency_id,
            'reference' => $reference
        ];*/


        $transfer = Flutterwave::transfers()->initiate($data);
        if($transfer['status']=='success'){
            $data = $transfer['data'];
            $withdraw->flw_transfer_id= $data['id'];
            $withdraw->flw_transfer_status = $data['status'];
            $withdraw->flw_complete_message = $data['complete_message'];
            $withdraw->flw_trans_charges = $data['fee'];
            $withdraw->save();
        }

        //return redirect('dashboard');
        return response()->json([
            'status' => 'success',
            'message' => 'Withdraw is initiated'
        ], 200);
       // return back()->with('success','Withdraw request has been submitted successfully.');
    }

    public function history()
    {
        $withdrawals = Withdrawals::where('user_id',auth()->id())->latest()->paginate(15);
        return view('user.withdraw.history',compact('withdrawals'));
    }

    public function checkAgent(Request $request){
        $receiver['data'] = Agent::where('email',$request->receiver)->first();
        if($receiver['data']){
            return response($receiver);
        }
        return response(null);
    }

    public function cashOutForm()
    {
        $wallets = Wallet::where('user_id',auth()->id())->where('user_type',1)->where('balance', '>', 0)->get();
        $charge = charge('cashout');
        return view('user.withdraw.cashout',compact('wallets','charge'));
    }

    public function cashOut(Request $request)
    {
        $request->validate([
            'receiver'  => 'required|email',
            'wallet_id' => 'required|integer',
            'amount'    => 'required|numeric|gt:0'
        ],
        [
            'wallet_id.required' => 'Wallet is required'
        ]);


        $agent = Agent::where('email',$request->receiver)->first();
        if(!$agent) return back()->with('error','Agent not found');

        $senderWallet = Wallet::where('id',$request->wallet_id)->where('user_type',1)->where('user_id',auth()->id())->first();
        if(!$senderWallet) return back()->with('error','Your wallet not found');

        $currency = Currency::findOrFail($senderWallet->currency->id);

        $charge = charge('cashout');

        if($charge->daily_limit != 0 && auth()->user()->cashOutDailyLimit() >= $charge->daily_limit){
            return back()->with('error','Your daily cashout limit has been reached');
        }

        if($charge->monthly_limit != 0 && auth()->user()->cashOutMonthlyLimit() >= $charge->monthly_limit){
            return back()->with('error','Your monthly cashout limit has been reached');
        }

        if(($charge->minimum *  $currency->rate) > $request->amount || ($charge->maximum *  $currency->rate) < $request->amount){
            return back()->with('error','Please follow the limit');
        }

        $agentWallet = Wallet::where('currency_id',$currency->id)->where('user_type',3)->where('user_id',$agent->id)->first();

        if(!$agentWallet){
            $agentWallet = Wallet::create([
                'user_id'     => $agent->id,
                'user_type'   => 3,
                'currency_id' => $currency->id,
                'balance'     => 0
            ]);
        }

        $finalCharge = amount(chargeCalc($charge,$request->amount,$currency->rate),$currency->type);
        $finalAmount =  amount($request->amount + $finalCharge, $currency->type);

        if($senderWallet->balance < $finalAmount) return back()->with('error','Insufficient balance.');

        $senderWallet->balance -= $finalAmount;
        $senderWallet->update();

        $trnx              = new Transaction();
        $trnx->trnx        = str_rand();
        $trnx->user_id     = auth()->id();
        $trnx->user_type   = 1;
        $trnx->currency_id = $currency->id;
        $trnx->wallet_id   = $senderWallet->id;
        $trnx->amount      = $request->amount;
        $trnx->charge      = $finalCharge;
        $trnx->remark      = 'cash_out';
        $trnx->type        = '-';
        $trnx->details     = trans('Cash out to '). $agent->email;
        $trnx->save();

        $agentWallet->balance += $request->amount;
        $agentWallet->update();

        $receiverTrnx              = new Transaction();
        $receiverTrnx->trnx        = $trnx->trnx;
        $receiverTrnx->user_id     = $agent->id;
        $receiverTrnx->user_type   = 3;
        $receiverTrnx->currency_id = $currency->id;
        $receiverTrnx->amount      = $request->amount;
        $receiverTrnx->charge      = 0;
        $receiverTrnx->remark      = 'cash_out';
        $receiverTrnx->type        = '+';
        $receiverTrnx->details     = trans('Cash out from '). auth()->user()->email;
        $receiverTrnx->save();

        try {
            @mailSend('cash_out_user',[
                'amount'    => amount($request->amount,$senderWallet->currency->type,3),
                'curr'      => $senderWallet->currency->code,
                'agent'     => $agent->email,
                'trnx'      => $trnx->trnx,
                'charge'    => amount($finalCharge,$senderWallet->currency->type,3),
                'date_time' => dateFormat($trnx->created_at),
                'balance'   => amount($senderWallet->balance,$senderWallet->currency->type,3)
            ],auth()->user());

            @mailSend('cash_out_agent',[
                'amount'    => amount($request->amount,$senderWallet->currency->type,3),
                'curr'      => $senderWallet->currency->code,
                'user'      => auth()->user()->email,
                'trnx'      => $trnx->trnx,
                'date_time' => dateFormat($trnx->created_at),
                'balance'   => amount($senderWallet->balance,$senderWallet->currency->type,3)
            ],$agent);
        } catch (\Throwable $th) {

        }

        return back()->with('success','Cash out successfully');


    }

    public function testFlutter()
    {


       $data = [

            'account_number'=> '0690000032',
            'account_bank' => '044'
        ];

        $transfer = Flutterwave::banks()->nigeria();
$transfer= $transfer['data'];
$data = [];
        foreach($transfer as $tra){
          $data[]=['bank_name'=>$tra['name'],'bank_code'=>$tra['code']];

        }
        DB::table('banks')->insert($data);
       // $transfer = Flutterwave::banks()->nigeria();

        //var_dump($transfer);die();
    }
}
