<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyRoleRequest;
use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;

class RolesController extends Controller
{
    public function index()
    {
        abort_if(Gate::denies('role_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $roles = Role::with('permissions')->where('title', '!=', 'Super Admin')->get();

        return view('admin.roles.index', compact('roles'));
    }

    public function create()
    {
        abort_if(Gate::denies('role_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $permissions = Permission::all()->groupBy('module');

        return view('admin.roles.create', compact('permissions'));
    }


    public function store(StoreRoleRequest $request)
    {
        $role = Role::create($request->only('title'));
        $role->permissions()->sync($request->input('permissions', []));

        return redirect()->route('admin.roles.index')->with('success', 'Role created successfully.');
    }

    public function edit(Role $role)
    {
        abort_if(Gate::denies('role_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $permissions = Permission::all()->groupBy('module');

        $role->load('permissions');

        return view('admin.roles.edit', compact('role', 'permissions'));
    }

    public function update(UpdateRoleRequest $request, Role $role)
    {
        $role->update($request->only('title'));
        $role->permissions()->sync($request->input('permissions', []));

        return redirect()->route('admin.roles.index')->with('success', 'Role updated successfully.');
    }

    public function show(Role $role)
    {
        abort_if(Gate::denies('role_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $role->load('permissions');
        return view('admin.roles.show', compact('role'));
    }

    public function destroy(Role $role)
    {
        abort_if(Gate::denies('role_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        // Check if any user is assigned this role
        $userCount = $role->users()->count(); // assumes Role has users() relationship
        if ($userCount > 0) {
            return response()->json([
                'success' => false,
                'message' => "Role '{$role->title}' cannot be deleted because it is assigned to {$userCount} user(s)."
            ]);
        }

        $role->delete();

        return response()->json([
            'success' => true,
            'message' => "Role '{$role->title}' has been deleted successfully!"
        ]);
    }


    public function massDestroy(MassDestroyRoleRequest $request)
    {
        $roles = Role::whereIn('id', request('ids'))->get();
        $deletedCount = 0;
        $skippedRoles = [];

        foreach ($roles as $role) {
            $userCount = $role->users()->count();
            if ($userCount > 0) {
                $skippedRoles[] = $role->title;
                continue; // skip deletion
            }

            $role->delete();
            $deletedCount++;
        }

        $message = "{$deletedCount} role(s) deleted successfully.";
        if (!empty($skippedRoles)) {
            $message .= " Skipped roles assigned to users: " . implode(', ', $skippedRoles);
        }

        return response()->json([
            'success' => true,
            'message' => $message
        ]);
    }
}
