<?php
if (!defined('ABSPATH')) {
    exit; // Evitar acceso directo
}

class WP2FA_License_Manager {

    private static $license_key_option = 'wp2fa_license_key';

    public static function get_license_key() {
        return get_option(self::$license_key_option, '');
    }

    public static function is_license_valid($license_key = null) {
        if (!$license_key) {
            $license_key = self::get_license_key();
        }

        $url = 'https://eroqs.com/lic/v.php';

        $domain = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])) : '';

        $response = wp_remote_post($url, [
            'body' => [
                'action' => 'validate',
                'license_key' => $license_key,
                'domain' => $domain
            ],
            'timeout' => 10
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        return isset($data['valid']) && $data['valid'] === true;
    }

    public static function is_premium_active() {
        return self::is_license_valid();
    }

    public static function handle_license_submission() {
        if (isset($_POST['wp2fa_license_key']) && check_admin_referer('wp2fa_license_save', 'wp2fa_license_nonce')) {
            $license_key = sanitize_text_field($_POST['wp2fa_license_key']);
            update_option(self::$license_key_option, $license_key);

            $is_valid = self::is_license_valid($license_key);
            update_option('wp2fa_license_status', $is_valid ? 'valid' : 'invalid');
        }
    }

    public static function show_license_field() {
        $saved = self::get_license_key();
        ?>
        <h2><?php echo esc_html__('Licencia Premium', 'wp-2fa-authenticator'); ?></h2>
        <form method="post">
            <?php wp_nonce_field('wp2fa_license_save', 'wp2fa_license_nonce'); ?>
            <input type="text" name="wp2fa_license_key" value="<?php echo esc_attr($saved); ?>" style="width: 300px;" />
            <input type="submit" class="button button-primary" value="<?php echo esc_attr__('Guardar licencia', 'wp-2fa-authenticator'); ?>" />
        </form>
        <?php
        if (!empty($saved)) {
            if (self::is_license_valid($saved)) {
                echo '<p style="color:green;">' . esc_html__('✅ Licencia válida. Funcionalidades premium activadas.', 'wp-2fa-authenticator') . '</p>';
            } else {
                echo '<p style="color:red;">' . esc_html__('❌ Licencia inválida.', 'wp-2fa-authenticator') . '</p>';
            }
        }
    }

    public static function display_license_notice() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $license_key = self::get_license_key();

        if (!$license_key) {
            echo '<div class="notice notice-warning is-dismissible"><p><strong>' . esc_html__('WP 2FA Authenticator:', 'wp-2fa-authenticator') . '</strong> ' . esc_html__('No has ingresado una licencia.', 'wp-2fa-authenticator') . '</p></div>';
        } elseif (!self::is_license_valid($license_key)) {
            echo '<div class="notice notice-error is-dismissible"><p><strong>' . esc_html__('WP 2FA Authenticator:', 'wp-2fa-authenticator') . '</strong> ' . esc_html__('La licencia es inválida o ha expirado.', 'wp-2fa-authenticator') . '</p></div>';
        } else {
            echo '<div class="notice notice-success is-dismissible"><p><strong>' . esc_html__('WP 2FA Authenticator:', 'wp-2fa-authenticator') . '</strong> ' . esc_html__('Licencia activa correctamente ✅', 'wp-2fa-authenticator') . '</p></div>';
        }
    }
}

add_action('admin_init', ['WP2FA_License_Manager', 'handle_license_submission']);
add_action('admin_notices', ['WP2FA_License_Manager', 'display_license_notice']);
