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

class SS_Ajax {
    public static function init() {
        add_action('wp_ajax_ss_test_connection', [__CLASS__, 'test_connection']);
    }

 public static function test_connection() {
    check_ajax_referer( 'ss_test_connection', '_ajax_nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'No permission' ), 403 );
    }

    $apiBase = (string) get_option( SS_Settings::OPT_API_BASE, '' );
    $apiKey  = (string) get_option( SS_Settings::OPT_API_KEY,  '' );

    $parsed  = wp_parse_url( get_site_url() );
    $domain  = (string) get_option(
        SS_Settings::OPT_DOMAIN,
        $parsed['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_success(['message'=>'License active', 'status'=>$res['status']]);
        }
        wp_send_json_error(['message'=>$res['error'] ?? 'Request failed', 'status'=>$res['status'] ?? 0], 200);
    }
}
