<?php
// File: modules/keyword-frequency.php

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

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/keyword-frequency', [
        'methods'             => WP_REST_Server::CREATABLE, // POST
        'callback'            => 'myaio_sac_keyword_frequency_check',
        // keep output unchanged (Unauthorized handled in callback)
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_keyword_frequency_check( WP_REST_Request $request ) {

    // ✅ Consistent auth across all modules (same output)
    $auth = function_exists('myaio_sac_require_api_key_or_401') ? myaio_sac_require_api_key_or_401($request) : null;
    if ($auth !== true) {
        return $auth instanceof WP_REST_Response ? $auth : new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }

    // Support JSON body + params
    $params = $request->get_json_params();
    if ( ! is_array($params) ) {
        $params = [];
    }

    // Keep your original validation + messages
    if (empty($params['keywords'])) {
        return new WP_REST_Response(['error' => 'Keywords are required'], 400);
    }

    $keywords = array_map('trim', explode(',', (string) $params['keywords']));
    $keywords = array_filter($keywords); // Remove empty strings
    $url      = isset($params['url']) ? (string) $params['url'] : null;

    $posts = [];

    if ($url) {
        $post_id = url_to_postid($url);
        if (!$post_id) {
            return new WP_REST_Response(['error' => 'Invalid or non-existent URL'], 404);
        }

        $post = get_post($post_id);
        if (!$post || $post->post_status !== 'publish') {
            return new WP_REST_Response(['error' => 'Post not found or not published'], 404);
        }

        $posts[] = $post;
    } else {
        $posts = get_posts([
            'post_type'   => ['post', 'page'],
            'post_status' => 'publish',
            'numberposts' => -1,
        ]);
    }

    $results = [];

    foreach ($posts as $post) {
        $content       = trim(wp_strip_all_tags(apply_filters('myaio_the_content', $post->post_content)));
        $content_lower = mb_strtolower($content);

        $counts = [];
        foreach ($keywords as $keyword) {
            $kw      = mb_strtolower($keyword);
            $pattern = '/\b' . preg_quote($kw, '/') . '\b/u';
            preg_match_all($pattern, $content_lower, $matches);
            $counts[$kw] = count($matches[0]);
        }

        $results[] = [
            'title'          => get_the_title($post),
            'url'            => get_permalink($post),
            'keyword_counts' => $counts,
        ];
    }

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