<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserPermissionModel;
use App\Models\PermissionsModel;
use App\Models\PermissionRolesModel;
use App\Models\RoleModel;

class UserPermissionController extends Controller
{
    public function edit($id)
    {
        $getPermissions = PermissionsModel::getRecords();
        $data['getPermissions'] = $getPermissions;
        $data['getRolesPermissions'] = PermissionRolesModel::getRolePermissions($id);
        $data['getRecord'] = RoleModel::getRecord($id);
        $permissions = PermissionsModel::getRecords();
        $userPermissions = UserPermissionModel::where('user_id', $id)->get();

        return view("users.editpermissions", $data ,compact("id"));
    }

    public function update(Request $request, $id)
    {
        $permissions = $request->input('permissions', []);

        // Remove existing user-specific permissions
        UserPermissionModel::where('user_id', $id)->delete();

        // Add new user-specific permissions
        foreach ($permissions as $permissionId => $hasPermission) {
            UserPermissionModel::create([
                'user_id' => $id,
                'permission_id' => $permissionId,
                'has_permission' => $hasPermission,
            ]);
        }

        return redirect()->back()->with('success', 'User permissions updated successfully!');
    }
}
