/**
 * Sort categories by ACF term meta 'order' for both normal queries and REST.
 */

/* A) Non‑REST queries (Elementor uses get_terms()) */
add_filter('get_terms_args', function (array $args, array $taxonomies) {
    // Only affect frontend queries for our 'category' taxonomy
    if (is_admin()) {
        return $args;
    }
    if (in_array('category', $taxonomies, true)) {
        $args['meta_key']  = 'order';
        $args['orderby']   = 'meta_value_num';
        $args['order']     = 'ASC';
    }
    return $args;
}, 10, 2);

/* B) Allow meta_value_num sorting in REST API */
add_filter('rest_category_collection_params', function (array $params) {
    // Extend allowed orderby values to include meta_value_num
    if (isset($params['orderby'])) {
        $params['orderby']['enum'][] = 'meta_value_num';
    }
    return $params;
});

/* C) REST query modifications */
add_filter('rest_category_query', function (array $args) {
    $args['meta_key']  = 'order';
    $args['orderby']   = 'meta_value_num';
    $args['order']     = 'ASC';
    return $args;
}, 10, 2);
