<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreUserRequest;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Inertia\Inertia;
use Inertia\Response;

class UserRoleController extends Controller
{
    public function index(Request $request): Response
    {
        Gate::authorize('manage-settings');

        $users = User::with('roles:id,slug,name')->orderBy('name')->get(['id', 'name', 'email', 'active', 'login_redirect']);
        $roles = Role::with('permissions:id,slug,name')->orderBy('name')->get(['id', 'name', 'slug']);
        $permissions = Permission::orderBy('slug')->get(['id', 'name', 'slug']);

        return Inertia::render('Admin/Users/Index', [
            'users' => $users,
            'roles' => $roles,
            'permissions' => $permissions,
        ]);
    }

    public function store(StoreUserRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
        ]);

        if (! empty($validated['roles'])) {
            $user->roles()->sync($validated['roles']);
        }

        return back()->with('success', 'Uporabnik uspešno ustvarjen');
    }

    public function update(Request $request, User $user): RedirectResponse
    {
        Gate::authorize('manage-settings');

        $validated = $request->validate([
            'roles' => ['array'],
            'roles.*' => ['integer', 'exists:roles,id'],
        ]);

        $user->roles()->sync($validated['roles'] ?? []);

        return back()->with('success', 'Roles updated');
    }

    public function toggleActive(User $user): RedirectResponse
    {
        Gate::authorize('manage-settings');

        $user->active = ! $user->active;
        $user->save();

        $status = $user->active ? 'aktiviran' : 'deaktiviran';

        return back()->with('success', "Uporabnik {$status}");
    }

    public function updateSettings(Request $request, User $user): RedirectResponse
    {
        Gate::authorize('manage-settings');

        $validated = $request->validate([
            'login_redirect' => ['nullable', 'string', 'max:255'],
        ]);

        $user->update($validated);

        return back()->with('success', 'Nastavitve shranjene');
    }
}
