<?php

namespace App\Modules\PLATFORM\UserManagement\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{
    public function index()
    {
        $roles = Role::where('name', '!=', 'super-admin')->get();
        return view('user-management::roles.index', compact('roles'));
    }

    public function create()
    {
        $permissionsByModule = Permission::orderBy('module')
            ->orderBy('submodule')
            ->get()
            ->groupBy(['module', 'submodule']);

        return view('user-management::roles.create', compact('permissionsByModule'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:roles,name',
            'permissions' => 'required|array|min:1'
        ], [
            'name.required' => 'Role name is required.',
            'name.max' => 'Role name must not exceed 255 characters.',
            'name.unique' => 'This role name already exists. Please choose a different name.',
            'permissions.required' => 'Please select at least one permission.',
            'permissions.array' => 'Permissions must be an array.',
            'permissions.min' => 'Please select at least one permission.',
        ]);

        DB::transaction(function () use ($request) {
            $role = Role::create(['name' => $request->name, 'guard_name' => 'web']);
            $role->syncPermissions($request->permissions);
        });

        return response()->json(['status' => true, 'message' => 'Role created successfully']);
    }

    public function edit(Role $role)
    {
        if ($role->name === 'super-admin') {
            abort(403, 'Super Admin role cannot be edited');
        }

        $permissionsByModule = Permission::orderBy('module')
            ->orderBy('submodule')
            ->get()
            ->groupBy(['module', 'submodule']);

        $rolePermissions = $role->permissions->pluck('id')->toArray();

        return view('user-management::roles.edit', compact('role', 'permissionsByModule', 'rolePermissions'));
    }

    public function update(Request $request, Role $role)
    {
        if ($role->name === 'super-admin') {
            abort(403, 'Super Admin role cannot be edited');
        }

        $request->validate([
            'name' => 'required|string|max:255|unique:roles,name,' . $role->id,
            'permissions' => 'required|array|min:1'
        ], [
            'name.required' => 'Role name is required.',
            'name.max' => 'Role name must not exceed 255 characters.',
            'name.unique' => 'This role name already exists. Please choose a different name.',
            'permissions.required' => 'Please select at least one permission.',
            'permissions.array' => 'Permissions must be an array.',
            'permissions.min' => 'Please select at least one permission.',
        ]);

        DB::transaction(function () use ($request, $role) {
            $role->update(['name' => $request->name]);
            $role->syncPermissions($request->permissions);
        });

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

    public function destroy(Role $role)
    {
        if ($role->name === 'super-admin') {
            abort(403, 'Super Admin role cannot be deleted');
        }

        // Check if role has users assigned
        $usersCount = DB::table('model_has_roles')
            ->where('role_id', $role->id)
            ->count();

        if ($usersCount > 0) {
            return response()->json([
                'status'  => false,
                'message' => 'Cannot delete this role. It is currently assigned to ' . $usersCount . ' user(s). Please remove or reassign all users before deleting this role.',
            ], 422);
        }

        // If no users assigned, allow deletion
        $role->delete();

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