<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolePermissionController extends Controller
{
    private const PROTECTED_ROLE_NAMES = ['super-admin', 'superadmin'];

    private function normalizeRoleName(string $name): string
    {
        return str_replace('_', '-', strtolower(trim(preg_replace('/\s+/', ' ', $name))));
    }

    private function isProtectedRole(Role $role): bool
    {
        return in_array($this->normalizeRoleName($role->name), self::PROTECTED_ROLE_NAMES, true);
    }

    private function abortIfProtected(Role $role)
    {
        if ($this->isProtectedRole($role)) {
            return response()->json([
                'success' => false,
                'message' => 'This role is protected and cannot be modified.',
            ], 403);
        }

        return null;
    }

    //* INDEX */
    public function index()
    {
        $roles = Role::latest()->get();
        $permissions = Permission::all();
        return view('backend.roles_permissions.index', compact('roles', 'permissions'));
    }

    //* STORE */
    public function store(Request $request)
    {
        $request->validate([
            'name'   => 'required|string|max:255|unique:roles,name',
            'status' => 'required|boolean',
        ]);

        $role = Role::create([
            'name'       => $request->name,
            'guard_name' => 'web',
            'status'     => $request->status,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Role created successfully!',
            'role'    => $role,
            'is_protected' => $this->isProtectedRole($role),
        ]);
    }

    //* EDIT (fetch single role for modal) */
    public function edit(Role $role)
    {
        return response()->json([
            'success' => true,
            'is_protected' => $this->isProtectedRole($role),
            'role'    => $role,
        ]);
    }

    //* UPDATE */
    public function update(Request $request, Role $role)
    {
        if ($response = $this->abortIfProtected($role)) {
            return $response;
        }

        $request->validate([
            'name'   => ['required', 'string', 'max:255', Rule::unique('roles', 'name')->ignore($role->id)],
            'status' => 'required|boolean',
        ]);

        $role->update([
            'name'   => $request->name,
            'status' => $request->status,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Role updated successfully!',
        ]);
    }

    //* DESTROY */
    public function destroy(Role $role)
    {
        if ($response = $this->abortIfProtected($role)) {
            return $response;
        }

        $role->delete();

        return response()->json([
            'success' => true,
            'message' => 'Role deleted successfully!',
        ]);
    }

    //* GET ROLE PERMISSIONS */
    public function getPermissions(Role $role)
    {
        $rolePermissions = $role->permissions->pluck('id')->toArray();
        $allPermissions = Permission::all();

        return response()->json([
            'success' => true,
            'rolePermissions' => $rolePermissions,
            'allPermissions' => $allPermissions,
            'is_protected' => $this->isProtectedRole($role),
        ]);
    }

    //* ASSIGN PERMISSIONS TO ROLE */
    public function assignPermissions(Request $request, Role $role)
    {
        if ($response = $this->abortIfProtected($role)) {
            return $response;
        }

        $request->validate([
            'permissions' => 'required|array',
            'permissions.*' => 'exists:permissions,id',
        ]);

        // Use the many-to-many relationship directly
        $role->permissions()->sync($request->permissions);

        return response()->json([
            'success' => true,
            'message' => 'Permissions assigned successfully!',
        ]);
    }

    //* GET ROLE USERS */
    public function getUsers(Role $role, Request $request)
    {
        $search = $request->get('search', '');
        $limit = $request->get('limit', 5);

        $query = \App\Models\User::query();

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $allUsers = $query->take($limit)->get();
        $roleUsers = \App\Models\User::role($role->name)->pluck('id')->toArray();

        return response()->json([
            'success' => true,
            'roleUsers' => $roleUsers,
            'allUsers' => $allUsers,
            'is_protected' => $this->isProtectedRole($role),
        ]);
    }

    //* ASSIGN USERS TO ROLE */
    public function assignUsers(Request $request, Role $role)
    {
        if ($response = $this->abortIfProtected($role)) {
            return $response;
        }

        $request->validate([
            'users' => 'required|array',
            'users.*' => 'exists:users,id',
        ]);

        // Get current users with this role
        $currentUsers = \App\Models\User::role($role->name)->get();

        // Remove role from users not in the list
        foreach ($currentUsers as $user) {
            if (!in_array($user->id, $request->users)) {
                $user->removeRole($role->name);
            }
        }

        // Assign role to selected users
        $users = \App\Models\User::whereIn('id', $request->users)->get();
        foreach ($users as $user) {
            $user->assignRole($role->name);
        }

        return response()->json([
            'success' => true,
            'message' => 'Users assigned successfully!',
        ]);
    }
}
