<?php
/**
 * EONSR AEO Agent - Keyphrase API Endpoint
 *
 * Handles the REST API endpoint for checking existing keyphrases
 * in Yoast SEO and Rank Math to prevent duplicates.
 *
 * @package EONSR_AEO_Agent
 */

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

/**
 * Register REST API endpoint.
 *
 * Route: /wp-json/eonsr-aeo-agent/v1/keyphrases?q={query}
 */
// Cập nhật tên hàm
add_action('rest_api_init', 'eonsr_aeo_agent_register_keyphrase_api');

function eonsr_aeo_agent_register_keyphrase_api()
{
    // Cập nhật Namespace và Callback
    register_rest_route('eonsr-aeo-agent/v1', '/keyphrases', [
        'methods'             => 'GET',
        'callback'            => 'eonsr_aeo_agent_get_existing_keyphrases',
        'permission_callback' => '__return_true', // Public access allowed
        'args'                => [
            'q' => [
                'required'    => true,
                'type'        => 'string',
                'description' => 'Query string to search for similar keyphrases in DB.'
            ]
        ]
    ]);
}

/**
 * Retrieve existing keyphrases that contain the query string.
 * Checks both Yoast SEO and Rank Math meta keys.
 *
 * @param WP_REST_Request $request The API request object.
 * @return array List of unique, sorted keyphrases found.
 */
function eonsr_aeo_agent_get_existing_keyphrases($request)
{
    $query = $request->get_param('q');

    // 1. Validate Input
    if (empty($query)) {
        return [];
    }

    global $wpdb;
    $search_term = '%' . $wpdb->esc_like($query) . '%';

    // 2. Query Yoast SEO Keywords
    // NOTE: Keep original meta keys for 3rd party plugins
    $yoast_query = "
        SELECT DISTINCT meta_value 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = '_yoast_wpseo_focuskw' 
        AND meta_value LIKE %s
        AND meta_value != ''
    ";
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Required for Yoast SEO meta search, no WP API available
    $yoast_kws = $wpdb->get_col($wpdb->prepare($yoast_query, $search_term));

    // 3. Query Rank Math Keywords
    // NOTE: Keep original meta keys for 3rd party plugins
    $rank_math_query = "
        SELECT DISTINCT meta_value 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = 'rank_math_focus_keyword' 
        AND meta_value LIKE %s
        AND meta_value != ''
    ";

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Required for Rank Math meta search, no WP API available
    $rank_math_kws = $wpdb->get_col($wpdb->prepare($rank_math_query, $search_term));

    // 4. Merge & Deduplicate
    $all_kws = array_unique(array_merge($yoast_kws, $rank_math_kws));

    // 5. Clean Data (Remove empty/null)
    $all_kws = array_filter($all_kws, function ($kw) {
        return !empty(trim($kw));
    });

    // 6. Sort by length (Shorter keywords first - often more general)
    usort($all_kws, function ($a, $b) {
        return strlen($a) - strlen($b);
    });

    // Reset array keys and return
    return array_values($all_kws);
}