<?php
// Keyword Research API Endpoint

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

// Use the shared key validation used across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/keyword-research', [
        'methods'  => 'GET',
        'callback' => 'myaio_sac_keyword_research',
        'permission_callback' => 'myaio_sac_keyword_research_permission',
    ]);
});

/**
 * Permission callback for keyword-research endpoint
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_keyword_research_permission') ) {
    function myaio_sac_keyword_research_permission( WP_REST_Request $request ) {
        if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_Error('unauthorized', 'Invalid or unverified API key', ['status' => 401]);
    }
}


/**
 * Callback function to return keyword research data
 */
function myaio_sac_keyword_research() {
    // Sample keywords (replace with real API logic if needed)
    $sample_keywords = [
        ['keyword' => 'seo tools', 'volume' => 2900, 'difficulty' => 38],
        ['keyword' => 'wordpress seo', 'volume' => 1300, 'difficulty' => 42],
        ['keyword' => 'best seo plugin', 'volume' => 2100, 'difficulty' => 35]
    ];

    return rest_ensure_response(['keywords' => $sample_keywords]);
}
