<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoginHistory;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\Permission\Models\Role;

class StaffController extends Controller
{
    public function index(Request $request): Response
    {
        $adminRoles = Role::where('guard_name', 'web')
            ->whereNotIn('name', ['customer'])
            ->pluck('name')
            ->toArray();

        $query = User::role($adminRoles)
            ->with('roles');

        // Search by name or email
        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search): void {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // Filter by role
        if ($role = $request->input('role')) {
            $query->role($role);
        }

        $staffMembers = $query
            ->orderBy('name')
            ->paginate(20)
            ->withQueryString();

        // Attach last login info
        $staffMembers->getCollection()->transform(function (User $user): User {
            $lastLogin = LoginHistory::query()
                ->forUser($user->id)
                ->where('success', true)
                ->latest()
                ->first();

            $user->setAttribute('last_login_at', $lastLogin?->created_at);
            $user->setAttribute('last_login_ip', $lastLogin?->ip_address);
            $user->setAttribute('role_names', $user->roles->pluck('name')->toArray());

            return $user;
        });

        $roles = Role::where('guard_name', 'web')
            ->whereNotIn('name', ['customer'])
            ->withCount('users')
            ->get()
            ->map(fn (Role $role): array => [
                'name' => $role->name,
                'users_count' => $role->users_count,
            ]);

        return Inertia::render('Admin/Staff/Index', [
            'staff' => $staffMembers,
            'roles' => $roles,
            'filters' => [
                'search' => $request->input('search', ''),
                'role' => $request->input('role', ''),
            ],
        ]);
    }

    public function show(User $user): Response
    {
        $user->load(['roles.permissions']);

        $allPermissions = $user->getAllPermissions()->pluck('name')->sort()->values();
        $directPermissions = $user->getDirectPermissions()->pluck('name')->sort()->values();

        $loginHistories = LoginHistory::query()
            ->forUser($user->id)
            ->latest()
            ->limit(20)
            ->get();

        return Inertia::render('Admin/Staff/Show', [
            'staffMember' => $user,
            'allPermissions' => $allPermissions,
            'directPermissions' => $directPermissions,
            'loginHistories' => $loginHistories,
        ]);
    }
}
