<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
use Illuminate\Http\Request;
use App\Traits\CrudTrait;
use Spatie\Permission\Models\Role;

class PermissionController extends Controller
{
    use CrudTrait;
    protected string $dataType = 'object';
    protected string $modelClass = Permission::class;

    public function index(Request $request)
    {
        return $this->getData($request);
    }

    public function store(Request $request)
    {
        return $this->storeData($request);
    }

    public function bulkStore(Request $request)
    {
        return $this->bulkStore($request);
    }

    public function update(Request $request)
    {
        return $this->updateData($request);
    }

    public function bulkUpdate(Request $request)
    {
        return $this->multiUpdate($request);
    }

    public function destroy(Request $request)
    {
        return $this->destroyData($request);
    }

    public function bulkDestory(Request $request)
    {
        return $this->bulkDelete($request);
    }

    public function clone(Request $request)
    {
        return $this->cloneData($request);
    }

    public function export(Request $request)
    {
        return $this->exportData($request);
    }

    public function import(Request $request)
    {
        return $this->importData($request);
    }

    public function upload(Request $request)
    {
        return $this->uploadFile($request);
    }

    public function download(Request $request)
    {
        return $this->downloadFile($request);
    }

    /**
     * @OA\Get(
     *     path="/api/amenity/listnames",
     *     summary="Get amenities as list of names",
     *     tags={"Amenity"},
     *     @OA\Response(
     *         response=200,
     *         description="Array of names"
     *     )
     * )
     */
    public function getDataAsArrayOfNames(Request $request)
    {
        return $this->getDataAsArray($request);
    }

    public function getAllPermissionsRegrouped(Request $request)
    {
        $roleId = $request->input('role_id'); // جلب role_id من request
        $role   = Role::findOrFail($roleId);  // نجيبو role

        $permissions = Permission::all();
        $groups = [];

        foreach ($permissions as $perm) {
            [$module, $action] = explode('-', $perm->name);

            if (!isset($groups[$perm->group])) {
                $groups[$perm->group] = [
                    'group' => $perm->group,
                    'modulePermission' => []
                ];
            }

            if (!isset($groups[$perm->group]['modulePermission'][$module])) {
                $groups[$perm->group]['modulePermission'][$module] = [
                    'module' => $module,
                    'permissions' => []
                ];
            }

            // تحقق واش هاد الـrole عندو هاد الـpermission
            $isAuthorized = $role->hasPermissionTo($perm->name);

            $groups[$perm->group]['modulePermission'][$module]['permissions'][] = [
                'id'        => $perm->id,
                'action'    => $action,
                'authorized' => $isAuthorized
            ];
        }

        foreach ($groups as &$group) {
            $group['modulePermission'] = array_values($group['modulePermission']);
        }

        return response()->json(array_values($groups));
    }

    public function assignPermissionsToRole(Request $request)
    {
        $data = $request->validate([
            'role_id'        => 'required|integer|exists:roles,id',
            'permission_ids' => 'required|array',
            'permission_ids.*' => 'integer|exists:permissions,id',
        ]);

        $role = Role::findOrFail($data['role_id']);

        // نديرو syncPermissions باش يعوض القديم بالجديد
        $role->syncPermissions($data['permission_ids']);

        return response()->json([
            'success' => true,
            'message' => 'Permissions assigned successfully',
            'role' => $role->name,
            'permissions' => $role->permissions()->pluck('name')
        ]);
    }
}
