<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\BonusPurchasePool;
use App\Models\Member;
use App\Models\Wallet;
use App\Models\WalletLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class BonusPurchasePoolController extends Controller
{
    public function index()
    {
        $randomRefNo = wordwrap(generateRandomCode(12), 4, "-", true);
        $referenceNo = "BPP-$randomRefNo";
        $applicationDate = Carbon::now()->format('d-m-Y');

        $walletBalance = Wallet::whereHas('wallet_list',function ($q){
            $q->where('name','Bonus wallet');
        })->where(['user_id' => Auth::id()])->first();

        $kycStatus = Member::where('user_id',Auth::id())->value('kyc_status');
        $isEnable2fa = false;
        if((!empty(Auth::user()->setting->fa_setting) && in_array('bonus_purchase_pool', Auth::user()->setting->fa_setting)) || !empty(Auth::user()->setting->fa3_setting) && in_array('bonus_purchase_pool', Auth::user()->setting->fa3_setting)){
            $isEnable2fa = true;
        }
        return view('frontend.bonus_purchase_pool.index',compact('walletBalance','kycStatus','referenceNo','applicationDate','isEnable2fa'));
    }

    public function bonusPurchasePoolStore(Request $request)
    {
        if(in_array('bonus_purchase_pool', Auth::user()->setting->fa_setting) || in_array('bonus_purchase_pool', Auth::user()->setting->fa3_setting)) {
            if(!Session::has('bonusPurchasePool2faVerification') || (Session::has('bonusPurchasePool2faVerification') && Session::get('bonusPurchasePool2faVerification') !== true)) {
                return response()->json(['status' => false, 'msg' => 'Can`t submit form without authentication code '], Response::HTTP_UNPROCESSABLE_ENTITY);
            } else {
                Session::forget('bonusPurchasePool2faVerification');
            }
        }
        $data = $request->validate([
            'amount' => 'required|numeric',
            'reference_no' => 'required'
        ], [
            'amount.required' => 'The Amount field is required.',
            'amount.numeric' => 'The Amount must be a number.',
            'reference_no.required' => 'The Reference No field is required.',
        ]);

        $walletBalance = Wallet::whereHas('wallet_list',function ($q){
            $q->where('name','Bonus wallet');
        })->where(['user_id' => Auth::id()])->first();
        $data['wallet_id'] = $walletBalance->id;
        $data['application_date'] = Carbon::now();
        $data['user_id'] = Auth::id();

        if($data['amount'] > $walletBalance->balance) {
            return response()->json(['success' => false,'msg' => 'Transaction declined: insufficient balance.'], 422);
        }

        $bonusPurchase = BonusPurchasePool::create($data);

        $walletLogData['amount'] = $bonusPurchase->amount;
        $walletLogData['reference_no'] = $bonusPurchase->reference_no;
        $amount =  round($bonusPurchase->amount,2);
        $balance = (double) $walletBalance->balance - (double) $amount;
        $balanceLog =  'Your bonus wallet balance changed from '. formatDisplayNumber($walletBalance->balance) .' to '. formatDisplayNumber($balance) .'';
        $walletBalance->balance = $balance;
        $walletBalance->save();

        WalletLog::create([
            'wallet_id' => $bonusPurchase->wallet_id,
            'action' => WalletLog::ACTION_CSR_PURCHASE,
            'data' => json_encode($walletLogData),
            'value' => $bonusPurchase->amount,
            'balance' => $balance,
            'unique_id' => $bonusPurchase->id
        ]);
        $log = 'Bonus purchase pool created successfully. <br><br>
                Username: ' . Auth::user()->details->username . ' <br>
                Members Name: ' . Auth::user()->details->first_name . ' ' . Auth::user()->details->last_name . ' <br>
                Requested Amount: ' . formatDisplayNumber($data['amount']) . ' EUR <br>
                Reference No: ' . $bonusPurchase->reference_no . '<br>
                Application Date: ' . $bonusPurchase->created_at . '<br>';
        saveLog($log, Auth::user(), ['logType' => 'bonus purchase pool'], 'bonus purchase pool');

        saveLog($balanceLog, Auth::user(), ['logType' => 'wallet balance'], 'wallet balance');


        return response()->json(['success' => true, 'msg' => 'Bonus purchase pool application created successfully']);
    }
}
