<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bonus;
use App\Models\PaymentSettings;
use App\Models\User;
use App\Models\RechargeSummery;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AdminRechargeManagementController extends Controller
{
    public function RechargeManagement()
    {
        $recharges = RechargeSummery::with(['user'])->latest()->paginate(10);
        return view('adminDashboard.recharge-management', compact('recharges'));
    }

    public static function giveFirstTimeBonus($user_id, $recharge_amount)
    {
        // Check if it's the user's first recharge
        $recharge_summery_count = RechargeSummery::where(['user_id' => $user_id, 'status' => 1])->count();
        $user = User::find($user_id);

        // Determine bonus percentage and check if the user is eligible for the first or subsequent recharge bonus
        $paymenSettings = PaymentSettings::first();
        if ($recharge_summery_count == 0) {
            $bonus_percentage = $paymenSettings->first_bonus;
        } elseif (env('EACH_RECHARGE_BONUS', false) && $paymenSettings->after_first_bonus != NULL && $paymenSettings->after_first_bonus > 0) {
            $bonus_percentage = $paymenSettings->after_first_bonus;
        } else {
            return false;
        }

        // Calculate bonus and update user balance
        $bonus_amount = ($bonus_percentage / 100) * $recharge_amount;
        $total_balance = $recharge_amount + $bonus_amount;
        $user->increment('amount', $total_balance);

        // Save bonus record
        Bonus::create([
            'user_id' => $user_id,
            'bonus' => $bonus_amount,
            'amount' => $recharge_amount,
            'comment' => 'recharge',
            'bonus_user_id' => $user_id
        ]);

        return true;
    }


    public function ApproveRecharge($id)
    {
        $wallet_summary = RechargeSummery::find($id);
        if ($wallet_summary && $wallet_summary->status != 1) {
            // Check if the first-time bonus is applicable
            $isFirstTimeBonusGiven = $this::giveFirstTimeBonus($wallet_summary->user_id, $wallet_summary->amount);

            // Update the wallet summary status after first-time bonus
            if ($isFirstTimeBonusGiven) {
                $wallet_summary->update(['status' => 1]);
            } else {
                // If not first-time recharge, just increment the user's amount
                $user = User::where(['id' => $wallet_summary->user_id])->first();
                $user->increment('amount', $wallet_summary->amount);
                $wallet_summary->update(['status' => 1]);
            }

            // Check and give referral bonus if applicable
            $user = User::where(['id' => $wallet_summary->user_id])->first();
            if ($user && $user->rcode != null) {
                $this->giveBonus($user->rcode, $wallet_summary->amount, $user->id);
            }
        }

        return redirect()->back();
    }

    public function giveBonus($rcode, $amount, $user_id)
    {
        $payment_settings = PaymentSettings::first();
        $first_user = User::where(['owncode' => $rcode])->first();
        if ($first_user) {
            $exists = Bonus::where(['user_id' => $user_id, 'bonus_user_id' => $first_user->id, 'comment' => 'recharge'])->get();
            if (count($exists) == 0) {

                $bonus_amount = ($payment_settings->level1_recharge_bonus / 100) * $amount;
                if ($bonus_amount > 0) {
                    $bonus = new Bonus();
                    $bonus->user_id = $user_id;
                    $bonus->bonus = $bonus_amount;
                    $bonus->amount = $amount;
                    $bonus->comment = "recharge";
                    $bonus->bonus_user_id = $first_user->id;
                    $bonus->level1 = 1;
                    $bonus->save();
                    $first_user->increment('amount', $bonus_amount);
                }

                if ($first_user->rcode != null) {
                    $second_user = User::where(['owncode' => $first_user->rcode])->first();
                    if ($second_user) {
                        $exists = Bonus::where(['user_id' => $user_id, 'bonus_user_id' => $second_user->id, 'comment' => 'recharge'])->get();
                        if (count($exists) == 0) {
                            $bonus_amount = ($payment_settings->level2_recharge_bonus / 100) * $amount;
                            if ($bonus_amount > 0) {
                                $bonus = new Bonus();
                                $bonus->user_id = $user_id;
                                $bonus->bonus = $bonus_amount;
                                $bonus->amount = $amount;
                                $bonus->comment = "recharge";
                                $bonus->bonus_user_id = $second_user->id;
                                $bonus->level2 = 1;
                                $bonus->save();
                                $second_user->increment('amount', $bonus_amount);
                            }

                            if ($second_user->rcode != null) {
                                $third_user = User::where(['owncode' => $second_user->rcode])->first();
                                if ($third_user) {
                                    $exists = Bonus::where(['user_id' => $user_id, 'bonus_user_id' => $third_user->id, 'comment' => 'recharge'])->get();
                                    if (count($exists) == 0) {
                                        $bonus_amount = ($payment_settings->level3_recharge_bonus / 100) * $amount;
                                        if ($bonus_amount > 0) {
                                            $bonus = new Bonus();
                                            $bonus->user_id = $user_id;
                                            $bonus->bonus = $bonus_amount;
                                            $bonus->amount = $amount;
                                            $bonus->comment = "recharge";
                                            $bonus->bonus_user_id = $third_user->id;
                                            $bonus->level3 = 1;
                                            $bonus->save();
                                            $third_user->increment('amount', $bonus_amount);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function DisapproveRecharge(Request $request)
    {
        $request->validate([
            'reject_id' => 'required',
            'reason' => 'required'
        ]);

        $recharge = RechargeSummery::find($request->reject_id);
        if ($recharge) {
            $user = User::find($recharge->user_id);

            // Check if the recharge was approved (status 1) and decrement the amount and bonus
            if ($recharge->status == 1) {
                $user->decrement('amount', $recharge->amount);

                // Find and remove the bonus associated with this recharge
                $bonus = Bonus::where([
                    'user_id' => $recharge->user_id,
                    'amount' => $recharge->amount,
                    'comment' => 'recharge'
                ])->first();

                if ($bonus) {
                    $user->decrement('amount', $bonus->bonus);
                    $bonus->delete(); // Remove the bonus record
                }
            }

            // Update recharge status to 'disapproved' and save the reason
            $recharge->status = 2;
            $recharge->rejection_reason = $request->reason;
            $recharge->save();
        }

        return redirect()->back();
    }



    public function DeleteRecharge($id)
    {
        Log::info('Recharge deleted by admin id: ' . $id);
        $recharge = RechargeSummery::find($id);
        if ($recharge) {
            $recharge->delete();
        }
        return redirect()->back();
    }

    public function RechargeHistory(Request $request)
    {
        $request->validate([
            'user_mobile' => 'required'
        ]);
        $recharges = RechargeSummery::with(['user'])->whereRelation('user', 'mobile', 'like', '%' . $request->user_mobile . '%')->latest()->limit(100)->get();
        foreach ($recharges as $key => $recharge) {
            $recharges[$key]->created = date_format($recharge->created_at, "Y-m-d H:i:s");
        }
        return response()->json(['status' => 'success', 'recharges' => $recharges]);
    }
}
