<?php

namespace App\Http\Controllers\Admin;

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

class AgentController extends Controller
{
    public function index()
    {
        $agents = User::agents()
            ->where('name', 'LIKE', '%' . request()->query('search', '') . '%')
            ->whereDate('created_at', 'LIKE', '%' . request()->query('datetime', '') . '%')
            ->latest('updated_at')->paginate();
        return view('admin.agents.index', compact('agents'));
    }

    public function createOrUpdate(Request $request, $id = null)
    {
        $agent = $id ? User::findOrFail($id) : new User();

        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|unique:users,phone,' . $id,
            'password' => $id ? 'nullable|string|min:8' : 'required|string|min:8',
        ]);

        $agent->name = $request->input('name');
        $agent->phone = $request->input('phone');
        $agent->password = bcrypt($request->input('password'));
        $agent->role = 'agent';
        $agent->save();

        return redirect()->route('agents.index')->with('success', 'Agent created successfully.');;
    }

    public function create()
    {
        return view('admin.agents.create-or-update');
    }

    public function edit($id)
    {
        $agent = User::agents()->findOrFail($id);
        return view('admin.agents.create-or-update', compact('agent'));
    }

    public function store(Request $request)
    {
        return $this->createOrUpdate($request);
    }
    public function show($id)
    {
        $agent = User::agents()->with('bettings.details')->findOrFail($id);
        return view('admin.agents.show', compact('agent'));
    }

    public function update(Request $request, $id)
    {
        return $this->createOrUpdate($request, $id);
    }

    public function destroy($id)
    {
        $agent = User::findOrFail($id);
        if ($agent->bettings()->count() > 0) {
            return back()->with('error', 'Agent is associated with games. Unable to delete.');
        }
        $agent->delete();
        return redirect()->route('agents.index')->with('success', 'Agent deleted successfully.');
    }

    public function toggleBlock($agent)
    {
        $user = User::findOrFail($agent);
        $user->update(['is_blocked' => !$user->is_blocked]);
        if ($user->is_blocked) {
            $user->tokens()->delete();
        }
        return response()->json("Game favourite changed successfully", 200);
    }
}
