<?php
/**
 * Handles Manual License Verification.
 * Limits and queues are now handled externally by the Pexally Central API.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class PexEmail_License {

    // You will document this API URL in the readme.txt under == External services ==
    const API_URL = 'https://payment.pexally.com/wp-json/pexally-license/v1/validate';

    /**
     * No more background cron jobs or telemetry.
     */
    public function init() {
        // Init intentionally left empty. 
    }

    /**
     * Manually verify the license only when the user clicks "Save" in the settings page.
     * No background telemetry. Only sends what is required to validate the key.
     */
    public static function verify_license_manually( $license_key, $user_email ) {
        
        if ( empty( $license_key ) ) {
            update_option( 'pexemail_license_status', 'invalid' );
            delete_option( 'pexemail_license_error' );
            return false;
        }

        $response = wp_remote_post( self::API_URL, [
            'timeout'     => 15,
            'redirection' => 5,
            'httpversion' => '1.1',
            'blocking'    => true,
            'headers'     => [
                'Content-Type' => 'application/json',
                'Accept'       => 'application/json'
            ],
            'body'        => wp_json_encode([
                'license_key' => sanitize_text_field( $license_key ),
                'admin_email' => sanitize_email( $user_email ),
                'domain'      => site_url(), // Sent once upon explicit user save action
            ]),
        ]);

        if ( is_wp_error( $response ) ) {
            update_option( 'pexemail_license_error', 'Could not connect to Pexally validation server.' );
            return false;
        }

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

        if ( isset( $data['license_status'] ) ) {
            update_option( 'pexemail_license_status', sanitize_text_field( $data['license_status'] ) );
            
            if ( $data['license_status'] === 'active' || $data['license_status'] === 'expired' ) {
                update_option( 'pexemail_license_details', [
                    'licensed_email' => sanitize_email( $data['licensed_email'] ?? $user_email ),
                    'expires_at'     => intval( $data['expires_at'] ?? 0 ),
                ]);
                delete_option( 'pexemail_license_error' );
                return true;
            } else {
                $error_msg = ! empty( $data['license_message'] ) ? $data['license_message'] : 'Invalid license key.';
                update_option( 'pexemail_license_error', sanitize_text_field( $error_msg ) );
                return false;
            }
        }

        return false;
    }

}