<?php 
namespace CCPWProLicenser;

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

use CryptocurrencyWidgetsProREG\CryptocurrencyWidgetsPROBase;

class License_Helper {
	// dynamic value variables for the framework
	public $hcpl_prefix = 'cpl';

	/**
     * instance
     */
    protected static $instance = null;

    public static function get_instance(){
        if(!self::$instance){
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function __construct(){
        require_once CCPWP_PATH . 'admin/CryptocurrencyWidgetsProBase.php';
	
		
        add_action( 'admin_print_styles', [ $this, 'set_admin_style' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'set_admin_scripts' ] );
        add_action('admin_notices', array($this, 'display_license_error_messages'));
		add_filter( 'site_transient_update_plugins', array( $this, 'hide_plugin_update_notice' ) );


        add_action('admin_footer', function () {
            if (isset($_GET['page']) && sanitize_key($_GET['page']) === 'cmc-addons-license' &&
                 (isset($_GET['activated']) ||isset($_GET['deactivated']) || isset($_GET['error']))) { ?>
                <script>
                    (function(){
                    if (history.replaceState) {
                        const url = new URL(location);
                        ['activated','deactivated','error'].forEach(k => url.searchParams.delete(k));
                        history.replaceState({}, '', url);
                    }
                    })();
                </script>
        <?php }
        });

		// Register AJAX + admin-post for BOTH prefixes
		foreach (['cmc','celp', 'ccpw'] as $pref) {
			add_action('wp_ajax_' . $pref . '_refresh_license_ajax',   [$this, 'handle_refresh_license_ajax']);
			add_action('admin_post_' . $pref . '_el_activate_license',  [$this, 'action_activate_license']);
			add_action('admin_post_' . $pref . '_el_deactivate_license',[$this, 'action_deactivate_license']);
		}
		foreach ($this->get_all_contexts() as $context_base) {
			$basename = plugin_basename($context_base['file']); 
			if (!$basename) { continue; }

			add_filter("plugin_action_links_{$basename}", function(array $links) use ($context_base){
				return $this->plugin_dashboard_link_dynamic($links, $context_base);
			});

			add_action("after_plugin_row_{$basename}", function($plugin_file, $plugin_data) use ($context_base){
				$this->plugin_custom_notice_dynamic($plugin_file, $plugin_data, $context_base);
			}, 10, 2);
		}
    }

	public function hide_plugin_update_notice($transient){		
		foreach ($this->get_all_contexts() as $context_base) {
			$base = $context_base['base'];
			$plugin_basename = plugin_basename($context_base['file']);

			$instance = $base::getInstance();
			$update_info = ( $instance && method_exists( $instance, '__plugin_updateInfo' ) )
				? $instance->__plugin_updateInfo()
				: '';
			$license_info = $base::GetRegisterInfo();

			if ( empty($update_info->download_link) || $license_info == null){

				if ( isset( $transient->response ) && isset( $transient->response[$plugin_basename] ) ) {
						unset( $transient->response[$plugin_basename] );
					}
			}
		}
		return $transient;
    }

	private function plugin_dashboard_link_dynamic($links,$context_base) {
		$url  = admin_url('admin.php?page=cool-crypto-registration');
		$text = esc_html__('License', $context_base['textdomain']);
		array_unshift($links, '<a href="'.esc_url($url).'">'.$text.'</a>');
		return $links;
	}

    public function plugin_custom_notice_dynamic($plugin_file, $plugin_data,$context_base){
        $text_domain = $context_base['textdomain'];
        $plugin_name = $context_base['plugin_name'];
		$base  = $context_base['base'];
    	// Get license info and update info for the plugin
		$license_info = $base::GetRegisterInfo();
        
        $instance = $base::getInstance();
        $update_info = ( $instance && method_exists( $instance, '__plugin_updateInfo' ) )
            ? $instance->__plugin_updateInfo()
            : '';

		// Get version available message using common helper
		$version_available_message = License_Helper::getVersionAvailableMessage($context_base);

		if ( ! $this->is_license_valid($context_base)) {	
			$renew_link = wp_kses_post(
				__( $version_available_message.' Please <a href="admin.php?page=cool-crypto-registration">enter your license key</a> to enable automatic updates and premium support for '.$plugin_name.' Plugin.', $text_domain ),
				array(
					'a' => array(
						'href' => array()
					)
				)
			);

		} else {
			// Check if new version is available and license is invalid/expired            

			if (empty( $update_info->download_link ) && ($this->is_support_expired($license_info) === true || $license_info->is_valid === 'license_expired')) {	
				$is_expired = (empty($update_info->is_downloadable) && $this->is_support_expired($license_info) !== true) ? 'license' : 'support';
                if($this->is_support_expired($license_info) === true && $license_info->is_valid === 'license_expired'){
                    $is_expired = 'license';
                }
				$message = ' Your ' . $is_expired . ' has expired,';
				$renew_text = ( ! empty( $license_info->market ) && $license_info->market === 'E' ) 
				? 'Please renew your ' . $is_expired . ' to continue receiving automatic updates and priority support.'
				: 'Please <a href="https://my.coolplugins.net/account/subscriptions/" target="_blank">Renew now</a> to continue receiving automatic updates and priority support.';	
				$renew_link = $version_available_message . $message . ' ' . $renew_text;
			}
		}

		if ( ! empty( $renew_link )) {
			?>
            <style>
					.plugins tr.active[data-plugin="<?php echo esc_attr($plugin_file); ?>"]
					th,
					.plugins tr.active[data-plugin="<?php echo esc_attr($plugin_file); ?>"]
					td 
					{
					 box-shadow: none;
					}
			</style>
			<tr class="plugin-update-tr active">
				<td colspan="4" class="plugin-update colspanchange">
					<div class="update-message notice inline notice-warning notice-alt"> 
						<p><?php echo wp_kses_post( $renew_link ); ?></p>
					</div>
				</td>
			</tr>
			<?php
		}  
    }


    public function set_admin_style(){
		if(isset($_GET['page']) && sanitize_text_field( $_GET['page'] ) === 'cool-crypto-registration'){
			if(defined('CMC_URL') && defined('CMC_PLUGIN_DIR')){
				if(file_exists(CMC_PLUGIN_DIR. 'admin/licensor-helper/assets/css/license.css')){
					wp_register_style( "cool-crypto-license-css", CMC_URL. 'admin/licensor-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "cool-crypto-license-css" );
				}
			}
			if(defined('CELP_URL') && defined('CELP_PATH')){
				if(file_exists(CELP_PATH. 'admin/licensor-helper/assets/css/license.css')){
					wp_register_style( "cool-crypto-license-css", CELP_URL. 'admin/licensor-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "cool-crypto-license-css" );	
				}
			}
			if(defined('CCPWP_URL') && defined('CCPWP_PATH')){
				if(file_exists(CCPWP_PATH. 'admin/licensor-helper/assets/css/license.css')){
					wp_register_style( "cool-crypto-license-css", CCPWP_URL. 'admin/licensor-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "cool-crypto-license-css" );	
				}
			}

		}
    }

    public function set_admin_scripts(){
        if(isset($_GET['page']) && sanitize_text_field( $_GET['page'] ) === 'cool-crypto-registration'){

			if(defined('CMC_URL') && defined('CMC_PLUGIN_DIR')){
				if(file_exists(CMC_PLUGIN_DIR. 'admin/licensor-helper/assets/js/crypto-license-setting.js')){	
					wp_enqueue_script(
						'cmc-license-setting',
						CMC_URL . 'admin/licensor-helper/assets/js/crypto-license-setting.js',
						array('jquery'),
						CMC,
						true
					);
					// Localize script with AJAX nonce
					wp_localize_script('cmc-license-setting', 'cmc_ajax', array(
						'nonce' => wp_create_nonce('cmc_refresh_license_nonce')
					));
				}
			}
			if(defined('CELP_URL') && defined('CELP_PATH')){
				if(file_exists(CELP_PATH. 'admin/licensor-helper/assets/js/crypto-license-setting.js')){					
					wp_enqueue_script(
						'celp-license-setting',
						CELP_URL . 'admin/licensor-helper/assets/js/crypto-license-setting.js',
						array('jquery'),
						CELP_VERSION,
						true
					);
							
					// // Localize script with AJAX nonce
					wp_localize_script('celp-license-setting', 'celp_ajax', array(
						'nonce' => wp_create_nonce('celp_refresh_license_nonce')
					));	
				}
			}
			if(defined('CCPWP_URL') && defined('CCPWP_PATH')){
				if(file_exists(CCPWP_PATH. 'admin/licensor-helper/assets/js/crypto-license-setting.js')){
					wp_enqueue_script(
						'ccpwp-license-setting',
						CCPWP_URL . 'admin/licensor-helper/assets/js/crypto-license-setting.js',
						array('jquery'),
						CCPWP_VERSION,
						true
					);
							
					// Localize script with AJAX nonce
					wp_localize_script('ccpwp-license-setting', 'ccpw_ajax', array(
						'nonce' => wp_create_nonce('ccpw_refresh_license_nonce')
					));	
				}
			}
        }
    }

	public function get_all_contexts() {
		$list = [];
		$cmc = $this->crypto_context_resolver('cmc_license_registration');
		if (!empty($cmc['file'])) $list[] = $cmc;

		$celp = $this->crypto_context_resolver('celp_license_registration');
		if (!empty($celp['file'])) $list[] = $celp;

		$ccpw = $this->crypto_context_resolver('ccpw_license_registration');
		if (!empty($ccpw['file'])) $list[] = $ccpw;

		return $list;
	}

    public function display_license_error_messages() {
		$textdomain = 'cool-crypto';
        if (isset($_GET['page']) && $_GET['page'] === 'cool-crypto-registration') {
              
            // Display error message if exists
            if (isset($_GET['error'])) {
                $error_message = $this->cmc_get_error_message($_GET['error']);
                ?>
                <div class="notice notice-error is-dismissible">
					<?php if($error_message === 'Response Error, contact with the author or update the plugin or theme.'){ 
						echo '<p>There is an issue with your account. Please contact our plugin support team by <a href="https://cryptocurrencyplugins.com/support/?utm_source=cmc_plugin&utm_medium=inside&utm_campaign=support&utm_content=license_dashboard" target="_blank">clicking here</a>.</p>';
					 } else { ?>
                    <p><?php echo esc_html($error_message); ?></p>
					<?php } ?>
                </div>
                <?php
            }

            // Display success message
            if (isset($_GET['activated']) && $_GET['activated'] === 'true') {
                ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php _e('License activated successfully!', $textdomain); ?></p>
                </div>
                <?php
            }

            // Display deactivation message
            if (isset($_GET['deactivated']) && $_GET['deactivated'] === 'true') {
                ?>
                <div class="notice notice-info is-dismissible">
                    <p><?php _e('License deactivated successfully!', $textdomain); ?></p>
                </div>
                <?php
            }
        }
    }

    public function handle_refresh_license_ajax(){
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->crypto_context_resolver($page);
		$base    = $base_context['base'];
		$prefix    = $base_context['prefix'];
		$file    = $base_context['file'];
		$section_id    = $base_context['section_id'];
		$textdomain    = $base_context['textdomain'];
        // Check nonce for security
        if (!wp_verify_nonce($_POST['nonce'], $prefix.'_refresh_license_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
            return;
        }

        $this->check_user_capabilities();
            
        // Get existing license key and email
        $license_key    = $this->get_license_key($prefix,$section_id);
        $license_email  = $this->get_license_email($prefix,$section_id);
        if (empty($license_key) || empty($license_email)) {
            wp_send_json_error(array('message' => 'No license information found to refresh.'));
            return;
        }

        $error = '';
        $response_obj = null;
        // Use the same activation logic to refresh the license
        if ($this->plugin_activate_license($base,$license_key, $license_email, $error, $response_obj,$file,$section_id,$base_context)) {      
            // Get updated license information
            $license_info = array(
                'is_valid' => $response_obj->is_valid ? $response_obj->is_valid:false,
                'license_title' => $response_obj->license_title ? $response_obj->license_title : '',
                'expire_date' => $response_obj->expire_date ? $response_obj->expire_date : '',
                'market' => $response_obj->market ? $response_obj->market : '',
                'support_end' => $response_obj->support_end ? $response_obj->support_end : '',
            );    
            wp_send_json_success(array(
                'message' => 'License Status Updated successfully!',
                'license_info' => $license_info,
                'version_available_message' => License_Helper::getVersionAvailableMessage($base_context)
            ));
        } else {
            // Map error message to error code
            $error_code = $this->cmc_map_error_to_code($error);
            $error_message = $this->cmc_get_error_message($error_code);
            wp_send_json_error(array('message' => $error_message));
        }
    }

    public function check_user_capabilities() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
    }

    public function cmc_map_error_to_code($error) {
            $error = strtolower($error);
           
            if (strpos($error, 'invalid') !== false) {
                return 'invalid_key';
            } elseif (strpos($error, 'disabled') !== false || strpos($error, 'temporary inactivated') !== false || strpos($error, 'inactive_license') !== false) {
                return 'disabled';
            } elseif (strpos($error, 'license quota has been over') !== false || strpos($error, 'installed on another domain') !== false) {
                return 'no_activations';
            } elseif (strpos($error, 'refunded') !== false || strpos($error, 'refunded_license') !== false) {
                return 'refunded';
            } elseif (strpos($error, 'expired') !== false) {
                return 'expired';
            } elseif (strpos($error, 'wrong_license_status') !== false) {
                return 'wrong_license_status';
            } elseif (strpos($error, 'domain_exceeded') !== false) {
                return 'domain_exceeded';
            }elseif (strpos($error, 'missing_key') !== false) {
                return 'missing_key';
            } elseif (strpos($error, 'missing_email') !== false) {
                return 'missing_email';
            } elseif (strpos($error, 'wrong_email_format') !== false) {
                return 'invalid_email';
            } elseif (strpos($error, 'response error, contact with the author or update the plugin or theme') !== false) {
                return 'response_error';
            }
            return 'default';
    }

    public function cmc_get_error_message($error_code) {        
	    $textdomain = 'cool-crypto';
        $messages = array(
            'missing_key' => __('License key is required.', $textdomain),
            'missing_email' => __('Email address is required.', $textdomain),
            'invalid_email' => __('Please enter a valid email address.', $textdomain),
            'invalid_format' => __('Invalid license key format. Please check your license key.', $textdomain),
            'invalid_key' => __('Invalid license key. Please check your license key and try again.', $textdomain),
            'expired' => __('Your license key has expired. Please renew your license.', $textdomain),
            'disabled' => __('Your license key has been disabled.', $textdomain),
            'no_activations' => __('License quota has been over, you can not add more domain with this license key.', $textdomain),
            'refunded' => __('Your purchase key has been refunded.', $textdomain),
            'wrong_license_status' => __('Your license key is inactive, has been refunded, or has exceeded the allowed domain limit.', $textdomain),
            'domain_exceeded' => __('Your license key has exceeded the allowed domain limit.', $textdomain),
			'response_error' => __('Response Error, contact with the author or update the plugin or theme.', $textdomain),
            'default' => __('An error occurred while validating your license. Please try again.', $textdomain)
        );

        return isset($messages[$error_code]) ? $messages[$error_code] : $messages['default'];
    }

    public function plugin_activate_license($base,$licenseKey, $licenseEmail, &$error, &$response_obj,$file,$section_id,$base_context) {  
        if ($base::CheckWPPlugin($licenseKey, $licenseEmail, $error, $response_obj, $file)) {
            $this->update_license_opts( array(
				$base_context['prefix'] . '-purchase-code'  => $licenseKey,
				$base_context['prefix'] . '-client-emailid' => $licenseEmail,
			),
			$section_id
			);
            delete_site_transient('update_plugins');
            return true;
        }
        return false;
    }

    public static function getVersionAvailableMessage($base_context){
		$base = $base_context['base'];
		$file = $base_context['file'];
		$plugin_version = $base_context['version'];
		$textdomain = $base_context['textdomain'];
        // Get license info and update info for the plugin
        $instance = $base::getInstance();
        $update_info = ( $instance && method_exists( $instance, '__plugin_updateInfo' ) )
            ? $instance->__plugin_updateInfo()
            : '';
        // Initialize and sanitize version information
        $latest_version = isset($update_info->new_version) ? sanitize_text_field($update_info->new_version) : '';
        $version_available_message = '';

        // Prepare update available message if current version is outdated
        $plugin_basename = plugin_basename($file);

        if ( ! empty($latest_version) && version_compare($plugin_version, $latest_version, '<') ) {

            list($plugin_slug, $plugin_file) = explode('/', $plugin_basename);

            $plugin_info_url = add_query_arg([
                'tab'       => 'plugin-information',
                'plugin'    => $plugin_slug . '/' . $plugin_file,
                'section'   => 'changelog',
                'TB_iframe' => 'true',
                'width'     => 772,
                'height'    => 390,
            ], admin_url('plugin-install.php'));

            $version_available_message = sprintf(
                /* translators: %s: version number with link */
                __('Version %s is available.', $textdomain),
                sprintf(
                    '<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s">%s</a>',
                    esc_url($plugin_info_url),
                    esc_attr(sprintf(__('View changelog for version %s', $textdomain), $latest_version)),
                    esc_html(sprintf(__('%s (View details)', $textdomain), $latest_version))
                )
            );
        }
        
        return $version_available_message;
    }

	function show_modern_form($section) {
		if (empty($section) || !is_array($section)) {
			return; 
		}
		?>
		<div class="metabox-holder">
			<?php foreach ($section as $form): ?>
				<?php 
				$form_id = isset($form['id']) ? esc_attr($form['id']) : '';
				if (empty($form_id)) {
					continue;
				}
				?>
				<div id="<?php echo $form_id; ?>" class="group" style="display:none;">
					<?php $this->render_page($form_id); ?>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
		$this->script();
	}

	
    function render_page($page){
		$hcpl_prefix = $this->hcpl_prefix;
		$context_base = $this->crypto_context_resolver($page);

		$prefix = $context_base['prefix'];
		$textdomain = $context_base['textdomain'];
		$plugin_name = $context_base['plugin_name'];

        global $wp_settings_sections, $wp_settings_fields;

        ?>
        <div class="wrap">
			<div class="main-content">
				<?php 
				if ( $this->is_license_valid($context_base) ) {
					echo $this->activated_panel($page,$context_base);
				} else {
					echo $this->license_form($page,$context_base);
				}
				?>
				<div class="side-content">
					<div class="<?php echo esc_attr($hcpl_prefix) ?>-dashboard-rate-us">
						<h3><?php _e('Rate Us ⭐⭐⭐⭐⭐', $textdomain); ?></h3>
						<p><?php _e('We\'d love your feedback! If our '.$plugin_name.' has helped you create better timelines.', $textdomain); ?></p>
						<?php if($prefix =='ccpw'): ?>
							<a href="https://wordpress.org/support/plugin/cryptocurrency-price-ticker-widget/reviews/#new-post" class="review-link" target="_blank"><?php _e('Submit a Review →', $textdomain); ?></a>
						<?php else: ?>
							<a href="https://trustpilot.com/review/coolplugins.net" class="review-link" target="_blank"><?php _e('Submit a Review →', $textdomain); ?></a>
						<?php endif; ?>
					</div>
				</div>
			</div>
        </div>
        <?php
    }
	
	function script() {
        ?>
        <script>
            jQuery(document).ready(function($) {
                //Initiate Color Picker
                $('.wp-color-picker-field').wpColorPicker();

                // Switches option sections
                $('.group').hide();
                var activetab = '';
                if (typeof(localStorage) != 'undefined' ) {
                    activetab = localStorage.getItem("activetab");
                }

                //if url has section id as hash then set it as active or override the current local storage value
                if(window.location.hash){
                    activetab = window.location.hash;
                    if (typeof(localStorage) != 'undefined' ) {
                        localStorage.setItem("activetab", activetab);
                    }
                }

                if (activetab != '' && $(activetab).length ) {
                    $(activetab).fadeIn();
                } else {
                    $('.group:first').fadeIn();
                }
                $('.group .collapsed').each(function(){
                    $(this).find('input:checked').parent().parent().parent().nextAll().each(
                    function(){
                        if ($(this).hasClass('last')) {
                            $(this).removeClass('hidden');
                            return false;
                        }
                        $(this).filter('.hidden').removeClass('hidden');
                    });
                });

                if (activetab != '' && $(activetab + '-tab').length ) {
                    $(activetab + '-tab').addClass('nav-tab-active');
                }
                else {
                    $('.nav-tab-wrapper a:first').addClass('nav-tab-active');
                }
                $('.nav-tab-wrapper a').on('click',function(evt) {
                    $('.nav-tab-wrapper a').removeClass('nav-tab-active');
                    $(this).addClass('nav-tab-active').blur();
                    var clicked_group = $(this).attr('href');
                    if (typeof(localStorage) != 'undefined' ) {
                        localStorage.setItem("activetab", $(this).attr('href'));
                    }
                    $('.group').hide();
                    $(clicked_group).fadeIn();
                    evt.preventDefault();
                });

                $('.wpsa-browse').on('click', function (event) {
                    event.preventDefault();

                    var self = $(this);

                    // Create the media frame.
                    var file_frame = wp.media.frames.file_frame = wp.media({
                        title: self.data('uploader_title'),
                        button: {
                            text: self.data('uploader_button_text'),
                        },
                        multiple: false
                    });

                    file_frame.on('select', function () {
                        attachment = file_frame.state().get('selection').first().toJSON();
                        self.prev('.wpsa-url').val(attachment.url).change();
                    });

                    // Finally, open the modal
                    file_frame.open();
                });
        });
        </script>
        <?php
    }
	/* ------------------------------------------
	 * Modern UI: License form (custom Hcpl)
	 * ------------------------------------------ */
	function license_form($page,$context_base){
		$hcpl_prefix = $this->hcpl_prefix;
		$prefix = $context_base['prefix'];
		$section_id = $context_base['section_id'];
		$textdomain = $context_base['textdomain'];
		$plugin_name = $context_base['plugin_name'];
		$purchase_email = $this->get_license_email($prefix,$section_id);

		ob_start(); ?>
			<div class="<?php echo esc_attr($hcpl_prefix) ?>-license-box">
				<div class="wrapper-header">
					<h3>🔐 <?php esc_html_e( $plugin_name .' Activate License', $textdomain ); ?></h3>
				</div>

				<div class="wrapper-body">
					<form class="<?php echo esc_attr($hcpl_prefix) ?>-license-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<input type="hidden" name="action" value="<?php echo esc_attr( $prefix ); ?>_el_activate_license"/>

						<?php 
							$this->render_license_fields_from_settings( $page,$prefix );
						?>

						<?php wp_nonce_field( $prefix . '-el-license' ); ?>

						<div class="<?php echo esc_attr($hcpl_prefix) ?>-el-license-active-btn">
							<?php submit_button( 'Activate' ); ?>
						</div>
					</form>

                    <?php 
                        $this->render_support_buttons($prefix,$textdomain);
                    ?>
				</div>
			</div>
		<?php
		return ob_get_clean();
	}

	/* ------------------------------------------
	 * Modern UI: Activated panel
	 * ------------------------------------------ */
	private function activated_panel($page,$context_base) {
		$hcpl_prefix = $this->hcpl_prefix;
		$base = $context_base['base'];
		$prefix = $context_base['prefix'];
		$section_id = $context_base['section_id'];
		$textdomain = $context_base['textdomain'];
    	$license_info = $base ? $base::GetRegisterInfo() : (object)[];

		ob_start(); ?>
			<div class="<?php echo esc_attr($hcpl_prefix) ?>-license-box">
				<div class="wrapper-header"><h3>🔐 <?php esc_html_e( 'Your License Info', $textdomain ); ?></h3></div>
				<div class="wrapper-body">
				<?php if ( $this->needs_refresh( $license_info ) && $this->should_show_refresh_button( $context_base ) ) : ?>
						<div class="<?php echo esc_attr($hcpl_prefix) ?>-refresh-row">
							<button type="button"
								class="<?php echo esc_attr($prefix) ?>-refresh-btn"
								id="<?php echo esc_attr($hcpl_prefix) ?>-refresh-license-btn"
								data-license-email="<?php echo esc_attr( $this->get_license_email($prefix,$section_id) ); ?>">
								<?php _e( '🔄 Check license status', $textdomain ); ?>
							</button>
						</div>
					<?php endif; ?>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<input type="hidden" name="action" value="<?php echo esc_attr( $prefix ); ?>_el_deactivate_license"/>

						<ul>
							<li>
								<strong><?php esc_html_e( 'Status: ', $textdomain ); ?></strong>
								<span class="<?php echo esc_attr($prefix) ?>-validity">
									<?php if ( $license_info->is_valid ) : ?>
										<?php if ( $this->is_license_expired( $license_info ) ) : ?>
											<strong>❌ <?php esc_html_e( 'License Expired', $textdomain ); ?></strong>
										<?php elseif ( $this->is_support_expired( $license_info ) ) : ?>
											<strong>❌ <?php esc_html_e( 'Support Expired',  $textdomain ); ?></strong>
										<?php else : ?>
											<strong>✅ <?php esc_html_e( 'Valid', $textdomain ); ?></strong>
										<?php endif; ?>
									<?php else : ?>
										<strong>❌ <?php esc_html_e( 'Invalid', $textdomain ); ?></strong>
									<?php endif; ?>
								</span>
							</li>

							<li>
								<strong><?php esc_html_e( 'License Type: ', $textdomain ); ?></strong>
								<strong class="<?php echo esc_attr($hcpl_prefix) ?>-license-type"><?php echo esc_html( $license_info->license_title ?? '' ); ?></strong>
							</li>

							<li>
								<strong><?php esc_html_e( 'Plugin Updates & Support Validity: ', $textdomain ); ?></strong>
								<span class="<?php echo esc_attr($prefix) ?>-validity">
									<?php
									$current_time = time();
									$expire_date_expired = false;

									if ( strtolower( $license_info->expire_date ) !== 'no expiry' ) {
										$expire_date_timestamp = strtotime( $license_info->expire_date );
										$expire_date_expired   = $expire_date_timestamp && $expire_date_timestamp < $current_time;
									}
									// Handle "no support"
									if ( strtolower( $license_info->support_end ) === 'no support' ) {

										esc_html_e( 'No Support', $textdomain );

									} else {
										$support_end_expired = false;

										if ( strtolower( $license_info->support_end ) !== 'unlimited' ) {
											$support_end_timestamp = strtotime( $license_info->support_end );
											$support_end_expired   = $support_end_timestamp && $support_end_timestamp < $current_time;
										}

										if ( $expire_date_expired ) {
											echo esc_html( $this->formatLicenseDate( $license_info->expire_date ) );
										} elseif ( $support_end_expired ) {
											echo esc_html( $this->formatLicenseDate( $license_info->support_end ) );
										} else {
											echo esc_html( $this->formatLicenseDate( $license_info->expire_date ) );
										}
									}
									?>
								</span>

							</li>

							<?php if ( ! empty( $license_info->license_key ) ) : ?>
								<li>
									<strong><?php esc_html_e( 'Your License Key: ', $textdomain ); ?></strong>
									<strong class="license-key">
										<?php
										$lk = (string) $license_info->license_key;
										echo esc_html( substr( $lk, 0, 9 ) . 'XXXXXXXX-XXXXXXXX' . substr( $lk, -9 ) );
										?>
									</strong>
								</li>
							<?php endif; ?>
						</ul>

						<?php wp_nonce_field( $prefix . '-el-license' ); ?>
						
						<div class="<?php echo esc_attr($hcpl_prefix) ?>-submit-button">
							<p><?php esc_html_e( 'Want to deactivate the license for any reason?', $textdomain ); ?></p>
							<?php submit_button( 'Deactivate License' ); ?>
						</div>
					</form>

					<?php if ($this->is_license_expired($license_info)): ?>
						<div class="<?php echo esc_attr($prefix) ?>-newLicense notice notice-error" style="margin-top: 10px; color: #d63638;">
						<?php $this->render_expiry_message($license_info,$context_base, 'license'); ?>
					</div>

					<?php elseif ($this->is_support_expired($license_info)): ?>
						<div class="<?php echo esc_attr($prefix) ?>-newLicense notice notice-error" style="margin-top: 10px; color: #d63638;">
						<?php $this->render_expiry_message($license_info,$context_base, 'support'); ?>
					</div>
					<?php endif; ?>

                    <?php 
                        $this->render_support_buttons($prefix,$textdomain);
                    ?>
				</div>
			</div>
		<?php
		return ob_get_clean();
	}

    public function render_support_buttons($prefix,$textdomain){
		$hcpl_prefix = $this->hcpl_prefix;
        ?>
        <div class="<?php echo esc_attr($hcpl_prefix) ?>-license-support">
		    <p><?php esc_html_e( 'Want to know more about the license key?', $textdomain ); ?></p>
				<div class="<?php echo esc_attr($hcpl_prefix) ?>-support-buttons">
					<a href="https://my.coolplugins.net/account/" target="_blank" class="button button-secondary">
						<?php esc_html_e( 'Check Account', $textdomain ); ?>
					</a>
					<a href="https://cryptocurrencyplugins.com/support/?utm_source=cmc_plugin&utm_medium=inside&utm_campaign=support&utm_content=license_dashboard"
					target="_blank" class="button button-secondary">
						<?php esc_html_e( 'Contact Support', $textdomain ); ?>
					</a>
				</div>
		</div>
        <?php 
    }

	
	private function crypto_context_resolver(string $page): array {
		if (strpos($page, 'cmc_') === 0) {
			return [
				'key'        => 'cmc',
				'prefix'     => 'cmc',
				'plugin_name'     => 'Coins MarketCap',
				'section_id' => 'cmc_license_registration',
				'base'       => class_exists('\CoinMarketCapREG\CoinsMarketCapBase')
								? '\CoinMarketCapREG\CoinsMarketCapBase'
								: null,
				'file'       => defined('CMC_PRO_FILE') ? CMC_PRO_FILE : '',
				'version'    => defined('CMC') ? CMC : '',
				'textdomain' => 'cmc',
				'ajax'       => ['action_refresh' => 'cmc_refresh_license_ajax', 'nonce' => 'cmc_refresh_license_nonce'],
			];
		}else if(strpos($page, 'celp_') === 0){
			return [
				'key'        => 'celp',
				'prefix'     => 'celp',
				'plugin_name'     => 'Cryptocurrency Exchanges List PRO',
				'section_id' => 'celp_license_registration',
				'base'       => '\CryptocurrencyExchangesListProREG\CryptocurrencyExchangesListPROBase',
				'file'       => defined('CELP_FILE') ? CELP_FILE : '',
				'version'    => defined('CELP_VERSION') ? CELP_VERSION : '',
				'textdomain' => 'celp',
				'ajax'       => ['action_refresh' => 'celp_refresh_license_ajax', 'nonce' => 'celp_refresh_license_nonce'],
			];
		}else if(strpos($page, 'ccpw_') === 0){
			return [
				'key'        => 'ccpw',
				'prefix'     => 'ccpw',
				'plugin_name'     => 'Cryptocurrency Price Ticker Widget PRO',
				'section_id' => 'ccpw_license_registration',
				'base'       => '\CryptocurrencyWidgetsProREG\CryptocurrencyWidgetsPROBase',
				'file'       => defined('CCPWP_PRO_FILE') ? CCPWP_PRO_FILE : '',
				'version'    => defined('CCPWP_VERSION') ? CCPWP_VERSION : '',
				'textdomain' => 'ccpw',
				'ajax'       => ['action_refresh' => 'ccpw_refresh_license_ajax', 'nonce' => 'ccpw_refresh_license_nonce'],
			];
		}

	}
    /* ------------------------------------------
	 * License helpers (storage = serialized array)
	 * option:  cmc_license_registration
	 * ------------------------------------------ */

	public function get_license_opts($section_id) {
		$opts = get_option( $section_id, array() );
		return is_array( $opts ) ? $opts : array();
	}

	public function get_license_key($prefix,$section_id) {
		$opts = $this->get_license_opts($section_id);
		return isset( $opts[ $prefix . '-purchase-code' ] ) ? $opts[ $prefix .'-purchase-code' ] : '';
	}

	public function get_license_email($prefix,$section_id) {
		$opts = $this->get_license_opts($section_id);
		return isset( $opts[ $prefix . '-client-emailid' ] ) ? $opts[ $prefix . '-client-emailid' ] : get_bloginfo( 'admin_email' );
	}

	public function update_license_opts( $new,$section_id) {
		$opts = $this->get_license_opts($section_id);
		update_option( $section_id, array_merge( $opts, $new ) );
	}

	public function clear_license_key_only($prefix,$section_id) {
		$opts = $this->get_license_opts($section_id);
		unset( $opts[ $prefix . '-purchase-code' ] );
		update_option( $section_id, $opts );
	}

	public function is_license_valid($context_base) {
		$base = $context_base['base'];
		if (!$base) return false;
		$info = $base::GetRegisterInfo();
		return isset($info);
	}

	public function is_license_expired( $license_info ) {
		return isset( $license_info->is_valid ) && $license_info->is_valid === 'license_expired';
	}

	public function is_support_expired( $license_info ) {
		$end = isset( $license_info->support_end ) ? strtolower( $license_info->support_end ) : '';
		return $end === 'no support'
			|| ( isset( $license_info->is_valid ) && $license_info->is_valid === 'support_expired' )
			|| ( $end !== 'unlimited' && ! empty( $end ) && strtotime( $license_info->support_end ) < time() );
	}

	public function needs_refresh( $license_info ) {
		return $this->is_license_expired( $license_info ) || $this->is_support_expired( $license_info );
	}

	public function should_show_refresh_button( $context_base ) {
		$key = $context_base['key'];
		
		switch ( $key ) {
			case 'ccpw':
				return defined('CCPWP_VERSION') && version_compare( CCPWP_VERSION, '4.1.7', '>' );
			case 'cmc':
				return defined('CMC') && version_compare( CMC, '5.6.7', '>' );
			case 'celp':
				return defined('CELP_VERSION') && version_compare( CELP_VERSION, '2.9.3', '>' );
			default:
				return false;
		}
	}

	public function formatLicenseDate($dateString) {
		if (!empty($dateString) && strtolower($dateString) !== 'no expiry' && strtolower($dateString) !== 'unlimited' && strtolower($dateString) !== 'no support') {
			$date = new \DateTime($dateString);
			return $date->format('d M Y');
		}
		return $dateString;
	}

	public function render_expiry_message($license_info,$context_base,$type = 'license'){
		$text_domain = $context_base['textdomain'];
		// Generate version available message using common helper
		$version_available_message = License_Helper::getVersionAvailableMessage($context_base);
			
		if ($license_info->msg === 'limit_reached') {
			echo wp_kses_post('There was an issue with your account. Please contact our plugin support team by <a href="https://my.coolplugins.net/account/support-tickets/">clicking here</a>.');
			return;
		}
		$message = $type === 'license' 
			? __('Your license has expired,', $text_domain) 
			: __('Your support has expired,', $text_domain);

		$renew_link = isset($license_info->market) && $license_info->market === 'E'
			? ''
			: ' <a href="https://my.coolplugins.net/account/subscriptions/" target="_blank">'.__('Renew now', $text_domain).'</a>';

		$final_message = '';
		// Add version message if available
		if (!empty($version_available_message)) {
			wp_enqueue_script('thickbox');
			wp_enqueue_style('thickbox');	
			$final_message .= wp_kses_post($version_available_message) . ' ';
		}
		// Add license expiry message
		$final_message .= esc_html($message) . $renew_link . esc_html__(' to continue receiving updates and priority support.', $text_domain);	
		echo $final_message;
    }
    
    /* ------------------------------------------
	 * Admin-post handlers
	 * ------------------------------------------ */
    public function action_activate_license() {
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->crypto_context_resolver($page);
    	$prefix    = $base_context['prefix'];
    	$base    = $base_context['base'];
    	$file    = $base_context['file'];
		$section_id    = $base_context['section_id'];
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Unauthorized' );
		}
		check_admin_referer( $prefix . '-el-license' );

        if(empty($_POST[$prefix . '_license_registration'][$prefix . '-purchase-code'])){
			$error_code = $this->cmc_map_error_to_code('missing_key');
			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&error=' . urlencode( $error_code ) ) );
			exit;
		}
		if(empty($_POST[$prefix . '_license_registration'][$prefix . '-client-emailid'])){
			$error_code = $this->cmc_map_error_to_code('missing_email');
			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&error=' . urlencode( $error_code ) ) );
			exit;
		}
		$license_key   = ! empty( $_POST[$prefix . '_license_registration'][$prefix . '-purchase-code'] )   ? sanitize_text_field( wp_unslash( $_POST[$prefix . '_license_registration'][$prefix . '-purchase-code'] ) )   : '';
		$license_email = ! empty( $_POST[$prefix . '_license_registration'][$prefix . '-client-emailid'] ) ? sanitize_email( wp_unslash( $_POST[$prefix . '_license_registration'][$prefix . '-client-emailid'] ) )      : '';

        if(empty($license_email)){
			$error_code = $this->cmc_map_error_to_code('wrong_email_format');
			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&error=' . urlencode( $error_code ) ) );
			exit;
		}
		$error    = '';
		$response = null;

		if ( $base::CheckWPPlugin( $license_key, $license_email, $error, $response, $file) ) {
			// persist in SAME array structure
			$this->update_license_opts( array(
				$prefix . '-purchase-code'  => $license_key,
				$prefix . '-client-emailid' => $license_email,
			),
			$section_id
			);
			delete_site_transient( 'update_plugins' );
			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&activated=true' ) );
			exit;
		}
		$error_code = $this->cmc_map_error_to_code($error);
		wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&error=' . urlencode( $error_code ) ) );
		exit;
	}

    public function action_deactivate_license() {
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->crypto_context_resolver($page);
		$prefix    = $base_context['prefix'];
    	$base    = $base_context['base'];
    	$file    = $base_context['file'];
    	$section_id    = $base_context['section_id'];

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Unauthorized' );
		}
		check_admin_referer( $prefix . '-el-license' );

		$message = '';
		if ( $base::RemoveLicenseKey( $file, $message ) ) {
			$this->clear_license_key_only($prefix,$section_id);
			delete_transient( $prefix . '_api_data_verification' );
			delete_site_transient( 'update_plugins' );

			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&deactivated=true' ) );
			exit;
		}
		if(empty($message)){
			wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&deactivated=false' ) );
			exit;
		}else{
		wp_safe_redirect( admin_url( 'admin.php?page=cool-crypto-registration&error=' . urlencode( $message ) ) );
		exit;
	}
	}

	public function detect_page_from_equest() {
		if (!empty($_POST['action'])) {
			$a = sanitize_key($_POST['action']);
			if (strpos($a, 'cmc_') === 0)  return 'cmc_license_registration';
			if (strpos($a, 'celp_') === 0) return 'celp_license_registration';
			if (strpos($a, 'ccpw_') === 0) return 'ccpw_license_registration';
		}

		$current = current_action(); // e.g. wp_ajax_cmc_refresh_license_ajax
		if (strpos($current, 'cmc_') !== false)  return 'cmc_license_registration';
		if (strpos($current, 'celp_') !== false) return 'celp_license_registration';
		if (strpos($current, 'ccpw_') !== false) return 'ccpw_license_registration';
		return 'celp_license_registration'; 
	}

	function render_license_fields_from_settings( $page,$prefix ) {
		$hcpl_prefix = $this->hcpl_prefix;
        global $wp_settings_fields;

        if ( empty( $wp_settings_fields[ $page ] ) ) {
            return;
        }
        // Flatten fields across all sections on this $page, preserving order.
        foreach ( $wp_settings_fields[ $page ] as $section_id => $fields ) {
            foreach ( $fields as $field_id => $field ) {
				$args       = $field['args'] ?? [];

				if ( $args['id'] !== $prefix.'-purchase-code' && $args['id'] !== $prefix.'-client-emailid' ) {
					continue;
				}
				
                $label_for  = $args['label_for'] ?? $field_id;

                echo '<div class='.$hcpl_prefix.'-license-field>';

                if ( ! empty( $field['title'] ) ) {
                    echo '<label for="' . esc_attr( $label_for ) . '">'
                            . wp_kses_post( $field['title'] ) .
                        '</label>';
                }

                // Render the control via the original callback
                ob_start();
                if ( is_callable( $field['callback'] ) ) {
                    call_user_func( $field['callback'], $args );
                }
                $hcpl = ob_get_clean();

                // If a legacy callback accidentally prints table markup, strip it.
                if ( strpos( $hcpl, '<tr' ) !== false || strpos( $hcpl, '<td' ) !== false ) {
                    $hcpl = preg_replace( '#</?(tr|th|td)[^>]*>#i', '', $hcpl );
                }

				$allowed = [
					'input' => [
						'type'        => true,
						'name'        => true,
						'id'          => true,
						'class'       => true,
						'value'       => true,
						'placeholder' => true,
						'size'        => true,
						'required'    => true,
						'checked'     => true,
						'pattern'     => true,
						'min'         => true,
						'max'         => true,
						'step'        => true,
						'autocomplete'=> true,
					],
				];
				$hcpl = wp_kses( $hcpl, $allowed );
				// Remove submit/button inputs (keep text/email/etc.)
				$hcpl = preg_replace(
					'#<input[^>]*\btype=["\']?(submit|button|reset)["\']?[^>]*>#i',
					'',
					$hcpl
				);

                echo $hcpl;

                // Optional small help text from args
                if ( ! empty( $args['description'] ) ) {
                    echo '<div><small>' . esc_html( $args['description'] ) . '</small></div>';
                }

                echo '</div>';
            }
        }
    }
}
