<?php
namespace WpAssetCleanUpPro\Admin;

use WpAssetCleanUp\Admin\MainAdmin;
use WpAssetCleanUp\Misc;

/**
 * Class LicenseAdminPro
 * @package WpAssetCleanUpPro
 */
class LicensePro
{
	/**
	 *
	 */
	public function init()
	{
		add_action('admin_init',          array($this, 'activateLicense'));
		add_action('admin_init',          array($this, 'markLicenseAsActive'));
		add_action('admin_init',          array($this, 'deactivateLicense'));
		add_action('wpacu_admin_notices', array($this, 'adminNotices'));

		// In the plugins page, make sure to explain that the license has to be added and activated to qualify for Dashboard updates
		add_action('in_plugin_update_message-'.plugin_basename(WPACU_PLUGIN_FILE), array($this, 'licenseNotActivated'), 10, 2);

		add_action('admin_footer', array($this, 'getLicenseInfoScripts'));

	    add_action('wp_ajax_'.WPACU_PLUGIN_ID.'_get_license_info', array($this, 'ajaxGetLicenseInfo'));
	}

	/**
	 *
	 */
	public function licensePage()
	{
		$license = get_option(WPACU_PLUGIN_ID . '_pro_license_key');
		$status  = get_option(WPACU_PLUGIN_ID . '_pro_license_status');

        $data = array(
            'license' => $license,
            'status'  => $status
        );

        // There are issues on some servers where the connection is not established to the remote server
        // This is a temporary fix that will remove the annoying "license is expired" message
        if (isset($_GET['wpacu_force_active'])) {
            update_option(WPACU_PLUGIN_ID . '_pro_license_status', 'valid');
        }

		MainAdmin::instance()->parseTemplate('admin-page-license', $data, true);
	}

	/**
     * @noinspection PhpUndefinedVariableInspection
     */
	public function activateLicense()
	{
		// listen for our activate button to be clicked
		if ( ! isset( $_POST['wpacu_license_activate'] ) ) {
			return;
		}

		// run a quick security check
		$nonceValue = Misc::getVar('post',WPACU_PLUGIN_ID . '_pro_nonce');
		if ( ! wp_verify_nonce($nonceValue, WPACU_PLUGIN_ID . '_pro_nonce') ) {
			$message = esc_html__('The security nonce is not valid. Please retry!', 'wp-asset-clean-up');
			$this->activationErrorRedirect($message); // stop here and redirect
		}

		// retrieve the license from the input
        $licenseKeyInputName = WPACU_PLUGIN_ID . '_pro_license_key';
		$licenseKeyValue = (isset($_POST[$licenseKeyInputName]) && trim($_POST[$licenseKeyInputName]) !== '') ? trim(sanitize_text_field($_POST[$licenseKeyInputName])) : '';

		// data to send in our API request
		$apiParams = array(
			'edd_action'      => 'activate_license',
			'activation_type' => 'manual',
			'license'         => $licenseKeyValue,
			'item_id'         => WPACU_PRO_PLUGIN_STORE_ITEM_ID, // The ID of the item in EDD Store
			'url'             => home_url()
		);

		// Call the custom API.
		$response = wp_remote_post(
			WPACU_PRO_PLUGIN_STORE_LICENSE_ACTION_URL,
			array(
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $apiParams
			)
		);

		// make sure the response came back okay
		if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            if ( is_wp_error($response) ) {
                $errorResponseMessage = $response->get_error_message();

                $message = ( $errorResponseMessage !== '' )
                        ? $errorResponseMessage
                        : __( 'An error occurred, please try again.', 'wp-asset-clean-up' );
            } else {
                // $response is array here (wp_remote_post success but non-200 code)
                $code   = (int) wp_remote_retrieve_response_code($response);
                $reason = wp_remote_retrieve_response_message($response);
                $reason = is_string($reason) ? sanitize_text_field($reason) : '';

                // Keep it user-friendly; include details only if available
                $message = __( 'An error occurred, please try again.', 'wp-asset-clean-up' );

                if ( $code ) {
                    $message .= ' (HTTP ' . $code . ( $reason !== '' ? ' - ' . $reason : '' ) . ')';
                }
            }
		} else {
			$licenseData = json_decode(wp_remote_retrieve_body($response));

			if (isset($licenseData->error, $licenseData->upgrades_output) && $licenseData->error === 'no_activations_left') {
                set_transient(WPACU_PLUGIN_ID . '_no_activations_left_upgrades_output', $licenseData->upgrades_output, 30);
            }

			if (false === $licenseData->success) {
				switch ($licenseData->error) {
					case 'expired':
					    $dateFormatted = date_i18n( get_option( 'date_format' ), strtotime( $licenseData->expires, current_time( 'timestamp' ) ) );
					    $licenseRenewalUrl = self::generateRenewalLink($licenseKeyValue, $licenseData);

						$message = 'expired';
					    $messageToPrint = sprintf(
							__('The license key you submitted expired on %s. %s %sRenew it now (%s off)%s', 'wp-asset-clean-up'),
							$dateFormatted,
                            '&nbsp;<span style="color: green;" class="dashicons dashicons-update"></span>',
                            '<a target="_blank" style="font-weight: bold; color: green;" href="'.$licenseRenewalUrl.'">',
                            '15%',
                            '</a>'
						);

					    set_transient(WPACU_PLUGIN_ID . '_license_activation_failed_msg', $messageToPrint);

						Misc::addUpdateOption( WPACU_PLUGIN_ID . '_pro_license_key', $licenseKeyValue);
						Misc::addUpdateOption( WPACU_PLUGIN_ID . '_pro_license_status', 'expired');
						break;

					case 'revoked':
						$message = esc_html__('Your license key has been disabled.', 'wp-asset-clean-up');
						break;

					case 'missing':
						$message = esc_html__('The license you submitted is invalid. Please update your license key with the one you received in your purchase email receipt and then activate it.', 'wp-asset-clean-up');
						break;

					case 'invalid':
					case 'site_inactive' :
						$message = esc_html__('Your license is not active for this URL.', 'wp-asset-clean-up');
						break;

					case 'item_name_mismatch':
						$message = sprintf(esc_html__('This appears to be an invalid license key for %s.', 'wp-asset-clean-up'), WPACU_PRO_PLUGIN_STORE_ITEM_NAME);
						break;

					case 'no_activations_left':
						$message = esc_html__('Your license key has reached its activation limit.', 'wp-asset-clean-up') . ' '.
						           esc_html__('You can increase the limit by upgrading the license type.', 'wp-asset-clean-up');
						break;

					default:
						$message = esc_html__('An error occurred, please try again.', 'wp-asset-clean-up');
						break;
				}
			}
		}

