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

class FixLinks_License {

    public static function validate(string $key): array {
        $domain   = wp_parse_url( get_site_url(), PHP_URL_HOST );
        $response = wp_remote_get(
            add_query_arg(['key' => $key, 'domain' => $domain], FIXLINKS_API_BASE . '/validate-key.php'),
            ['timeout' => 15, 'sslverify' => true]
        );
        if (is_wp_error($response)) return ['valid' => false, 'reason' => 'connection_failed'];
        return json_decode(wp_remote_retrieve_body($response), true) ?? ['valid' => false, 'reason' => 'invalid_response'];
    }

    public static function is_active(): bool {
        return !empty(get_option('fixlinks_license_key', '')) && get_option('fixlinks_license_plan', 'free') !== 'free';
    }

    public static function get_plan(): string {
        return get_option('fixlinks_license_plan', 'free');
    }

    public static function get_billing_url(): ?string {
        $key = get_option('fixlinks_license_key', '');
        $gw  = get_option('fixlinks_license_gateway', '');
        if (!$key) return null;
        return FIXLINKS_API_BASE . '/billing.php?' . http_build_query(['key' => $key, 'gateway' => $gw]);
    }

    public static function deactivate_domain(): void {
        $key = get_option('fixlinks_license_key', '');
        if (!$key) return;
        wp_remote_get(
            add_query_arg(
                ['key' => $key, 'domain' => wp_parse_url( get_site_url(), PHP_URL_HOST ), 'action' => 'deactivate'],
                FIXLINKS_API_BASE . '/validate-key.php'
            ),
            ['timeout' => 10]
        );
    }

    public static function recheck(): void {
        $key = get_option('fixlinks_license_key', '');
        if (!$key) return;
        $r = self::validate($key);
        if (!($r['valid'] ?? false)) {
            update_option('fixlinks_license_plan', 'free');
            update_option('fixlinks_license_key', '');
        }
    }

    public static function ajax_save_settings(): void {
        check_ajax_referer('fixlinks_nonce', 'nonce');
        if (!current_user_can('manage_options')) wp_die('Forbidden');
        $key = sanitize_text_field(wp_unslash($_POST['license_key'] ?? ''));
        if (empty($key)) {
            wp_send_json_error(__('License key is required.', 'fixlinks-ai'));
        }
        $r = self::validate($key);
        if ($r['valid'] ?? false) {
            update_option('fixlinks_license_key',     $key);
            update_option('fixlinks_license_plan',    $r['plan']);
            update_option('fixlinks_license_gateway', $r['gateway'] ?? '');
            wp_send_json_success(['message' => __('License activated!', 'fixlinks-ai'), 'plan' => $r['plan']]);
        } else {
            wp_send_json_error($r['reason'] ?? __('Activation failed. Check your key.', 'fixlinks-ai'));
        }
    }
}