<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bonus;
use App\Models\RedEnvelope;
use App\Models\User;
use Illuminate\Http\Request;

class AdminRewardManagementController extends Controller
{
    public function RewardManagement()
    {
        $rewards = Bonus::where([
            'level1' => 0,
            'level2' => 0,
            'level3' => 0,
            'comment' => 'reward'
        ])->with(['bonusGivenTo'])->latest()->paginate(10);
        $users = User::where(['status' => 1])->where('role', '!=', 'admin')->get();
        return view('adminDashboard.reward-management', compact('rewards', 'users'));
    }

    public function SaveReward(Request $request)
    {
        $request->validate([
            'user_mobile' => 'required',
            'reward' => 'required'
        ]);

        $user = User::where(['mobile' => $request->user_mobile])->first();
        if (!$user) {
            return back()->with('status', 'User not found');
        }

        $user->amount += $request->reward;
        $user->save();

        $bonus = new Bonus();
        $bonus->bonus = $request->reward;
        $bonus->user_id = null;
        $bonus->bonus_user_id = $user->id;
        $bonus->comment = "reward";
        $bonus->save();

        User::where(['id' => $request->user_id])->increment('amount', $request->reward);
        return redirect()->back();
    }

    public function RedEnvelope()
    {
        $envelopes = RedEnvelope::latest()->paginate(10);
        // prx($envelopes);
        return view('adminDashboard.red-envelope', compact('envelopes'));
    }

    public function RedEnvelopeActive($id)
    {
        $envelope = RedEnvelope::find($id);
        if ($envelope) {
            $envelope->status = 1;
            $envelope->save();
        }
        return redirect()->back();
    }

    public function RedEnvelopeInactive($id)
    {
        $envelope = RedEnvelope::find($id);
        if ($envelope) {
            $envelope->status = 0;
            $envelope->save();
        }
        return redirect()->back();
    }

    public function SaveRedEnvelope(Request $request)
    {
        $request->validate([
            'user_limit' => 'required',
            'amount' => 'required'
        ]);
        $envelope = new RedEnvelope();
        $envelope->amount = $request->amount;
        $envelope->user_limit = $request->user_limit;
        $envelope->remaining = $request->user_limit;
        $envelope->status = 1;
        $envelope->link_code = time();
        $envelope->save();

        return redirect()->back();
    }
}