		// Check if anything passed on a message constituting a failure
		if ( ! empty($message) ) {
			wp_redirect(add_query_arg(
				array( 'wpacu_pro_activation' => 'false', 'message' => urlencode( $message ) ),
				esc_url( admin_url( 'admin.php?page=' . WPACU_PLUGIN_ID . '_license' ) )
			));
			exit();
		}

		// $licenseData->license will be either "valid" or "invalid"
		Misc::addUpdateOption( WPACU_PLUGIN_ID . '_pro_license_status', $licenseData->license);

		$baseUrl = esc_url(admin_url( 'admin.php?page=' . WPACU_PLUGIN_ID . '_license'));

		if ($licenseData->license === 'valid') {
			Misc::addUpdateOption( WPACU_PLUGIN_ID . '_pro_license_key', $licenseKeyValue);
			Misc::addUpdateOption( WPACU_PLUGIN_ID . '_pro_license_status', $licenseData->license);
		    $redirect = add_query_arg(array('wpacu_pro_activation' => 'true'), $baseUrl);
		    set_transient(WPACU_PLUGIN_ID . '_license_just_activated', true, 30);
		} else {
		    $redirect = $baseUrl;
		}

		wp_redirect($redirect);
		exit();
	}

	/**
	 *
	 */
	public function markLicenseAsActive()
    {
        if ( ! empty($_REQUEST) && Misc::getVar('request', 'wpacu_mark_license_valid_button') !== '' ) {
	        // retrieve the license from the input
	        $licenseKeyInputName = WPACU_PLUGIN_ID . '_pro_license_key';
	        $licenseKeyValue = (isset($_POST[$licenseKeyInputName]) && trim($_POST[$licenseKeyInputName]) !== '') ? trim(sanitize_text_field($_POST[$licenseKeyInputName])) : '';

	        Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_key', $licenseKeyValue);
	        Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'valid');

	        wp_redirect(add_query_arg(
		        array('wpacu_pro_activation' => 'true'),
		        esc_url(admin_url('admin.php?page=' . WPACU_PLUGIN_ID . '_license'))
	        ));
	        exit();
        }
    }

    /*
      * Illustrates how to deactivate a license key.
      * This will decrease the site count
    */
	/**
	 *
	 */
	public function deactivateLicense()
	{
        // listen for our activate button to be clicked
        if ( ! isset( $_POST['wpacu_license_deactivate']) ) {
            return;
        }

		// run a quick security check
        $nonceValue = Misc::getVar('post',WPACU_PLUGIN_ID . '_pro_nonce');

	 	if ( ! wp_verify_nonce($nonceValue, WPACU_PLUGIN_ID . '_pro_nonce') ) {
	 	    $message = __('The security nonce is not valid. Please retry!', 'wp-asset-clean-up');
		    $this->deactivationErrorRedirect($message); // stop here and redirect
	 	}

		// retrieve the license from the database
		$license = trim(get_option( WPACU_PLUGIN_ID . '_pro_license_key'));

		// data to send in our API request
		$apiParams = array(
			'edd_action' => 'deactivate_license',
			'license'    => $license,
			'item_name'  => urlencode(WPACU_PRO_PLUGIN_STORE_ITEM_NAME), // the exact name of the product in EDD
			'item_id'    => WPACU_PRO_PLUGIN_STORE_ITEM_ID,
			'url'        => home_url()
		);

		// Call the custom API.
		$response = wp_remote_post(WPACU_PRO_PLUGIN_STORE_LICENSE_ACTION_URL, array('timeout' => 15, 'sslverify' => false, 'body' => $apiParams));

		// make sure the response came back okay
		if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
			if (is_wp_error($response)) {
				$message = $response->get_error_message();
			} else {
				$message = __('An error occurred, please try again.', 'wp-asset-clean-up');
			}

			$this->deactivationErrorRedirect($message); // stop here and redirect
		}

		$bodyResponse = wp_remote_retrieve_body($response);

		// The key is no longer valid (if it ever was)
		if (stripos($bodyResponse, 'invalid license key') !== false) {
			delete_option(WPACU_PLUGIN_ID . '_pro_license_key');
			delete_option(WPACU_PLUGIN_ID . '_pro_license_status');
		}

		// decode the license data
		$licenseData = json_decode($bodyResponse);

        if ( ! is_object($licenseData) || ! isset($licenseData->license) ) {
            $this->activationErrorRedirect( __( 'An error occurred, please try again.', 'wp-asset-clean-up' ) );
        }

		// $licenseData->license will be either "deactivated" or "failed"
		if (in_array($licenseData->license, array('deactivated', 'failed'))) {
			delete_option(WPACU_PLUGIN_ID . '_pro_license_key');
			delete_option(WPACU_PLUGIN_ID . '_pro_license_status');
		}

        set_transient(WPACU_PLUGIN_ID . '_license_just_deactivated', true, 30);

		wp_redirect( add_query_arg(array('wpacu_pro_deactivation' => 'true'), esc_url(admin_url( 'admin.php?page=' . WPACU_PLUGIN_ID . '_license' ))) );
		exit();
	}

	/**
	 * @param $message
	 */
	public function activationErrorRedirect($message)
    {
	    wp_redirect( add_query_arg(
		    array('wpacu_pro_activation' => 'false', 'message' => urlencode($message)),
		    esc_url(admin_url( 'admin.php?page=' . WPACU_PLUGIN_ID . '_license' ))
	    ) );
	    exit();
    }

    /**
     * @param $message
     *
     * @return void
     */
    public function deactivationErrorRedirect($message)
    {
        wp_redirect( add_query_arg(
            array('wpacu_pro_deactivation' => 'false', 'message' => urlencode($message)),
            esc_url(admin_url( 'admin.php?page=' . WPACU_PLUGIN_ID . '_license' ))
        ) );
        exit();
    }

	/**
      * This is a means of catching errors from the activation method above and displaying it to the customer
	 */
	public function adminNotices()
	{
        if ( ! (isset($_GET['wpacu_pro_activation']) || isset($_GET['wpacu_pro_deactivation'])) ) {
            return;
        }

		static $noticeShown = false;

		// [Activate]
        if (isset($_GET['wpacu_pro_activation'])) {
            switch ($_GET['wpacu_pro_activation']) {
                case 'false':
                    if ( ! $noticeShown && isset($_GET['message']) ) {
                        if ($message = get_transient(WPACU_PLUGIN_ID . '_license_activation_failed_msg')) {
                            delete_transient(WPACU_PLUGIN_ID . '_license_activation_failed_msg');
                        } else {
                            $message = urldecode( $_GET['message'] );
                        }
                        ?>
                        <div class="wpacu-error">
                            <p><?php echo esc_html($message); ?></p>

                            <?php
                            if ($upgradesOutput = get_transient(WPACU_PLUGIN_ID . '_no_activations_left_upgrades_output')) {
                                delete_transient(WPACU_PLUGIN_ID . '_no_activations_left_upgrades_output');
                                echo preg_replace( '@<(script|style|iframe)[^>]*?>.*?</\\1>@si', '', $upgradesOutput );
                             }
                            ?>
                        </div>
                        <?php
                    }
                    $noticeShown = true;
                break;

                case 'true':
                default:
                    $transName = WPACU_PLUGIN_ID . '_license_just_activated';

                    if ( ! $noticeShown && get_transient($transName) ) {
                        delete_transient($transName);
                        ?>
                        <div class="notice notice-success is-dismissible">
                            <span class="dashicons dashicons-yes"></span> <?php _e('The license has been activated successfully.', 'wp-asset-clean-up'); ?>
                        </div>
                        <?php
                    }
                    $noticeShown = true;
                break;
            }
        }
        // [/Activate]

        // [Deactivate]
        if (isset($_GET['wpacu_pro_deactivation'])) {
            switch ($_GET['wpacu_pro_deactivation']) {
                case 'false':
                    // The message is always in the query string-
                    if ( ! $noticeShown && isset($_GET['message']) ) {
                        $message = urldecode( $_GET['message'] );
                        ?>
                        <div class="wpacu-error">
                            <p><?php echo esc_html($message); ?></p>
                        </div>
                        <?php
                    }
                    $noticeShown = true;
                    break;

                case 'true':
                default:
                    $transName = WPACU_PLUGIN_ID . '_license_just_deactivated';

                    if ( ! $noticeShown && get_transient($transName) ) {
                        delete_transient($transName);
                        ?>
                        <div class="notice notice-success is-dismissible">
                            <span class="dashicons dashicons-yes"></span> <?php _e('The license has been deactivated successfully.', 'wp-asset-clean-up'); ?>
                        </div>
                        <?php
                    }
                    $noticeShown = true;
                    break;
            }
        }
        // [/Deactivate]
    }

	/**
	 * @param $pluginData
	 * @param $response
	 */
	public function licenseNotActivated($pluginData, $response)
	{
		static $shownLicenseNotActivatedMessage = false;

		$license = get_option( WPACU_PLUGIN_ID . '_pro_license_key');
		$status  = get_option( WPACU_PLUGIN_ID . '_pro_license_status');

		if ((($status !== 'valid') || (! $license)) && (! $shownLicenseNotActivatedMessage)) {
			echo '<strong><a href="'.esc_url(admin_url('admin.php?page=wpassetcleanup_license')).'">'.
			     '&nbsp;&nbsp;<span class="dashicons dashicons-warning"></span>&nbsp;'.'Please make sure you have a valid license activated in "License" plugin\'s page to qualify for plugin updates.'
			     .'</a></strong>';
			$shownLicenseNotActivatedMessage = true;
		}
	}

	/**
	 *
	 */
	public function getLicenseInfoScripts()
	{
		global $current_screen;

		$licenseKeyValue = get_option(WPACU_PLUGIN_ID . '_pro_license_key');

		if ( ! $licenseKeyValue ) {
		    return;
		}

        $currentPageIsPluginLicense = isset($_GET['page']) && $_GET['page'] === WPACU_PLUGIN_ID.'_license';

        // Trigger every {$hoursMax} hours (or whenever they are accessed, it could be after 10 hours since last time)
        // the plugin license check on any plugin page and a few key pages from the Dashboard
        $currentlyOnPagesToTriggerEveryXTime =
	        (isset($_GET['page']) && is_string($_GET['page']) && (strpos($_GET['page'], WPACU_PLUGIN_ID.'_') === 0)) ||
            $current_screen->base === 'dashboard' ||
            $current_screen->base === 'plugins' ||
            $current_screen->base === 'update-core';

		$triggerIf = $currentPageIsPluginLicense || $currentlyOnPagesToTriggerEveryXTime;

		if ( ! $triggerIf ) {
			return; // Nothing to check here
		}

		// Outside plugin's "License" page; Don't check too often
		if ( ! $currentPageIsPluginLicense && $currentlyOnPagesToTriggerEveryXTime ) {
            $lastTimeCheckOutsideLicensePage = get_transient(WPACU_PLUGIN_ID . '_last_time_check_outside_license_page');

            if ($lastTimeCheckOutsideLicensePage) {
	            $hoursMax = 8;

                $diffFromLastCheckUntilNowSeconds = (time() - $lastTimeCheckOutsideLicensePage);

                if (($diffFromLastCheckUntilNowSeconds / 3600) < $hoursMax) {
                    // If less than $hoursMax hours have passed since the last check, don't trigger it
                    return;
                }
		    }

			set_transient(WPACU_PLUGIN_ID . '_last_time_check_outside_license_page', time());
		}

        $anyPreviousResponseArray = get_option(WPACU_PLUGIN_ID . '_pro_license_response', array());
		?>
		<script type="text/javascript">
            /*
             *
            */
            function wpacuUpdateLicenseStatusFromMenu($, wpacuJsonResponse)
            {
                var wpacuLicenseStatusUpdated = wpacuJsonResponse.new_license_status;
                var wpacuLicenseStatus        = wpacuJsonResponse.license_status;

                var wpacuMenuLicenseTargetEl  = '.wpacu-tab-current .extra-info.license-status';

                // Update the status from the top menu within "License" tab
                if ($(wpacuMenuLicenseTargetEl).length > 0) {
                    /*
                     * The license status was updated during the checking (e.g. from expired to valid as the license was renewed)
                     */
                    if (wpacuLicenseStatusUpdated === 'valid') {
                        $(wpacuMenuLicenseTargetEl).removeClass('inactive').addClass('active').html('active');
                        $('#wpacu-sidebar-menu-license-status').hide();
                    } else {
                        /*
                         * No license status was updated during the checking (e.g. from expired to active after a license renewal)
                         */
                        if (wpacuLicenseStatus === 'expired') {
                            $(wpacuMenuLicenseTargetEl).removeClass('active').addClass('inactive').html('expired');
                        } else if (wpacuLicenseStatus === 'site_inactive' || wpacuLicenseStatus === 'invalid') {
                            // e.g. Moved from one domain to another without reactivating the license
                            $(wpacuMenuLicenseTargetEl).removeClass('active').addClass('inactive').html('inactive');
                        } else if (wpacuLicenseStatus === 'disabled') {
                            // e.g. Moved from one domain to another without reactivating the license
                            $(wpacuMenuLicenseTargetEl).removeClass('active').addClass('inactive').html('disabled');
                        } else if (wpacuLicenseStatus === 'active') {
                            $(wpacuMenuLicenseTargetEl).removeClass('inactive').addClass('active').html('active');
                            $('#wpacu-sidebar-menu-license-status').hide();
                        }
                    }
                }
            }

            if ('undefined' !== typeof window.jQuery) {
                jQuery(document).ready(function ($) {
                    $.ajax('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
                        type: 'POST',
                        cache: false,
                        data: {
                            action: '<?php echo WPACU_PLUGIN_ID . '_get_license_info'; ?>',
                            time_r: new Date().getTime()
                        },

                        success: function (response) { // Callback
                            try {
                                var wpacuResponseJson = $.parseJSON(response);
                            } catch (e) {
                                var wpacuResponseJson = '<?php echo wp_json_encode($anyPreviousResponseArray) ?>';
                            }

                            // The current site was deactivated from the Dashboard or the Customer Dashboard
                            // It should not be kept as active, thus the license details will be removed
                            // The client could re-activate it, if it will ever be the case
                            if (wpacuResponseJson && wpacuResponseJson.site_not_activated == 1) {
                                window.location.href = wpacuResponseJson.redirect_to;
                                return;
                            }

                            if ( ! wpacuResponseJson.output ) {
                                var wpacuLicenseStatusHtml = '<span style="font-size: 20px;">❗</span><em>There was an error in fetching the details of the license. The functionality of the plugin is not affected. Please check this page later! '+
                                    'If this error persists, please <a target="_blank" href="https://www.gabelivan.com/contact/?utm_source=wpacu_pro_plugin_license_page&utm_medium=wpacu_json_response_error">submit a ticket</a>!</em>';

                                $('#wpacu-license-form').html(wpacuLicenseStatusHtml);
                            } else {
                                wpacuUpdateLicenseStatusFromMenu(jQuery, wpacuResponseJson);

                                var wpacuOutputTableRows   = wpacuResponseJson.output,
                                    wpacuRenewalLink       = wpacuResponseJson.renewal_link,
                                    wpacuLicenseStatusHtml = wpacuResponseJson.license_status_html;

                                // In case there are glitches and duplicate values are printed
                                $('tr.wpacu-license-extra-info').remove();

                                // Append the extra license info to the table
                                $('#wpacu-license-table-info tbody').prepend(wpacuOutputTableRows);

                                // Set renew license link
                                $('#wpacu-license-renewal-link').show().find('a').attr('href', wpacuRenewalLink);

                                if (wpacuLicenseStatusHtml) {
                                    $('#wpacu-license-status-area').html(wpacuLicenseStatusHtml);
                                }

                                // Show the fetched response
                                $('#wpacu-license-table-info').removeClass('wpacu_hide');
                            }

                            // Hide the loading spinner as the license page information has been updated
                            // Either with the latest information or a fetch error
                            $('#wpacu-license-spinner-for-all-info').hide();
                        }
                    });
                });
            }
		</script>
		<?php
	}

    /**
     * @param $licenseKey
     * @param $itemId
     *
     * @return string
     */
    public static function generateCacheFileNameFromLicenseKey($licenseKey, $itemId = 17193)
    {
        $licensePrefix = substr($licenseKey, 0, 5);  // First 5 characters
        $licenseSuffix = substr($licenseKey, -5);   // Last 5 characters

        // Reverse the license key for added uniqueness
        $reversedLicense = strrev($licenseKey);

        // Generate a secure cache key using combinations of values
        return hash('sha256', $licensePrefix . $itemId .  $reversedLicense . $licenseSuffix);
    }

    /**
     * Check license via AWS: fallback to the default server
     *
     * @param string $licenseKey
     * @param int    $itemId
     * @return array|null - if valid, it would return the JSON format
     */
    public static function checkLicenseViaAwsGetJson($licenseKey, $itemId)
    {
        $hash  = self::generateCacheFileNameFromLicenseKey($licenseKey, $itemId);

        $s3Url = 'https://wpacu-p.s3.amazonaws.com/cache/' .
                 'check-license-' . $itemId . '/' . $hash . '.json';

        // Facem request GET la S3
        $response = wp_remote_get($s3Url, array(
            'timeout'   => 5, // short
            'sslverify' => true
        ));

        // Dacă există eroare de rețea
        if (is_wp_error($response)) {
            return null; // fallback la serverul principal
        }

        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode !== 200) {
            return null; // fallback
        }

        $body = wp_remote_retrieve_body($response);

        $json = json_decode( $body ); // obiect (stdClass), nu array

        // Dacă JSON-ul e invalid sau nu are "license" setat
        if ( json_last_error() !== JSON_ERROR_NONE || ! is_object( $json ) || ! isset( $json->license ) || $json->license === '' ) {
            return null; // fallback
        }

        return $json; // JSON valid din S3
    }

    /**
     * @param $licenseKeyValue
     * @param $itemId
     *
     * @return array|\WP_Error - if valid, it will return the response
     */
    public static function checkLicenseViaMainGetResponse($licenseKeyValue, $itemId)
    {
        // data to send in our API request
        $apiParams = array(
            'edd_action' => 'check_license',
            'license'    => $licenseKeyValue,
            'item_id'    => $itemId, // The ID of the item in EDD Store
            'url'        => home_url()
        );

        $apiUrl = add_query_arg(array(
            'wpacu_license_action' => 'check'
        ), WPACU_PRO_PLUGIN_STORE_LICENSE_ACTION_URL);

        // Call the custom API.
        $response = wp_remote_post(
            $apiUrl,
            array(
                'timeout'   => 15,
                'sslverify' => false,
                'body'      => $apiParams
            )
        );

        return $response;
    }

    /**
     * @param $licenseKeyValue
     * @param $itemId
     *
     * @return array|null
     */
    public static function checkLicenseViaMainGetJson($licenseKeyValue, $itemId)
    {
        $response = self::checkLicenseViaMainGetResponse($licenseKeyValue, $itemId);

        // Dacă există eroare de rețea
        if (is_wp_error($response)) {
            return null;
        }

        $statusCode = wp_remote_retrieve_response_code($response);

        if ($statusCode !== 200) {
            return null;
        }

        $body = wp_remote_retrieve_body($response);

        $json = json_decode( $body ); // obiect (stdClass), nu array

        // Dacă JSON-ul e invalid sau nu are "license" setat
        if ( json_last_error() !== JSON_ERROR_NONE || ! is_object( $json ) || ! isset( $json->license ) || $json->license === '' ) {
            return null; // fallback
        }

        return $json; // JSON valid din S3
    }

    /**
	 * Triggered in /wp-admin/admin-ajax.php
	 */
	public function ajaxGetLicenseInfo()
	{
		// Triggered in /wp-admin/admin-ajax.php
		$licenseKeyValue         = trim(get_option(WPACU_PLUGIN_ID . '_pro_license_key'));
		$licenseKeyCurrentStatus = trim(get_option(WPACU_PLUGIN_ID . '_pro_license_status'));

		$isRightAction           = isset($_POST['action']) && ($_POST['action'] === WPACU_PLUGIN_ID.'_get_license_info');
        
        if ( ! $isRightAction || ! $licenseKeyValue ) {
            exit();
        }

        $useFallback = true; // default

        // First, check AWS
        $licenseData = self::checkLicenseViaAwsGetJson($licenseKeyValue, WPACU_PRO_PLUGIN_STORE_ITEM_ID);

        if (is_object($licenseData) && isset($licenseData->license) && $licenseData->license !== '') {
            // All good
            $useFallback = false;
        }

        // S3 fetch failed, use the default method
        if ($useFallback) {
            $response = self::checkLicenseViaMainGetResponse($licenseKeyValue, WPACU_PRO_PLUGIN_STORE_ITEM_ID);

            // [Make sure the response came back okay]
            if ( is_wp_error( $response ) ) {
                $errorMessage = $response->get_error_message();

                $responseArray['license_status_html'] = '<span style="color:#cc0000;">' . esc_html( $errorMessage ) . '</span>';

                echo wp_json_encode( $responseArray );
                exit();
            }

            $statusCode = (int) wp_remote_retrieve_response_code( $response );

            if ( $statusCode !== 200 ) {
                $body = wp_remote_retrieve_body( $response );

                // Try to extract a meaningful message from a JSON response (EDD sometimes returns JSON even on errors)
                $json = json_decode( $body );

                $extra = '';

                if ( is_object( $json ) ) {
                    // Common EDD patterns: "error", "message", sometimes "error_description"
                    if ( isset( $json->message ) && $json->message !== '' ) {
                        $extra = $json->message;
                    } elseif ( isset( $json->error_description ) && $json->error_description !== '' ) {
                        $extra = $json->error_description;
                    } elseif ( isset( $json->error ) && is_string( $json->error ) && $json->error !== '' ) {
                        $extra = $json->error;
                    }
                }

                if ( $extra === '' && is_string( $body ) && $body !== '' ) {
                    // Fallback: show a short, sanitized snippet (avoid dumping full HTML)
                    $snippet = wp_strip_all_tags( $body );
                    $snippet = trim( preg_replace( '/\s+/', ' ', $snippet ) );
                    $extra   = substr( $snippet, 0, 180 );
                }

                $html = 'License server returned an unexpected HTTP status code: <strong>' . $statusCode . '</strong>.';

                if ( $extra !== '' ) {
                    $html .= '<br /><em>' . esc_html( $extra ) . '</em>';
                }

                $responseArray['license_status_html'] = '<span style="color:#cc0000;">' . $html . '</span>';

                echo wp_json_encode( $responseArray );
                exit();
            }
            // [/Make sure the response came back okay]

            $licenseData = json_decode(wp_remote_retrieve_body($response));
        }

        $currentSiteUrl = home_url();

        if ($currentSiteUrl) {
            $currentSiteUrlInActivationList = false;

            $cleanCurrentSiteurl = trim(self::getCleanSiteUrl($currentSiteUrl), '/');

            if (isset($licenseData->site_names) && ! empty($licenseData->site_names)) {
                foreach ($licenseData->site_names as $siteNameActivated) {
                    $cleanSiteNameActivated = trim(self::getCleanSiteUrl($siteNameActivated), '/');

                    if ($cleanSiteNameActivated === $cleanCurrentSiteurl) {
                        $currentSiteUrlInActivationList = true;
                        break;
                    }
                }
            }

            if ( ! $currentSiteUrlInActivationList ) {
                // The URL is not in the activation list; it's very likely the website was removed from the activation list
                // within the Dashboard (by the admin), or the Customer Dashboard (by the client)
                // In this case, we will remove the license key and the status
                delete_option(WPACU_PLUGIN_ID . '_pro_license_key');
                delete_option(WPACU_PLUGIN_ID . '_pro_license_status');

                $redirectTo = add_query_arg( array(
                    'page' => WPACU_PLUGIN_ID . '_license',
                    'wpacu_site_not_activated' => 1
                ), esc_url(admin_url('admin.php')) );

                echo wp_json_encode(array('site_not_activated' => 1, 'redirect_to' => $redirectTo));
                exit();
            }
        }

        ob_start();

if (isset($licenseData->price_id) && $licenseData->price_id) {
            ?>
            <tr valign="top" class="wpacu-license-extra-info">
                <th scope="row" valign="top">
                    <?php _e('Activation Limit', 'wp-asset-clean-up'); ?>
                </th>
                <td style="padding-bottom: 18px;">
                    <span style="background: rgba(255, 255, 255, 0.5); border: 1px solid #e7e7e7; border-radius: 4px; padding: 5px;">
                        <?php
                        $licenseLimit = ($licenseData->license_limit === 0) ? 'Unlimited' : $licenseData->license_limit;
                        echo (int)$licenseData->site_count.' / <strong>'.$licenseLimit.'</strong>';
                        ?>
                    </span>
                    <?php
                    echo '&nbsp;&nbsp;';

                    // For any license except the Unlimited one
                    if ($licenseData->license_limit > 0) {
                        if ($licenseLimit === 1) { // Single
                            echo ' &nbsp; If you need to use the license on more than one website, <a target="_blank" href="https://www.gabelivan.com/customer-dashboard/license-update/">click here to view the upgrade options.</a>';
                        } elseif ($licenseLimit > 1) { // Plus
                            if ($licenseData->site_count === $licenseLimit) {
                                echo '&nbsp;You have reached the maximum number of activations.';
                            }
                            echo '&nbsp;If you need to use the license on more websites, <a target="_blank" href="https://www.gabelivan.com/customer-dashboard/license-update/">click here to view the upgrade options.</a>';
                        }
                    }
                    ?>
                </td>
            </tr>
            <?php
        }

        if (isset($licenseData->expires) && $licenseData->expires) {
            ?>
            <tr valign="top" class="wpacu-license-extra-info">
                <th scope="row" valign="top">
                    <?php _e('Expiration Date', 'wp-asset-clean-up'); ?>
                </th>
                <td style="padding-bottom: 18px;">
                    <?php echo date(get_option('date_format'), strtotime($licenseData->expires)); ?>

                    <?php
                    if (isset($licenseData->license) && $licenseData->license === 'expired') {
                        echo ' * <em>this license has to be renewed in order to be eligible for updates &amp; premium customer support</em>';

                        // Mark it as expired
                        Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'expired');
                    }
                    ?>
                </td>
            </tr>
            <?php
        }

        $outputTableRows = ob_get_clean();

        $responseArray = array(
            'output'             => $outputTableRows,
            'license_status'     => $licenseData->license,
            'new_license_status' => '', // if any
            'renewal_link'       => ''  // it will get filled later on
        );

        if (in_array($licenseData->license, array('valid', 'expired', 'site_inactive', 'invalid', 'disabled'))) {
            ob_start();

            if ($licenseData->license === 'valid') {
                    // The license expired (as its current status is set), and it was renewed
                    // Try to re-check it, to update its new status
                    if ($licenseKeyCurrentStatus === 'expired') {
                        $newLicenseData = self::checkLicenseViaMainGetJson($licenseKeyValue, WPACU_PRO_PLUGIN_STORE_ITEM_ID);

                        if ($newLicenseData !== null) {
                            if (isset($newLicenseData->license) && $newLicenseData->license === 'valid' && ! (isset($newLicenseData->error) && $newLicenseData->error)) {
                                Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'valid');
                                $responseArray['new_license_status'] = 'valid';
                            } elseif (isset($licenseData->error) && $licenseData->error === 'no_activations_left') {
                                Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'inactive');
                                $responseArray['new_license_status'] = 'inactive';
                            } else {
                                Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'inactive');
                                $responseArray['new_license_status'] = 'inactive';
                            }
                        }
                    }
            ?>
                <span style="color: green; font-weight: bold;"><span class="dashicons dashicons-yes"></span> <?php _e('active', 'wp-asset-clean-up'); ?>&nbsp;&nbsp;</span>
            <?php } ?>

            <?php  if ($licenseData->license === 'expired') { ?>
                <span style="color: #cc0000; font-weight: bold;"><?php _e('expired', 'wp-asset-clean-up'); ?>&nbsp;&nbsp;</span> <span style="vertical-align: top;" id="wpacu-license-renewal-link">&nbsp;<a href="<?php echo esc_url(self::generateRenewalLink($licenseKeyValue, $licenseData)); ?>" class="button button-primary">Renew License for a 15% discount</a></span>
            <?php } ?>

            <?php if (in_array($licenseData->license, array('site_inactive', 'invalid', 'disabled'))) { ?>
                <span style="color: #cc0000; font-weight: bold;"><span class="dashicons dashicons-warning"></span> <?php
                    if ($licenseData->license === 'invalid') {
                        _e( 'invalid', 'wp-asset-clean-up' );
                        ?>
                        * <small style="font-weight: 300; font-style: italic;">It looks like the license is no longer valid. Please renew it!</small>
                        <?php
                    } elseif ($licenseData->license === 'disabled') {
                        // Mark it as expired
                        Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_status', 'disabled');

                        _e( 'disabled', 'wp-asset-clean-up' );
                        ?>
                        * <small style="font-weight: 300; font-style: italic;">It looks like the license has been disabled. It usually happens when a refund has been issued. If you believe this is a mistake and the license should be active, <a target="_blank" href="https://www.gabelivan.com/contact/">please write a support ticket</a>.</small>
                        <?php
                    } else {
                        _e( 'inactive', 'wp-asset-clean-up' );
                    }
                    ?>&nbsp;&nbsp;</span>
            <?php } ?>
            <?php
            $responseArray['license_status_html'] = ob_get_clean();
        }

        if ($licenseData->license === 'expired' && $responseArray['new_license_status'] === '') {
            $responseArray['renewal_link'] = self::generateRenewalLink($licenseKeyValue, $licenseData);

            Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_renewal_link', $responseArray['renewal_link']);
        }

        if ( $responseArray['new_license_status'] === 'valid' || (isset($licenseData->license) && $licenseData->license === 'valid') ) {
            delete_option(WPACU_PLUGIN_ID . '_pro_license_renewal_link'); // no need to store the renewal link if the license is active
        }

        // Store it, and show it in case the next "check_license" response fetch would fail for any reason
        Misc::addUpdateOption(WPACU_PLUGIN_ID . '_pro_license_response', $responseArray);

        echo wp_json_encode($responseArray);

		exit();
	}

	/**
	 * @param $licenseKeyValue
	 * @param $licenseData
	 *
	 * @return string
	 */
	public static function generateRenewalLink($licenseKeyValue, $licenseData)
	{
		$licenseKeyValueHiddenInUrl = strrev(
			substr_replace(
				$licenseKeyValue,
				str_replace('.', '', uniqid('', true)),
				6,
				20
			)
		);

		// Product ID & Payment ID
		$prIdPayId = strrev( WPACU_PRO_PLUGIN_STORE_ITEM_ID.'/' . $licenseData->payment_id );

		return WPACU_PRO_PLUGIN_STORE_URL.'/checkout/?nocache=true' .
		               '&wpacu_str_one=' . $licenseKeyValueHiddenInUrl .
		               '&wpacu_str_two=' . $prIdPayId;
	}

	/**
	 * @param $licenseKeyValue
	 * @param bool $licenseData
	 *
	 * @return array|bool|mixed|object
	 */
	public function autoActivationAttempt($licenseKeyValue, $licenseData = false)
	{
		// data to send in our API request
		$apiParams = array(
			'edd_action' => 'activate_license',
			'license'    => $licenseKeyValue,
			'item_id'    => WPACU_PRO_PLUGIN_STORE_ITEM_ID, // The ID of the item in EDD Store
			'url'        => home_url()
		);

        $apiUrl = add_query_arg( array(
            'wpacu_activation_type' => 'automatic'
        ), WPACU_PRO_PLUGIN_STORE_LICENSE_ACTION_URL );

		// Call the custom API.
		$response = wp_remote_post(
            $apiUrl,
			array(
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $apiParams
			)
		);

		// make sure the response came back okay
		if ( ! (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) ) {
			// Overwrite the $license_data with a new one, that has the license active
			$licenseData = json_decode( wp_remote_retrieve_body( $response ) );
		}

		return $licenseData;
	}

    /**
     * @param $url
     *
     * @return string
     */
    public static function getCleanSiteUrl($url)
    {
        $url = strtolower( $url );

        // strip www subdomain
        $url = str_replace( array( '://www.', ':/www.' ), '://', $url );

        // strip protocol
        $url = str_replace( array( 'http://', 'https://', 'http:/', 'https:/' ), '', $url );

        $port = parse_url( $url, PHP_URL_PORT );

        if ( $port ) {
            // strip port number
            $url = str_replace( ':' . $port, '', $url );
        }

        return sanitize_text_field( $url );
    }

	}
