<?php
if ( ! defined( 'ABSPATH' ) ) exit;
function easy_gpt_license_page() {
    $license_key = get_option('easy_gpt_license_key');
    $license_status = get_option('easy_gpt_license_status');
    $license_expires = get_option('easy_gpt_license_expires');
    $is_license_valid = $license_status === 'valid' && new DateTime($license_expires) > new DateTime();

    // Enmascarar la licencia para mostrar solo los ¨²ltimos 4 caracteres
    if ( ! empty( $license_key ) ) {
        $masked_license_key = str_repeat( '*', strlen( $license_key ) - 4 ) . substr( $license_key, -4 );
    } else {
        $masked_license_key = '';
    }
    ?>
    <div class="wrap">
        <h2>Easy GPT License</h2>
        <?php
            wp_enqueue_style('easy_gpt_admin_css', plugins_url('../styles/license.css', __FILE__));
        ?>
        <form method="post" action="">
            <?php wp_nonce_field( 'easy_gpt_license_nonce', 'easy_gpt_license_nonce_field' ); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">License Key</th>
                    <td>
                        <input type="text" name="easy_gpt_license_key" value="<?php echo esc_attr( $masked_license_key ); ?>" style="width: 100%; max-width: 450px;">
                        <p class="description">Your license key is masked for security.</p>
                    </td>
                </tr>
                <?php if ( $is_license_valid ): ?>
                <tr>
                    <td colspan="2" class="easy-gpt-status">License is valid until <?php echo esc_html( $license_expires ); ?>.</td>
                </tr>
                <?php else: ?>
                <tr>
                    <td colspan="2" class="easy_gpt-warning">License is not valid or has expired.</td>
                </tr>
                <?php endif; ?>
            </table>
            <?php submit_button( 'Validate', 'primary', 'submit', false ); ?>
        </form>
        <a href="https://easygptforwp.com/pricing-plans/" target="_blank" class="easy-gpt-button">Purchase a license or get a free trial license (valid for 5 days)</a>
    </div>
    <?php
}


add_action('admin_init', 'easy_gpt_handle_license_submission');
function easy_gpt_handle_license_submission() {
    if (isset($_POST['easy_gpt_license_key'])) {
        
        $license_key = isset($_POST['easy_gpt_license_key']) ? sanitize_text_field( wp_unslash( $_POST['easy_gpt_license_key'] ) ) : '';

        $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);

        $api_url = 'https://easygptforwp.com/wp-json/miapi/v1/verificar_licencia/';
        $response = wp_remote_post($api_url, [
            'method' => 'POST',
            'headers' => [
                'Content-Type' => 'application/json'
            ],
            'body' => wp_json_encode([
                'licencia' => $license_key,
                'dominio' => $domain
            ]),
            'data_format' => 'body'
        ]);

        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);

            if (isset($data['message']) && $data['message'] === 'Licencia verificada y dominio registrado correctamente.' && isset($data['expires'])) {
                update_option('easy_gpt_license_key', $license_key);
                update_option('easy_gpt_license_status', 'valid');
                update_option('easy_gpt_license_expires', sanitize_text_field($data['expires']));
            }         
            if (isset($data['message']) && $data['message'] === 'Este dominio ya esta registrado con esta licencia y sigue siendo valida.') {
                update_option('easy_gpt_license_key', $license_key);
                update_option('easy_gpt_license_status', 'valid');
                update_option('easy_gpt_license_expires', sanitize_text_field($data['expires']));
            }
            
        } 
    } 
}



// Programar la verificaciÃ³n de la licencia
if (!wp_next_scheduled('easy_gpt_verify_license_event')) {
    wp_schedule_event(time(), 'daily', 'easy_gpt_verify_license_event');
}

add_action('easy_gpt_verify_license_event', 'easy_gpt_verify_license');

// Funci¨®n para verificar la licencia
function easy_gpt_verify_license() {
    $license_key = get_option('easy_gpt_license_key');
    if (empty($license_key)) {
        return;
    }

    $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
    $api_url = 'https://easygptforwp.com/wp-json/miapi/v1/verificar_licencia/';
    $response = wp_remote_post($api_url, [
        'method' => 'POST',
        'headers' => [
            'Content-Type' => 'application/json'
        ],
        'body' => wp_json_encode([
            'licencia' => $license_key,
            'dominio' => $domain
        ]),
        'data_format' => 'body'
    ]);

    if (!is_wp_error($response)) {
        $data = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($data['message']) && $data['message'] === 'Este dominio ya esta registrado con esta licencia y sigue siendo valida.') {
            update_option('easy_gpt_license_status', 'valid');
            update_option('easy_gpt_license_expires', sanitize_text_field($data['expires']));
        } else {
            update_option('easy_gpt_license_status', 'invalid');
        }
    } 
}
