<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CardMonthlyMaintenanceDeductionRequest;
use App\Models\CardMaintenanceCharge;
use App\Models\CardMonthlyMaintenanceDeduction;
use App\Models\TransactionHistory;
use App\Models\VirtualCard;
use App\Models\VirtualCardKy;
use App\Models\Wallet;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class CardMonthlyMaintenanceDeductionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $cardMonthlyMaintenanceDeductions = CardMonthlyMaintenanceDeduction::paginate();

        return view('admin.card-monthly-maintenance-deduction.index', compact('cardMonthlyMaintenanceDeductions'))
            ->with('i', ($request->input('page', 1) - 1) * $cardMonthlyMaintenanceDeductions->perPage());
    }



    /**
     * Show the form for creating a new resource.
     */
    public function runDeduction(): View
    {
        $cardMonthlyMaintenanceDeduction = new CardMonthlyMaintenanceDeduction();
$cardSetting = getCardSetting();
        return view('admin.card-monthly-maintenance-deduction.create', compact('cardMonthlyMaintenanceDeduction', 'cardSetting'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function processDeduction(CardMonthlyMaintenanceDeductionRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        $cardCharges = new CardMaintenanceCharge();

        $activeCards = VirtualCard::where('is_active', 'Yes')->get();
        $cardSetting = getCardSetting();
        $maintenanceFees = $cardSetting->monthly_maintenance_fee;
        $exchangeRate =$cardSetting->exchange_rate;
        $deductedFees = $exchangeRate * $maintenanceFees;
        $cardCharges->batch_id = $request->batch_id;
        $cardCharges->maintenance_fees = $maintenanceFees;
        $cardCharges->exchange_rate = $exchangeRate;
        $cardCharges->deduction_month = $request->deduction_month;
        $cardCharges->deduction_year = $request->deduction_year;
        $cardCharges->billing_date = date('Y-m-d');
        $cardCharges->save();
        $totalDeductedAmount=0;
        $totalCountOncredit = 0;
        $totalCountPaid = 0;
        foreach($activeCards as $card){

            $cardFees = new CardMonthlyMaintenanceDeduction();
            $user = $card->user;
            $userWallet = Wallet::where('user_id',$user->id)->first();
            //check if wallet has blaance
            if ($userWallet->balance >= $deductedFees) {
                // Deduct entirely from the main balance
                $userWallet->balance -= $deductedFees;
              //  $cardFees->deducted_amount = $deductedFees;
                $cardFees->deducted_from = 'balance';
                $cardFees->status = 'paid';
                $cardFees->remarks = 'Deduction from balance';
                $totalCountPaid++;
            } elseif ($userWallet->balance < $deductedFees && $userWallet->balance > 0 && ($userWallet->balance + $userWallet->refer_bonus_balance) >= $deductedFees) {
                // Deduct partially from balance and the rest from refer bonus balance
                $remainingFees = $deductedFees - $userWallet->balance;
                $userWallet->balance = 0;
                $userWallet->refer_bonus_balance -= $remainingFees;
               // $cardFees->deducted_amount = $deductedFees;
                $cardFees->deducted_from = 'balance & bonus_balance';
                $cardFees->status = 'paid';
                $cardFees->remarks = 'Partial deduction from balance and bonus balance';
                $totalCountPaid++;
            } elseif ($userWallet->refer_bonus_balance >= $deductedFees) {
                // Deduct entirely from the refer bonus balance
                $userWallet->refer_bonus_balance -= $deductedFees;
              //  $cardFees->deducted_amount = $deductedFees;
                $cardFees->deducted_from = 'bonus_balance';
                $cardFees->status = 'paid';
                $cardFees->remarks = 'Deduction from bonus balance';
                $totalCountPaid++;
            } else {
                // Insufficient funds: Make the wallet negative
              //  $totalFunds = $userWallet->balance + $userWallet->refer_bonus_balance;
               // $remainingAmount = $deductedFees - $totalFunds;

                $userWallet->balance -= $deductedFees;
                $cardFees->status = 'paidoncredit';
                $cardFees->remarks = 'Deduction from balance on credit';
                $totalCountOncredit++;


                $cardFees->deducted_amount = $deductedFees;
                $cardFees->deducted_from = 'balance';
                $cardFees->status = 'paidoncredit';
                $cardFees->remarks = 'Deduction with insufficient funds, wallet balance went negative';
            }
            $cardFees->card_id = $card->id;
            $cardFees->user_id = $card->user_id;
            $cardFees->batch_id = $request->batch_id;
            $cardFees->maintenance_fee = $maintenanceFees;
            $cardFees->deducted_amount = $deductedFees;
            $totalDeductedAmount+=$deductedFees;
            if($cardFees->save()){
                $userWallet->save();
                TransactionHistory::create([
                    'descriptions' =>'Monthly Card Maintenance Fees for '.$request->deduction_month.' '.$request->deduction_year,
                    'trade_id' => null,
                    'request_id' =>$cardCharges->id,
                    'tradedcard_details_id' => null,
                    'transaction_ref' =>$cardCharges->batch_id,
                    'user_id' => $cardFees->user_id,
                    'amount' =>$deductedFees,
                    'exchange_rate'=>$exchangeRate,
                    'transaction_amount_in_usd'=>$maintenanceFees,
                    'transaction_type' => 'Debit',
                    'created_by' => auth()->user()->id,
                    'source' => 'Virtual Card',
                    'status' => 'success',
                    'status_at' => now(),
                    'status_by' => auth()->user()->id,
                    'status_reason' =>  $cardFees->remarks,

                    'rate' => null,
                    'currency' => "NGN",
                ]);


            }


        }
        $cardCharges->total_deducted_amount = $totalDeductedAmount;
        $cardCharges->total_count_in_paid = $totalCountPaid;
        $cardCharges->total_count_in_credit= $totalCountOncredit;
        $cardCharges->save();


        return Redirect::route('admin.card-maintenance.batch-list')
            ->with('success', 'Process successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show($id): View
    {
        $cardMonthlyMaintenanceDeduction = CardMonthlyMaintenanceDeduction::find($id);

        return view('card-monthly-maintenance-deduction.show', compact('cardMonthlyMaintenanceDeduction'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id): View
    {
        $cardMonthlyMaintenanceDeduction = CardMonthlyMaintenanceDeduction::find($id);

        return view('card-monthly-maintenance-deduction.edit', compact('cardMonthlyMaintenanceDeduction'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(CardMonthlyMaintenanceDeductionRequest $request, CardMonthlyMaintenanceDeduction $cardMonthlyMaintenanceDeduction): RedirectResponse
    {
        $cardMonthlyMaintenanceDeduction->update($request->validated());

        return Redirect::route('card-monthly-maintenance-deductions.index')
            ->with('success', 'CardMonthlyMaintenanceDeduction updated successfully');
    }

    public function destroy($id): RedirectResponse
    {
        CardMonthlyMaintenanceDeduction::find($id)->delete();

        return Redirect::route('card-monthly-maintenance-deductions.index')
            ->with('success', 'CardMonthlyMaintenanceDeduction deleted successfully');
    }
}
