<?php

// Register rest api routes for all registered custom taxonomies
// Hook the custom taxonomy REST API registration function into WordPress
add_action('rest_api_init', 'dragblock_custom_taxonomy_rest_api');
function dragblock_custom_taxonomy_rest_api() {
    // Get all registered custom taxonomies
    $custom_taxonomies = get_taxonomies(array(
        'public'   => true,
        '_builtin' => false,
    ), 'objects');

    // Loop through each custom taxonomy and register it with a prefix
    foreach ($custom_taxonomies as $taxonomy) {
        // Register REST route for searching terms in taxonomy
        register_rest_route('wp/v2', '/' . DRAGBLOCK_START_TAX_QUERY_KEY . $taxonomy->name, array(
            'methods' => 'GET',
            'callback' => 'dragblock_search_taxonomy_terms',
            'permission_callback' => 'dragblock_request_custom_taxonomy_terms_permission',
            'args' => array(                
                'search' => array(
                    'required' => false,
                    'validate_callback' => 'dragblock_validate_search_query_custom_taxonomy'
                ),
            ),
        ));
    }
}

function dragblock_validate_search_query_custom_taxonomy($param, $request, $key) {
    return is_string($param);
}

// Callback function to handle search terms in taxonomy
function dragblock_search_taxonomy_terms($data) {
    // Get the taxonomy name from the request
    $taxonomy_slug = $data->get_route();
    $taxonomy_slug_parts = explode('/', $taxonomy_slug);
    $taxonomy_name = end($taxonomy_slug_parts);
    $taxonomy_name = str_replace(DRAGBLOCK_START_TAX_QUERY_KEY, '', $taxonomy_name);

    // Get the search term from the request parameters
    $search_term = $data->get_param('search');
    // return [$taxonomy_name, $search_term];

    // Retrieve terms of the specified taxonomy matching the search term
    $terms = get_terms(array(
        'taxonomy' => $taxonomy_name,
        'search' => $search_term,
        'hide_empty' => false, // Include empty terms
    ));

    // Prepare terms data
    $terms_data = array();
    foreach ($terms as $term) {
        $terms_data[] = array(
            'id' => $term->term_id,
            'name' => $term->name,
            'description' => $term->description,
            // 'slug' => $term->slug,
            // Add more fields as needed
        );
    }

    // Return terms data
    return $terms_data;
}


function dragblock_request_custom_taxonomy_terms_permission() {
    if (current_user_can('administrator')) {
        return true;
    }
    return current_user_can('editor');
}
