<?php
if (!defined('ABSPATH')) exit;

class SS_Ajax {
    public static function init() {
        add_action('wp_ajax_ss_test_connection', [__CLASS__, 'test_connection']);
        add_action('wp_ajax_ss_ai_publish_llms', [__CLASS__, 'ai_publish_llms']);
        add_action('wp_ajax_ss_ai_status',       [__CLASS__, 'ai_status']);
        add_action('admin_post_ss_ai_download',  [__CLASS__, 'ai_download']); // non-AJAX download

    }

    public static function test_connection() {
        check_ajax_referer('ss_test_connection','_ajax_nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message'=>'No permission'], 403);

        $apiBase = (string) get_option(SS_Settings::OPT_API_BASE, '');
        $apiKey  = (string) get_option(SS_Settings::OPT_API_KEY,  '');
        $domain  = (string) get_option(SS_Settings::OPT_DOMAIN, wp_parse_url(get_site_url(), PHP_URL_HOST));

        if (!$apiBase || !preg_match('#/api/?$#', $apiBase)) {
            wp_send_json_error(['message'=>'API base must end with /api'], 400);
        }
        if (!$apiKey || !$domain) {
            wp_send_json_error(['message'=>'Missing API key or domain'], 400);
        }

        $res = \SS\Core\Http::postJson('license.validate','/license/validate',[
            'domain'         => $domain,
            'plugin_version' => defined('SEARCHSHIFTER_VERSION') ? SEARCHSHIFTER_VERSION : 'unknown',
        ], ['timeout'=>10]);

        if (empty($res['ok'])) {
            wp_send_json_error([
                'message' => $res['error'] ?? 'Request failed',
                'status'  => $res['status'] ?? 0
            ], 200);
        }

        $data = is_array($res['json'] ?? null) ? ($res['json']['data'] ?? []) : [];
        wp_send_json_success([
            'message'   => 'License active',
            'status'    => $res['status'],
            'plan'      => $data['plan']      ?? null,
            'readOnly'  => $data['readOnly']  ?? null,
            'expiresAt' => $data['expiresAt'] ?? null,
        ]);
    }


    public static function ai_publish_llms(){
        check_ajax_referer('ss_ai_admin_actions','_ajax_nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message'=>'forbidden'], 403);

        $ok = (class_exists('SS_AI_Protocol') && SS_AI_Protocol::write_llms_to_root());

        // Queue telemetry regardless of outcome (if enabled)
        if (class_exists('SS\\Core\\Telemetry')) {
            \SS\Core\Telemetry::queue('ai_admin_publish_llms', [
                'screen'    => 'ai_protocol_files',
                'cache_hit' => false,           // reserved; matches sanitizer allow-list
                'endpoint'  => 'llms.write',    // shows up as a key (domain-stripped)
            ]);
        }

        if ($ok) {
            wp_send_json_success(['message'=>'written']);
        }
        wp_send_json_error(['message'=>'write_failed']);
    }


public static function ai_status(){
    check_ajax_referer('ss_ai_admin_actions','_ajax_nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(['message'=>'forbidden'], 403);

    $out = [
        'policy_ok' => false, 'policy_msg' => '',
        'llms_ok'   => false, 'llms_msg'   => '',
        'robots_ok' => false, 'robots_msg' => '',
    ];

    // Policy page exists & published
    $pid = (int) get_option('ss_ai_policy_page_id');
    if ($pid && get_post_status($pid) === 'publish'){
        $out['policy_ok'] = true;
    } else {
        $out['policy_msg'] = 'Not published';
    }

    // llms.txt: HTTP 200 + text/plain
    $llms_url = home_url('/llms.txt');
    $r = wp_remote_get($llms_url, ['timeout'=>8, 'redirection'=>2]);
    if (!is_wp_error($r)){
        $code = (int) wp_remote_retrieve_response_code($r);
        $ct   = (string) wp_remote_retrieve_header($r, 'content-type');
        if ($code===200 && stripos($ct,'text/plain')!==false){
            $out['llms_ok'] = true;
        } else {
            $out['llms_msg'] = "HTTP $code ".($ct?:'');
        }
    } else {
        $out['llms_msg'] = $r->get_error_message();
    }

    // robots.txt contains our marker
    $robots = wp_remote_get(home_url('/robots.txt'), ['timeout'=>8]);
    if (!is_wp_error($robots)){
        $body = (string) wp_remote_retrieve_body($robots);
        if (stripos($body, '# SearchShifter AI Discovery') !== false){
            $out['robots_ok'] = true;
        } else {
            $out['robots_msg'] = 'No AI block';
        }
    } else {
        $out['robots_msg'] = $robots->get_error_message();
    }

    wp_send_json_success($out);
}

/** Force-download llms.txt or policy HTML (server-side render) */
public static function ai_download(){
    if (!current_user_can('manage_options')) wp_die('forbidden', 403);
    check_admin_referer('ss_ai_admin_actions');

    $file = isset($_GET['file']) ? sanitize_key($_GET['file']) : '';
    if (!class_exists('SS_AI_Protocol')) wp_die('missing', 500);

    if ($file === 'llms'){
    $payload = SS_AI_Protocol::preview_llms();
    $bytes   = strlen($payload);

    nocache_headers();
    header('Content-Type: text/plain; charset=utf-8');
    header('Content-Disposition: attachment; filename="llms.txt"');
    header('Content-Length: ' . $bytes);

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo $payload;
    exit;
    }

    if ($file === 'policy'){
        $payload = SS_AI_Protocol::preview_policy();
        $bytes   = strlen($payload);

        nocache_headers();
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: attachment; filename="ai-visibility-policy.html"');
        header('Content-Length: ' . $bytes);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $payload;
        exit;
    }

    wp_die('bad_request', 400);
}

}
