<?php
defined('ABSPATH') || exit;

class FixLinks_AI {

    public static function get_suggestion(string $broken_url): ?array {
        $key = get_option('fixlinks_license_key', '');
        if (!$key) return null;
        $response = wp_remote_post(FIXLINKS_API_BASE . '/ai.php', [
            'timeout' => 20,
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => wp_json_encode([
                'license_key' => $key,
                'broken_url'  => $broken_url,
                'site_urls'   => FixLinks_Crawler::get_site_urls(200),
            ]),
        ]);
        if (is_wp_error($response)) return null;
        $body = json_decode(wp_remote_retrieve_body($response), true);
        return isset($body['error']) ? null : $body;
    }

    public static function ajax_get_suggestion(): void {
        check_ajax_referer('fixlinks_nonce', 'nonce');
        if (!current_user_can('manage_options')) wp_die('Forbidden');
        if (!FixLinks_License::is_active()) {
            wp_send_json_error(__('Pro license required.', 'fixlinks-ai'));
        }
        $link_id    = intval($_POST['link_id']    ?? 0);
        $broken_url = sanitize_url(wp_unslash($_POST['broken_url'] ?? ''));
        if (!$link_id || !$broken_url) {
            wp_send_json_error(__('Invalid parameters.', 'fixlinks-ai'));
        }
        $result = self::get_suggestion($broken_url);
        if (!$result) {
            wp_send_json_error(__('Could not get AI suggestion. Try again.', 'fixlinks-ai'));
        }
        FixLinks_DB::update_suggestion($link_id, $result['suggestion'], $result['confidence']);
        wp_send_json_success($result);
    }
}