<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules;

class UserController extends Controller
{
    public function getUsers(Request $request): JsonResponse
    {
        $q = User::query()
            ->leftJoin('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
            ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
            ->selectRaw('
            users.*,
            roles.name role
        ')
            ->where(['estatus' => 'activo']);

        $users = $q->get();

        return response()->json([
            'data' => $users->load('roles'),
        ], JsonResponse::HTTP_OK);
    }

    public function registro(Request $request): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', Rule::unique('users')],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'estatus' => 'activo',
        ]);

        if (\Spatie\Permission\Models\Role::where('name', User::CAPORAL_ROL)->where('guard_name', 'web')->exists()) {
            $user->assignRole(User::CAPORAL_ROL);
        }

        return response()->json([
            'data' => $user->load('roles'),
        ], JsonResponse::HTTP_CREATED);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'role' => ['required', Rule::exists('roles', 'name')],
            'email' => ['required', 'email', Rule::unique('users')->where(function ($query) {
                return $query->whereNotIn('estatus', ['inactivo']);
            })],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'estatus' => 'activo',
        ]);

        $user->assignRole($request->role);

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function update(Request $request, User $user): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'role' => ['required', Rule::exists('roles', 'name')],
            'email' => ['required', 'email', Rule::unique('users')->where(function ($query) use ($user) {
                return $query->whereNotIn('id', [$user->id])->whereNotIn('estatus', ['inactivo']);
            })],
        ]);

        $user->update($request->only(['name', 'email']));

        if (! $user->hasRole($request->role)) {
            foreach ($user->getRoleNames() as $role) {
                $user->removeRole($role);
            }
            $user->assignRole($request->role);
        }

        return response()->json([
            'data' => $user->fresh()->load('roles'),
        ], JsonResponse::HTTP_OK);
    }

    public function updatePassword(Request $request, User $user): JsonResponse
    {
        $request->validate([
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function updatePerfil(Request $request): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255'],
        ]);

        $request->user()->update($request->only([
            'name',
            'email',
        ]));

        return response()->json([
            'data' => $request->user(),
        ], JsonResponse::HTTP_OK);
    }

    public function getUser(User $user): JsonResponse
    {
        return response()->json([
            'data' => $user->load('roles'),
        ], JsonResponse::HTTP_OK);
    }

    public function destroy(User $user): JsonResponse
    {
        $user->update([
            'estatus' => 'inactivo',
        ]);

        return response()->json(null, JsonResponse::HTTP_NO_CONTENT);
    }
}
