<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\StaffRole;
use App\Models\User;
use App\Support\Authorization\PermissionCatalog;
use Illuminate\Http\Request;
use Spatie\Permission\PermissionRegistrar;

class TeamController extends Controller
{
    private function activeStaffRoles()
    {
        return StaffRole::query()
            ->platform()
            ->custom()
            ->where('is_active', true)
            ->orderBy('name')
            ->get();
    }

    public function index()
    {
        $users = User::query()
            ->whereIn('role', User::adminRoles())
            ->orderByDesc('id')
            ->get();
        $users->each(fn (User $user) => $user->setAttribute('current_role_name', $user->platformRoleName()));

        $staffRoles = $this->activeStaffRoles();

        $stats = [
            'total' => $users->count(),
            'active' => $users->where('is_active', true)->count(),
            'inactive' => $users->where('is_active', false)->count(),
            'admins' => $users->where('role', User::ROLE_ADMIN)->count(),
        ];

        return view('content.admin.team.index', [
            'users' => $users,
            'staffRoles' => $staffRoles,
            'stats' => $stats,
        ]);
    }

    public function store(Request $request)
    {
        $staffRoleCodes = $this->activeStaffRoles()->pluck('code')->all();

        if (empty($staffRoleCodes)) {
            return redirect()->route('admin.roles.index')->withErrors([
                'name' => 'Primero crea al menos un Staff Role para poder agregar miembros del equipo.',
            ]);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
            'staff_role' => ['required', 'string', 'in:' . implode(',', $staffRoleCodes)],
            'is_active' => ['required', 'boolean'],
        ]);

        $staffRoleCode = $validated['staff_role'];
        unset($validated['staff_role']);
        $validated['role'] = User::ROLE_STAFF;
        $validated['organization_id'] = null;
        $validated['has_all_mariachi_groups'] = false;

        $user = User::create($validated);
        $role = StaffRole::query()
            ->where('code', $staffRoleCode)
            ->whereNull('organization_id')
            ->firstOrFail();

        app(PermissionRegistrar::class)->setPermissionsTeamId(PermissionCatalog::GLOBAL_TEAM_ID);
        $user->syncRoles([$role]);
        $user->update(['staff_role' => $role->code]);

        return redirect()->route('admin.team.index')->with('status', 'Miembro de equipo creado correctamente.');
    }

    public function deactivate(User $user)
    {
        if (!in_array($user->role, User::adminRoles(), true)) {
            abort(404);
        }

        $user->update(['is_active' => false]);

        return redirect()->route('admin.team.index')->with('swal_success', 'Miembro desactivado correctamente.');
    }
}
