<?php
/**
 * ACL_Controller — REST API برای سیستم دسترسی‌های یکپارچه
 *
 * Endpoints:
 *   GET    /acc/v1/acl/permissions            لیست همه مجوزها
 *   GET    /acc/v1/acl/roles                  لیست نقش‌ها
 *   POST   /acc/v1/acl/roles                  ساخت نقش جدید
 *   PUT    /acc/v1/acl/roles/{id}             ویرایش نقش
 *   DELETE /acc/v1/acl/roles/{id}             حذف نقش
 *   GET    /acc/v1/acl/roles/{id}/permissions مجوزهای نقش
 *   PUT    /acc/v1/acl/roles/{id}/permissions به‌روزرسانی مجوزها  body:{permissions:[]}
 *
 *   GET    /acc/v1/acl/users                  لیست کاربران با نقش‌هایشان
 *   GET    /acc/v1/acl/users/{id}/roles       نقش‌های کاربر
 *   POST   /acc/v1/acl/users/{id}/roles       اختصاص نقش body:{role_id, scope_type, scope_id}
 *   DELETE /acc/v1/acl/users/{id}/roles/{uid} حذف نقش از کاربر
 *
 *   GET    /acc/v1/acl/menus                  لیست همه منوها
 *   POST   /acc/v1/acl/menus                  افزودن منو
 *   PUT    /acc/v1/acl/menus/{id}             ویرایش منو
 *   DELETE /acc/v1/acl/menus/{id}             حذف منو
 *
 *   GET    /acc/v1/acl/me                     مجوزها و منوهای کاربر فعلی
 *   GET    /acc/v1/acl/module-registry         رجیستری ماژول و scope
 *   GET    /acc/v1/acl/profiles                پروفایل‌های آماده
 *   GET    /acc/v1/acl/users/{id}/profile      پروفایل دسترسی کاربر
 *   PUT    /acc/v1/acl/users/{id}/profile      ذخیره پروفایل دسترسی
 *   GET    /acc/v1/acl/scope-options/{type}    لیست اشیاء scope (انبار، پروژه، ...)
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class ACL_Controller {

    public static function register_routes(): void {
        $ns = 'acc/v1';
        $p  = 'acc_jwt_check_permission';
        $m  = function() { return acl_can( 'system.acl.manage' ); };

        // مجوزها (read only)
        register_rest_route( $ns, '/acl/permissions', [
            'methods' => 'GET', 'callback' => [self::class,'get_permissions'], 'permission_callback' => $p,
        ] );

        // نقش‌ها
        register_rest_route( $ns, '/acl/roles', [
            ['methods'=>'GET',  'callback'=>[self::class,'get_roles'],   'permission_callback'=>$p],
            ['methods'=>'POST', 'callback'=>[self::class,'create_role'], 'permission_callback'=>$m],
        ] );
        register_rest_route( $ns, '/acl/roles/(?P<id>\d+)', [
            ['methods'=>'PUT',    'callback'=>[self::class,'update_role'], 'permission_callback'=>$m],
            ['methods'=>'DELETE', 'callback'=>[self::class,'delete_role'], 'permission_callback'=>$m],
        ] );
        register_rest_route( $ns, '/acl/roles/(?P<id>\d+)/permissions', [
            ['methods'=>'GET', 'callback'=>[self::class,'get_role_permissions'], 'permission_callback'=>$p],
            ['methods'=>'PUT', 'callback'=>[self::class,'set_role_permissions'], 'permission_callback'=>$m],
        ] );

        // کاربران
        register_rest_route( $ns, '/acl/users', [
            'methods' => 'GET', 'callback' => [self::class,'get_users_with_roles'], 'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/acl/users/(?P<id>\d+)/roles', [
            ['methods'=>'GET',  'callback'=>[self::class,'get_user_roles'], 'permission_callback'=>$p],
            ['methods'=>'POST', 'callback'=>[self::class,'assign_user_role'], 'permission_callback'=>$m],
        ] );
        register_rest_route( $ns, '/acl/users/(?P<id>\d+)/roles/(?P<assignment_id>\d+)', [
            'methods'=>'DELETE', 'callback'=>[self::class,'remove_user_role'], 'permission_callback'=>$m,
        ] );

        // منوها
        register_rest_route( $ns, '/acl/menus', [
            ['methods'=>'GET',  'callback'=>[self::class,'get_menus'],   'permission_callback'=>$p],
            ['methods'=>'POST', 'callback'=>[self::class,'create_menu'], 'permission_callback'=>$m],
        ] );
        register_rest_route( $ns, '/acl/menus/(?P<id>\d+)', [
            ['methods'=>'PUT',    'callback'=>[self::class,'update_menu'], 'permission_callback'=>$m],
            ['methods'=>'DELETE', 'callback'=>[self::class,'delete_menu'], 'permission_callback'=>$m],
        ] );

        // کاربر فعلی
        register_rest_route( $ns, '/acl/me', [
            'methods' => 'GET', 'callback' => [self::class,'get_me'], 'permission_callback' => $p,
        ] );

        // overrides
        register_rest_route( $ns, '/acl/overrides', [
            ['methods'=>'GET',  'callback'=>[self::class,'get_overrides'], 'permission_callback'=>$p],
            ['methods'=>'POST', 'callback'=>[self::class,'set_override'],  'permission_callback'=>$m],
        ] );
        register_rest_route( $ns, '/acl/overrides/(?P<id>\d+)', [
            'methods'=>'DELETE', 'callback'=>[self::class,'delete_override'], 'permission_callback'=>$m,
        ] );

        // پروفایل دسترسی یکپارچه
        register_rest_route( $ns, '/acl/module-registry', [
            'methods' => 'GET', 'callback' => [self::class,'get_module_registry'], 'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/acl/profiles', [
            'methods' => 'GET', 'callback' => [self::class,'get_access_profiles'], 'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/acl/scope-options/(?P<type>[a-z_]+)', [
            'methods' => 'GET', 'callback' => [self::class,'get_scope_options'], 'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/acl/users/(?P<id>\d+)/profile', [
            ['methods'=>'GET', 'callback'=>[self::class,'get_user_profile'], 'permission_callback'=>$p],
            ['methods'=>'PUT', 'callback'=>[self::class,'save_user_profile'], 'permission_callback'=>$m],
        ] );
    }

    /* ── مجوزها ─────────────────────────────────────────────── */
    public static function get_permissions( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT * FROM {$wpdb->prefix}acl_permissions ORDER BY module, resource, action",
            ARRAY_A
        );
        // گروه‌بندی بر اساس ماژول
        $grouped = [];
        foreach ( $rows ?? [] as $r ) {
            $grouped[ $r['module'] ][] = $r;
        }
        return new WP_REST_Response( ['data' => $rows ?? [], 'grouped' => $grouped] );
    }

    /* ── نقش‌ها ─────────────────────────────────────────────── */
    public static function get_roles( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT r.*,
                    (SELECT COUNT(*) FROM {$wpdb->prefix}acl_role_permissions WHERE role_id = r.id) AS perm_count,
                    (SELECT COUNT(*) FROM {$wpdb->prefix}acl_user_roles       WHERE role_id = r.id) AS user_count
             FROM {$wpdb->prefix}acl_roles r
             ORDER BY r.sort_order, r.name",
            ARRAY_A
        );
        return new WP_REST_Response( ['data' => $rows ?? []] );
    }

    public static function create_role( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $slug = sanitize_key( $req->get_param('slug') ?? '' );
        $name = sanitize_text_field( $req->get_param('name') ?? '' );
        if ( ! $slug || ! $name ) return new WP_REST_Response( ['message'=>'slug و name الزامی است'], 400 );

        $wpdb->insert( "{$wpdb->prefix}acl_roles", [
            'slug'        => $slug,
            'name'        => $name,
            'description' => sanitize_textarea_field( $req->get_param('description') ?? '' ),
            'is_system'   => 0,
        ] );
        return new WP_REST_Response( ['id' => $wpdb->insert_id, 'success' => true], 201 );
    }

    public static function update_role( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id = (int) $req->get_param('id');
        $data = [];
        if ( $req->get_param('name') !== null )        $data['name']        = sanitize_text_field( $req->get_param('name') );
        if ( $req->get_param('description') !== null ) $data['description'] = sanitize_textarea_field( $req->get_param('description') );
        if ( $data ) $wpdb->update( "{$wpdb->prefix}acl_roles", $data, ['id' => $id] );
        return new WP_REST_Response( ['success' => true] );
    }

    public static function delete_role( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id   = (int) $req->get_param('id');
        $role = $wpdb->get_row( $wpdb->prepare( "SELECT is_system FROM {$wpdb->prefix}acl_roles WHERE id=%d", $id ), ARRAY_A );
        if ( ! $role )                       return new WP_REST_Response( ['message'=>'یافت نشد'], 404 );
        if ( (int)$role['is_system'] === 1 ) return new WP_REST_Response( ['message'=>'نقش سیستمی قابل حذف نیست'], 409 );

        $wpdb->delete( "{$wpdb->prefix}acl_role_permissions", ['role_id' => $id] );
        $wpdb->delete( "{$wpdb->prefix}acl_user_roles",       ['role_id' => $id] );
        $wpdb->delete( "{$wpdb->prefix}acl_roles",            ['id'      => $id] );
        return new WP_REST_Response( ['success' => true] );
    }

    public static function get_role_permissions( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id = (int) $req->get_param('id');
        $perms = $wpdb->get_col( $wpdb->prepare(
            "SELECT permission_key FROM {$wpdb->prefix}acl_role_permissions WHERE role_id = %d", $id
        ) );
        return new WP_REST_Response( ['data' => $perms ?? []] );
    }

    public static function set_role_permissions( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id    = (int) $req->get_param('id');
        $perms = $req->get_param('permissions');
        if ( ! is_array( $perms ) ) return new WP_REST_Response( ['message'=>'permissions باید آرایه باشد'], 400 );

        // پاک کردن قبلی
        $wpdb->delete( "{$wpdb->prefix}acl_role_permissions", ['role_id' => $id] );

        // افزودن جدید
        foreach ( $perms as $pk ) {
            $pk = sanitize_text_field( $pk );
            if ( $pk ) {
                $wpdb->insert( "{$wpdb->prefix}acl_role_permissions", [
                    'role_id'        => $id,
                    'permission_key' => $pk,
                ] );
            }
        }
        return new WP_REST_Response( ['success' => true, 'count' => count( $perms )] );
    }

    /* ── کاربران ─────────────────────────────────────────────── */
    public static function get_users_with_roles( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT u.ID AS user_id, u.user_login, u.display_name, u.user_email,
                    GROUP_CONCAT(DISTINCT CONCAT(r.name, IF(ur.scope_type='global','',CONCAT(' [',ur.scope_type,':',COALESCE(ur.scope_id,''),']'))) SEPARATOR ', ') AS roles_list,
                    COUNT(DISTINCT ur.role_id) AS role_count
             FROM {$wpdb->users} u
             LEFT JOIN {$wpdb->prefix}acl_user_roles ur ON ur.user_id = u.ID
             LEFT JOIN {$wpdb->prefix}acl_roles      r  ON r.id = ur.role_id
             GROUP BY u.ID
             ORDER BY u.display_name",
            ARRAY_A
        );
        return new WP_REST_Response( ['data' => $rows ?? []] );
    }

    public static function get_user_roles( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $uid = (int) $req->get_param('id');
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT ur.id AS assignment_id, ur.scope_type, ur.scope_id, ur.granted_at,
                    r.id AS role_id, r.slug, r.name AS role_name
             FROM {$wpdb->prefix}acl_user_roles ur
             INNER JOIN {$wpdb->prefix}acl_roles r ON r.id = ur.role_id
             WHERE ur.user_id = %d
             ORDER BY r.sort_order",
            $uid
        ), ARRAY_A );
        return new WP_REST_Response( ['data' => $rows ?? []] );
    }

    public static function assign_user_role( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $uid        = (int) $req->get_param('id');
        $role_id    = (int) $req->get_param('role_id');
        $scope_type = sanitize_text_field( $req->get_param('scope_type') ?: 'global' );
        $scope_id   = $req->get_param('scope_id') !== null && $req->get_param('scope_id') !== ''
                        ? (int) $req->get_param('scope_id') : null;

        if ( ! $uid || ! $role_id ) return new WP_REST_Response( ['message'=>'user_id و role_id الزامی است'], 400 );

        // upsert
        $exists = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}acl_user_roles
             WHERE user_id=%d AND role_id=%d AND scope_type=%s AND COALESCE(scope_id, -1) = %d",
            $uid, $role_id, $scope_type, $scope_id ?? -1
        ) );
        if ( $exists ) return new WP_REST_Response( ['message'=>'این اختصاص از قبل وجود دارد', 'id'=>$exists], 200 );

        $current_uid = (int) get_current_user_id();
        $wpdb->insert( "{$wpdb->prefix}acl_user_roles", [
            'user_id'    => $uid,
            'role_id'    => $role_id,
            'scope_type' => $scope_type,
            'scope_id'   => $scope_id,
            'granted_by' => $current_uid > 0 ? $current_uid : null,
        ] );
        return new WP_REST_Response( ['id' => $wpdb->insert_id, 'success' => true], 201 );
    }

    public static function remove_user_role( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $assignment_id = (int) $req->get_param('assignment_id');
        $wpdb->delete( "{$wpdb->prefix}acl_user_roles", ['id' => $assignment_id] );
        return new WP_REST_Response( ['success' => true] );
    }

    /* ── منوها ──────────────────────────────────────────────── */
    public static function get_menus( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT * FROM {$wpdb->prefix}acl_menus ORDER BY sort_order, id",
            ARRAY_A
        );
        return new WP_REST_Response( ['data' => $rows ?? []] );
    }

    public static function create_menu( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $wpdb->insert( "{$wpdb->prefix}acl_menus", [
            'menu_key'            => sanitize_key( $req->get_param('menu_key') ?? '' ),
            'parent_key'          => sanitize_key( $req->get_param('parent_key') ?? '' ),
            'title'               => sanitize_text_field( $req->get_param('title') ?? '' ),
            'icon'                => sanitize_text_field( $req->get_param('icon') ?? '' ),
            'route'               => sanitize_text_field( $req->get_param('route') ?? '' ),
            'required_permission' => sanitize_text_field( $req->get_param('required_permission') ?? '' ),
            'sort_order'          => (int) ( $req->get_param('sort_order') ?? 0 ),
        ] );
        return new WP_REST_Response( ['id' => $wpdb->insert_id, 'success' => true], 201 );
    }

    public static function update_menu( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id   = (int) $req->get_param('id');
        $data = [];
        foreach ( ['title','icon','route','required_permission','parent_key'] as $k ) {
            $v = $req->get_param( $k );
            if ( $v !== null ) $data[ $k ] = sanitize_text_field( (string) $v );
        }
        if ( $req->get_param('sort_order') !== null ) $data['sort_order'] = (int) $req->get_param('sort_order');
        if ( $req->get_param('is_active')  !== null ) $data['is_active']  = (int) $req->get_param('is_active');
        if ( $data ) $wpdb->update( "{$wpdb->prefix}acl_menus", $data, ['id' => $id] );
        return new WP_REST_Response( ['success' => true] );
    }

    public static function delete_menu( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $wpdb->delete( "{$wpdb->prefix}acl_menus", ['id' => (int) $req->get_param('id')] );
        return new WP_REST_Response( ['success' => true] );
    }

    /* ── کاربر فعلی ─────────────────────────────────────────── */
    public static function get_me( WP_REST_Request $req ): WP_REST_Response {
        $uid = (int) get_current_user_id();
        if ( ! $uid && isset( $GLOBALS['acc_jwt_user_id'] ) ) $uid = (int) $GLOBALS['acc_jwt_user_id'];
        if ( ! $uid ) return new WP_REST_Response( ['message'=>'unauthorized'], 401 );

        $wp_user = get_user_by( 'id', $uid );

        return new WP_REST_Response( [
            'user_id'     => $uid,
            'user'        => $wp_user ? [
                'id'           => $uid,
                'display_name' => $wp_user->display_name,
                'user_login'   => $wp_user->user_login,
                'email'        => $wp_user->user_email,
            ] : null,
            'roles'       => acl_get_user_roles( $uid ),
            'permissions' => acl_get_user_permissions( $uid ),
            'menus'       => acl_get_user_menus( $uid ),
            'scopes'      => acl_get_current_user_scopes(),
        ] );
    }

    /* ── Overrides ──────────────────────────────────────────── */
    public static function get_overrides( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $user_id = $req->get_param('user_id') ? (int) $req->get_param('user_id') : null;
        $where   = $user_id ? $wpdb->prepare( "WHERE user_id = %d", $user_id ) : "";
        $rows    = $wpdb->get_results(
            "SELECT o.*, u.display_name AS user_name
             FROM {$wpdb->prefix}acl_object_overrides o
             LEFT JOIN {$wpdb->users} u ON u.ID = o.user_id
             {$where}
             ORDER BY o.created_at DESC LIMIT 200",
            ARRAY_A
        );
        return new WP_REST_Response( ['data' => $rows ?? []] );
    }

    public static function set_override( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $data = [
            'user_id'        => (int) $req->get_param('user_id'),
            'entity_type'    => sanitize_text_field( $req->get_param('entity_type') ?? '' ),
            'entity_id'      => (int) $req->get_param('entity_id'),
            'permission_key' => sanitize_text_field( $req->get_param('permission_key') ?? '' ),
            'effect'         => in_array( $req->get_param('effect'), ['allow','deny'] ) ? $req->get_param('effect') : 'allow',
            'notes'          => sanitize_text_field( $req->get_param('notes') ?? '' ),
        ];
        if ( ! $data['user_id'] || ! $data['entity_type'] || ! $data['permission_key'] ) {
            return new WP_REST_Response( ['message'=>'فیلدهای الزامی ناقص است'], 400 );
        }

        $exists = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}acl_object_overrides
             WHERE user_id=%d AND entity_type=%s AND entity_id=%d AND permission_key=%s",
            $data['user_id'], $data['entity_type'], $data['entity_id'], $data['permission_key']
        ) );
        if ( $exists ) {
            $wpdb->update( "{$wpdb->prefix}acl_object_overrides",
                ['effect' => $data['effect'], 'notes' => $data['notes']],
                ['id' => $exists]
            );
            return new WP_REST_Response( ['id' => $exists, 'success' => true] );
        }

        $wpdb->insert( "{$wpdb->prefix}acl_object_overrides", $data );
        return new WP_REST_Response( ['id' => $wpdb->insert_id, 'success' => true], 201 );
    }

    public static function delete_override( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $wpdb->delete( "{$wpdb->prefix}acl_object_overrides", ['id' => (int) $req->get_param('id')] );
        return new WP_REST_Response( ['success' => true] );
    }

    /* ── پروفایل دسترسی یکپارچه ───────────────────────────── */
    public static function get_module_registry( WP_REST_Request $req ): WP_REST_Response {
        require_once dirname( __DIR__ ) . '/helpers/acl-scope-registry.php';
        return new WP_REST_Response( [
            'data'    => acl_get_module_registry(),
            'profiles'=> acl_get_access_profiles(),
        ] );
    }

    public static function get_access_profiles( WP_REST_Request $req ): WP_REST_Response {
        require_once dirname( __DIR__ ) . '/helpers/acl-scope-registry.php';
        return new WP_REST_Response( ['data' => acl_get_access_profiles()] );
    }

    public static function get_user_profile( WP_REST_Request $req ): WP_REST_Response {
        $uid = (int) $req->get_param('id');
        $profile = acl_get_user_access_profile( $uid );
        if ( ! $profile ) return new WP_REST_Response( ['message'=>'کاربر یافت نشد'], 404 );

        require_once dirname( __DIR__ ) . '/helpers/acl-scope-registry.php';
        global $wpdb;
        $all_menus = $wpdb->get_results(
            "SELECT menu_key, title, icon, route, required_permission, sort_order
             FROM {$wpdb->prefix}acl_menus WHERE is_active = 1 ORDER BY sort_order",
            ARRAY_A
        ) ?? [];

        $roles = $wpdb->get_results(
            "SELECT id, slug, name, description FROM {$wpdb->prefix}acl_roles ORDER BY sort_order, name",
            ARRAY_A
        ) ?? [];

        foreach ( $roles as &$role ) {
            $role['permissions'] = $wpdb->get_col( $wpdb->prepare(
                "SELECT permission_key FROM {$wpdb->prefix}acl_role_permissions WHERE role_id = %d",
                (int) $role['id']
            ) ) ?? [];
        }
        unset( $role );

        $suggested = acl_suggest_roles_for_menus( $profile['menu_keys'] );

        return new WP_REST_Response( [
            'profile'         => $profile,
            'menus'           => $all_menus,
            'roles'           => $roles,
            'suggested_roles' => $suggested,
            'scope_types'     => acl_get_scope_types_from_menus( $profile['menu_keys'] ),
        ] );
    }

    public static function save_user_profile( WP_REST_Request $req ): WP_REST_Response {
        $uid = (int) $req->get_param('id');
        $body = [
            'menu_keys' => $req->get_param('menu_keys') ?? [],
            'role_ids'  => $req->get_param('role_ids') ?? [],
            'scopes'    => $req->get_param('scopes') ?? [],
            'force'     => (bool) $req->get_param('force'),
        ];

        $result = acl_save_user_access_profile( $uid, $body );
        if ( ! ( $result['success'] ?? false ) ) {
            return new WP_REST_Response( $result, 400 );
        }
        return new WP_REST_Response( $result );
    }

    public static function get_scope_options( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $type = sanitize_text_field( $req->get_param('type') ?? '' );
        $data = [];

        switch ( $type ) {
            case 'warehouse':
                $data = $wpdb->get_results(
                    "SELECT id, name AS label, code, type FROM {$wpdb->prefix}inv_warehouses WHERE is_active = 1 ORDER BY name",
                    ARRAY_A
                ) ?? [];
                break;
            case 'project':
                $data = $wpdb->get_results(
                    "SELECT id, name AS label, code, status FROM {$wpdb->prefix}pc_projects ORDER BY name",
                    ARRAY_A
                ) ?? [];
                break;
            case 'district':
                $data = $wpdb->get_results(
                    "SELECT id, name AS label, city FROM {$wpdb->prefix}gis_districts ORDER BY city, name",
                    ARRAY_A
                ) ?? [];
                break;
            case 'neighborhood':
                $data = $wpdb->get_results(
                    "SELECT n.id, CONCAT(d.name, ' — ', n.name) AS label, n.district_id, n.name
                     FROM {$wpdb->prefix}gis_neighborhoods n
                     INNER JOIN {$wpdb->prefix}gis_districts d ON d.id = n.district_id
                     ORDER BY d.name, n.name",
                    ARRAY_A
                ) ?? [];
                break;
            default:
                return new WP_REST_Response( ['message'=>'نوع scope نامعتبر است', 'data'=>[]], 400 );
        }

        return new WP_REST_Response( ['scope_type' => $type, 'data' => $data] );
    }
}
