<?php

namespace App\Http\Controllers;

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

class PermissionController extends Controller
{
    public function modulePermission()
    {
        $role = Role::all();

        $role_has_permissions = DB::table('role_has_permissions')
            ->join('permissions', 'role_has_permissions.permission_id', '=', 'permissions.id')
            ->where('role_has_permissions.role_id', 2)
            ->get();

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

        return view('app.module-permission.index', compact('role', 'permissions', 'role_has_permissions'));
    }

    public function getPermissionByRole(Request $request)
    {
        $role_has_permissions = DB::table('role_has_permissions')
            ->join('permissions', 'role_has_permissions.permission_id', '=', 'permissions.id')
            ->where('role_has_permissions.role_id', $request->role_id)
            ->get();

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


        $html = view('app.module-permission.permission', compact('permissions', 'role_has_permissions'))->render();

        return response()->json(['html' => $html], 200);
    }

    public function updatePermission(Request $request)
    {
        $roleId = $request->role_id;
        $permissionIds = $request->permissions;

        $permissions = DB::table('role_has_permissions')
            ->where('role_id', $roleId)
            ->delete();

        foreach ($permissionIds as $permissionId) {
            $data[] = [
                'role_id' => $roleId,
                'permission_id' => $permissionId
            ];
        };

        DB::table('role_has_permissions')->insert($data);


        return response()->json(['message' => 'Permission updated successfully'], 200);
    }
}
