<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\admin\user\CreateUserRequest;
use App\Http\Requests\admin\user\UpdateUserRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UsersController extends Controller
{
    public function index(Request $request)
    {
        $query = User::select('id', 'name', 'email', 'mobile', 'is_admin')
            ->with(['userSubscribers' => function ($q) {
                $q->where('expired_at', '>=', now());
            }]);

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where(function ($qry) use ($q) {
                $qry->where('name', 'like', "%{$q}%")
                    ->orWhere('email', 'like', "%{$q}%")
                    ->orWhere('mobile', 'like', "%{$q}%");
            });
        }
        if ($request->filled('type') && in_array($request->type, ['0', '1'])) {
            $query->where('is_admin', (bool) $request->type);
        }

        $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
        $users = $query->paginate($perPage)->withQueryString();

        return view('admin.users.index', compact('users'));
    }

    public function create()
    {
        return view('admin.users.create');
    }

    public function store(CreateUserRequest $request)
    {
        $validated = $request->validated();
        $validated['password'] = Hash::make(fake()->password);
        $validated['is_admin'] = $validated['is_admin'] == 'on' ? true : false;
        User::query()->create($validated);

        return redirect(route('users.index'));
    }

    public function edit(User $user)
    {
        return view('admin.users.update', compact('user'));
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $validated = $request->validated();
        $validated['is_admin'] = $validated['is_admin'] == 'on' ? true : false;
        $user->update($validated);

        return redirect(route('users.index'));
    }

    public function destroy(User $user)
    {
        $user->delete();

        return back();
    }
}
