<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Organization;
use App\Models\Role;
use App\Models\User;
use App\Support\Authorization\PermissionCatalog;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Spatie\Permission\PermissionRegistrar;

class UserController extends Controller
{
    public function index()
    {
        $users = User::with('mariachiGroup')
            ->where('role', User::ROLE_CLIENT)
            ->orderByDesc('id')
            ->get();

        $stats = [
            'total' => $users->count(),
            'active' => $users->where('is_active', true)->count(),
            'inactive' => $users->where('is_active', false)->count(),
            'with_mariachi_group' => $users->whereNotNull('organization_id')->count(),
        ];

        return view('content.admin.users.index', [
            'users' => $users,
            'mariachiGroups' => Organization::orderBy('name')->get(),
            'stats' => $stats,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
            'mariachi_group_id' => ['nullable', Rule::exists('organizations', 'id')],
            'is_active' => ['required', 'boolean'],
        ]);

        $validated['role'] = User::ROLE_CLIENT;
        $validated['staff_role'] = null;
        $validated['organization_id'] = $validated['mariachi_group_id'] ?? null;
        $validated['has_all_mariachi_groups'] = true;
        unset($validated['mariachi_group_id']);

        $user = User::create($validated);

        if (!empty($user->organization_id)) {
            $ownerRole = Role::query()->firstOrCreate(
                [
                    'code' => PermissionCatalog::ownerSystemRoleCode((int) $user->organization_id),
                    'guard_name' => 'web',
                ],
                [
                    'name' => 'OWNER',
                    'organization_id' => (int) $user->organization_id,
                    'is_system' => true,
                    'is_active' => true,
                ]
            );
            $ownerRole->syncPermissions(PermissionCatalog::permissionNamesForPanel(PermissionCatalog::PANEL_OWNER));

            app(PermissionRegistrar::class)->setPermissionsTeamId($user->organization_id);
            $user->syncRoles([$ownerRole]);
        }

        return redirect()->route('admin.users.index')->with('status', 'Propietario creado correctamente.');
    }

    public function deactivate(User $user)
    {
        if ($user->role !== User::ROLE_CLIENT) {
            abort(404);
        }

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

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