<?php

namespace App\Http\Controllers;

use App\Http\Requests\Admin\StoreUserRequest;
use App\Http\Requests\Admin\UpdateUserRequest;
use App\Models\Group;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class UserController extends Controller
{
    /**
     * Daftar pengguna (FR-USR-01).
     */
    public function index(Request $request): Response
    {
        $users = User::with('groups')
            ->when($request->string('search')->toString(), fn ($q, $search) => $q
                ->where('name', 'like', "%{$search}%")
                ->orWhere('email', 'like', "%{$search}%")
                ->orWhere('username', 'like', "%{$search}%"))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return Inertia::render('users/Index', [
            'users' => $users,
            'filters' => $request->only(['search']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('users/Create', [
            'groups' => Group::orderBy('name')->get(['id', 'name', 'description']),
        ]);
    }

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

        $user = User::create([
            'name' => $data['name'],
            'first_name' => $data['first_name'] ?? null,
            'last_name' => $data['last_name'] ?? null,
            'company' => $data['company'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'],
            'username' => $data['username'] ?? null,
            'password' => $data['password'],
            'credit' => $data['credit'] ?? 0,
            'status' => $data['status'] ?? 'active',
        ]);

        $this->syncGroups($user, $data['groups'] ?? []);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Pengguna berhasil dibuat.')]);

        return to_route('users.index');
    }

    public function edit(User $user): Response
    {
        return Inertia::render('users/Edit', [
            'user' => $user->load('groups'),
            'groups' => Group::orderBy('name')->get(['id', 'name', 'description']),
        ]);
    }

    public function update(UpdateUserRequest $request, User $user): RedirectResponse
    {
        $data = $request->validated();

        $user->fill([
            'name' => $data['name'],
            'first_name' => $data['first_name'] ?? null,
            'last_name' => $data['last_name'] ?? null,
            'company' => $data['company'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'],
            'username' => $data['username'] ?? null,
            'credit' => $data['credit'] ?? $user->credit,
            'status' => $data['status'] ?? $user->status,
        ]);

        if (! empty($data['password'])) {
            $user->password = $data['password'];
        }

        $user->save();
        $this->syncGroups($user, $data['groups'] ?? []);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Pengguna berhasil diperbarui.')]);

        return to_route('users.index');
    }

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

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Pengguna berhasil dihapus.')]);

        return to_route('users.index');
    }

    /**
     * Sinkronkan keanggotaan grup (FR-USR-02).
     *
     * @param  array<int, string>  $groupNames
     */
    private function syncGroups(User $user, array $groupNames): void
    {
        if (empty($groupNames)) {
            return;
        }

        $groupIds = Group::whereIn('name', $groupNames)->pluck('id')->all();
        $user->groups()->sync($groupIds);
    }
}
