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

add_action('wp_ajax_webability_acwg_verify', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['msg' => 'forbidden'], 403);
    }
    check_ajax_referer('webability_acwg_verify_nonce', 'nonce');

    $home   = home_url('/');
    $parsed = wp_parse_url($home);
    $domain = $parsed['host'];

    // Use the same public GraphQL query the widget uses — no auth token needed
    $resp = wp_remote_post('https://api.webability.io/graphql', [
        'timeout'    => 10,
        'user-agent' => 'WebAbility-WordPress-Plugin/' . WEBABILITY_WIDGET_VERSION,
        'headers'    => ['Content-Type' => 'application/json'],
        'body'       => wp_json_encode([
            'query'     => 'query validateToken($url: String!) { validateToken(url: $url) { validation } }',
            'variables' => ['url' => $domain],
        ]),
    ]);

    if (is_wp_error($resp)) {
        wp_send_json(['ok' => false, 'msg' => 'Could not reach the verification service. Please try again later.']);
    }

    $code = wp_remote_retrieve_response_code($resp);
    $body = wp_remote_retrieve_body($resp);
    $data = json_decode($body, true);

    if ($code !== 200 || json_last_error() !== JSON_ERROR_NONE) {
        wp_send_json(['ok' => false, 'msg' => 'Domain not found in your WebAbility dashboard']);
    }

    $detected = isset($data['data']['validateToken']['validation'])
        && $data['data']['validateToken']['validation'] === 'found';

    update_option('webability_verified', $detected ? 1 : 0, true);

    wp_send_json(['ok' => $detected]);
});
