<?php 
namespace CoolTimelineProLicenser;

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

use CoolTimelineProREG\CoolTimelineProBase;

class License_Helper {

	// dynamic value variables for the framework
	public $html_prefix = 'tml';	
	/**
     * 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 CTP_PLUGIN_DIR . 'admin/registration/CoolTimelineProBase.php';
        add_action( 'admin_print_styles', [ $this, 'set_admin_style' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'set_admin_scripts' ] );
        add_action('ctl_display_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']) === 'timeline-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 (['ctp','twae','cptb','tmdivi','ctlb'] 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);
		}
		add_action( 'admin_enqueue_scripts', function() {
			if ( isset( $_GET['page'] ) && $_GET['page'] === 'timeline-addons-license' ) {
				wp_dequeue_script( 'twae-settings-script' );
				wp_deregister_script( 'twae-settings-script' );
				wp_dequeue_script( 'cptb-settings-script' );
				wp_deregister_script( 'cptb-settings-script' );

				wp_dequeue_style( 'twae-settings-style' );
				wp_deregister_style( 'twae-settings-style' );
				wp_dequeue_style( 'cptb-settings-style' );
				wp_deregister_style( 'cptb-settings-style' );
			}
		}, 999 );
    }

	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']);

			if ( class_exists( $base ) ) {
				$instance = method_exists( $base, 'getInstance' ) ? $base::getInstance($context_base['file']) : null;
				$update_info = ( $instance && method_exists( $instance, '__plugin_updateInfo' ) )
					? $instance->__plugin_updateInfo()
					: '';
				$license_info = method_exists( $base, 'GetRegisterInfo' ) ? $base::GetRegisterInfo() : null;
			} else {
				continue;
			}

			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=timeline-addons-license');
		$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'];

		if(! class_exists( $base )){
			return;
		}
    	// 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=timeline-addons-license">enter your license key</a> to enable automatic updates and premium support for '.$plugin_name.'', $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 <a href="https://codecanyon.net/downloads/" target="_blank">Renew now</a> 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'] ) === 'timeline-addons-license'){

			if(defined('CTP_PLUGIN_URL') && defined('CTP_PLUGIN_DIR')){
				if(file_exists(CTP_PLUGIN_DIR. 'admin/license-helper/assets/css/license.css')){
					wp_register_style( "cool-timeline-widget-license-css", CTP_PLUGIN_URL. 'admin/license-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "cool-timeline-widget-license-css" );
				}
			}
			if(defined('TWAE_PRO_URL') && defined('TWAE_PRO_PATH')){
				if(file_exists(TWAE_PRO_PATH. 'admin/license-helper/assets/css/license.css')){
					wp_register_style( "timeline-widget-license-css", TWAE_PRO_URL. 'admin/license-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "timeline-widget-license-css" );	
				}
			}
			if(defined('cp_timeline_builder_URL') && defined('cp_timeline_builder_DIR_PATH')){
				if(file_exists(cp_timeline_builder_DIR_PATH. 'admin/license-helper/assets/css/license.css')){
					wp_register_style( "timeline-widget-license-css", cp_timeline_builder_URL. 'admin/license-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "timeline-widget-license-css" );	
				}
			}
			if(defined('TM_DIVI_PRO_URL') && defined('TM_DIVI_PRO_DIR')){
				if(file_exists(TM_DIVI_PRO_DIR. 'admin/license/tm-divi-lic-style.css')){
					wp_register_style( "timeline-widget-license-css", TM_DIVI_PRO_URL. 'admin/license/tm-divi-lic-style.css',10,time());
					wp_enqueue_style( "timeline-widget-license-css" );	
				}
			}
				if(defined('CTLB_Pro_File') && defined('CTLB_Pro_File')){
				if(file_exists(CTLB_Pro_Dir. 'admin/license-helper/assets/css/license.css')){
					wp_register_style( "timeline-widget-license-css", CTLB_Pro_Url. 'admin/license-helper/assets/css/license.css',10,time());
					wp_enqueue_style( "timeline-widget-license-css" );	
				}
			}

		}
    }

    public function set_admin_scripts(){
        if(isset($_GET['page']) && sanitize_text_field( $_GET['page'] ) === 'timeline-addons-license'){

			if(defined('CTP_PLUGIN_URL') && defined('CTP_PLUGIN_DIR')){
				if(file_exists(CTP_PLUGIN_DIR. 'admin/license-helper/assets/js/timeline-widget-license-setting.js')){	
					wp_enqueue_script(
						'ctl-timeline-widget-license-setting',
						CTP_PLUGIN_URL . 'admin/license-helper/assets/js/timeline-widget-license-setting.js',
						array('jquery'),
						CTLPV,
						true
					);
					// Localize script with AJAX nonce
					wp_localize_script('ctl-timeline-widget-license-setting', 'ctp_ajax', array(
						'nonce' => wp_create_nonce('ctp_refresh_license_nonce')
					));
				}
			}
			if(defined('TWAE_PRO_URL') && defined('TWAE_PRO_PATH')){
				if(file_exists(TWAE_PRO_PATH. 'admin/license-helper/assets/js/timeline-widget-license-setting.js')){					
					wp_enqueue_script(
						'twae-widget-license-setting',
						TWAE_PRO_URL . 'admin/license-helper/assets/js/timeline-widget-license-setting.js',
						array('jquery'),
						TWAE_PRO_VERSION,
						true
					);
							
					// // Localize script with AJAX nonce
					wp_localize_script('twae-widget-license-setting', 'twae_ajax', array(
						'nonce' => wp_create_nonce('twae_refresh_license_nonce')
					));	
				}
			}
			if(defined('cp_timeline_builder_URL') && defined('cp_timeline_builder_DIR_PATH')){
				if(file_exists(cp_timeline_builder_DIR_PATH. 'admin/license-helper/assets/js/timeline-widget-license-setting.js')){
					wp_enqueue_script(
						'cptb-widget-license-setting',
						cp_timeline_builder_URL . 'admin/license-helper/assets/js/timeline-widget-license-setting.js',
						array('jquery'),
						cp_timeline_builder_V,
						true
					);
					// // Localize script with AJAX nonce
					wp_localize_script('cptb-widget-license-setting', 'cptb_ajax', array(
						'nonce' => wp_create_nonce('cptb_refresh_license_nonce')
					));	
				}
			}
		if(defined('TM_DIVI_PRO_URL') && defined('TM_DIVI_PRO_DIR')){
				
				if(file_exists(TM_DIVI_PRO_DIR. 'admin/license/timeline-module-dashboard-setting.js')){	
						
					wp_enqueue_script(
						'tmdivi-license-setting',
						TM_DIVI_PRO_URL . 'admin/license/timeline-module-dashboard-setting.js',
						array('jquery'),
						TM_DIVI_PRO_V,
						true
					);
					// Localize script with AJAX nonce
					wp_localize_script('tmdivi-license-setting', 'tmdivi_ajax', array(
						'nonce' => wp_create_nonce('tmdivi_refresh_license_nonce')
					));
				}
			}
			if(defined('CTLB_Pro_Url') && defined('CTLB_Pro_Dir')){
				
				if(file_exists(CTLB_Pro_Dir. 'admin/license-helper/assets/js/timeline-widget-license-setting.js')){	
						
					wp_enqueue_script(
						'ctlb-license-setting',
						CTLB_Pro_Url . 'admin/license-helper/assets/js/timeline-widget-license-setting.js',
						array('jquery'),
						CTLBV,
						true
					);
					// Localize script with AJAX nonce
					wp_localize_script('ctlb-license-setting', 'ctlb_ajax', array(
						'nonce' => wp_create_nonce('ctlb_refresh_license_nonce')
					));
				}
			}
        }
    }

	public function get_all_contexts() {
		$list = [];
		$ctp = $this->timeline_context_resolver('ctp_license_registration');
		if (!empty($ctp['file'])) $list[] = $ctp;

		$twae = $this->timeline_context_resolver('twae_license_registration');
		if (!empty($twae['file'])) $list[] = $twae;

		$cptb = $this->timeline_context_resolver('cptb_license_registration');
		if (!empty($cptb['file'])) $list[] = $cptb;

		$tmdivi = $this->timeline_context_resolver('tmdivi_license_registration');
		if (!empty($tmdivi['file'])) $list[] = $tmdivi;

		$ctlb = $this->timeline_context_resolver('ctlb_license_registration');
		if (!empty($ctlb['file'])) $list[] = $ctlb;
		
		
		return $list;
	}

    public function display_license_error_messages() {
		$textdomain = 'cool-timeline';
        if (isset($_GET['page']) && $_GET['page'] === 'timeline-addons-license') {
              
            // Display error message if exists
            	    if (isset($_GET['error'])) {
                $error_message = $this->ctp_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.'|| 
					          $error_message === 'No valid request method works for license checking.'
					){ 
						echo '<p>There is an issue with your account. Please contact our plugin support team by <a href="https://cooltimeline.com/support/?utm_source=ctp_plugin&utm_medium=inside&utm_campaign=support&utm_content=license_dashboard">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 should_show_refresh_button( $context_base ) {
        $key = $context_base['key'];
        switch ( $key ) {
            case 'ctp':
                return defined('CTLPV') && version_compare( CTLPV, '4.9.2', '>' );
            case 'twae':
                return defined('TWAE_PRO_VERSION') && version_compare( TWAE_PRO_VERSION, '2.3.0', '>' );
            case 'cptb':
                return defined('cp_timeline_builder_V') && version_compare( cp_timeline_builder_V, '1.1.2', '>' );
			case 'tmdivi':
			    return defined('TM_DIVI_PRO_V') && version_compare( TM_DIVI_PRO_V, '1.0.7', '>' );
			case 'ctlb':
				return defined('CTLBV') && version_compare( CTLBV, '1.1.1', '>' );
            default:
                return false;
        }
    }

    public function handle_refresh_license_ajax(){
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->timeline_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
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, $prefix . '_refresh_license_nonce' ) ) {
			return wp_send_json_error( array( 'message' => 'Security check failed.' ) );
        }
		
        $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 = '';
        $responseObj = null;

        // Use the same activation logic to refresh the license
        if ($this->plugin_activate_license($base,$license_key, $license_email, $error, $responseObj,$file,$section_id,$base_context)) {        
            // Get updated license information
            $license_info = array(
                'is_valid' => $responseObj->is_valid ? $responseObj->is_valid:false,
                'license_title' => $responseObj->license_title ? $responseObj->license_title : '',
                'expire_date' => $responseObj->expire_date ? $responseObj->expire_date : '',
                'market' => $responseObj->market ? $responseObj->market : '',
                'support_end' => $responseObj->support_end ? $responseObj->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->ctp_map_error_to_code($error);
            $error_message = $this->ctp_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 ctp_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, 'response error, contact with the author or update the plugin or theme') !== false) {
                return 'response_error';
            }
			 elseif (strpos($error, 'no valid request method works for license checking') !== false) {
                return 'blockedA_error';
            }
            return 'default';
    }

    public function ctp_get_error_message($error_code) {        
		$textdomain = 'cool-timeline';
        $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),
			'blockedA_error' => __('No valid request method works for license checking.', $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, &$responseObj,$file,$section_id,$base_context) {  
        if ($base::CheckWPPlugin($licenseKey, $licenseEmail, $error, $responseObj, $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){
		$html_prefix = $this->html_prefix;
		$context_base = $this->timeline_context_resolver($page);
        $review_link = $context_base['review_link'];
		$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($html_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>
						<a href="<?php echo esc_url( $review_link ); ?>" class="review-link" target="_blank"><?php _e('Submit a Review →', $textdomain); ?></a>
					</div>
				</div>
			</div>
        </div>
        <?php
    }
	
	function script() {
        ?>

				<style>
			
				.nav-tab.disabled{
					pointer-events: none;
					opacity: 0.5;
					cursor: not-allowed;
					/* optional: make it keyboard-inert */
					outline: none;
				}

				</style>
        <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();
                   
                   $('.nav-tab').addClass('disabled');
					setTimeout(function() {
						 $('.nav-tab').removeClass('disabled');
					}, 600); 
						$(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 HTML)
	 * ------------------------------------------ */
	function license_form($page,$context_base){		
		$html_prefix = $this->html_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($html_prefix) ?>-license-box">
				<div class="wrapper-header">
					<h3>🔐 <?php esc_html_e( $plugin_name .' Licensing', $textdomain ); ?></h3>
				</div>

				<div class="wrapper-body">	
					<form class="<?php echo esc_attr($html_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($html_prefix) ?>-el-license-active-btn">
							<?php submit_button( 'Activate' ); ?>
						</div>
					</form>

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

	/* ------------------------------------------
	 * Modern UI: Activated panel
	 * ------------------------------------------ */
	private function activated_panel($page,$context_base) {
		$html_prefix = $this->html_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($html_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($html_prefix) ?>-refresh-row">
							<button type="button"
								class="<?php echo esc_attr($prefix) ?>-refresh-btn"
								id="<?php echo esc_attr($html_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($html_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($html_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,$section_id, $license_info);
                    ?>
				</div>
			</div>
		<?php
		return ob_get_clean();
	}

    public function render_support_buttons($prefix,$textdomain,$section_id,$license_info){
		$html_prefix = $this->html_prefix;
		$license_key = $this->get_license_key($prefix,$section_id);
		$lt_visibility= isset($license_info->market) && $license_info->market === 'E'  && ($this->is_license_expired($license_info) || $this->is_support_expired($license_info)) ? 'block' : 'none';
		$check_button_visibility= $lt_visibility === 'block' ? 'none' : 'block';
		$check_account_url = isset($license_info->market) && $license_info->market === 'E' ? 'https://codecanyon.net/downloads/' : 'https://my.coolplugins.net/account/';
			if($prefix === 'ctp'){
			$lifetime_license_url = 'https://cooltimeline.com/plugin/cool-timeline-pro/#pricing';
		}
	   ?>
        <div class="<?php echo esc_attr($html_prefix) ?>-license-support" data-support-prefix="<?php echo esc_attr($html_prefix); ?>">
			<?php if ( isset($license_info->market) && $license_info->market === 'E'  && ($this->is_license_expired($license_info) || $this->is_support_expired($license_info))) : ?>
		<p><?php esc_html_e( 'Get lifetime access today and eliminate yearly subscription fees.', $textdomain ); ?></p>
		<?php else : ?>
		    <p><?php esc_html_e( 'Want to know more about the license key?', $textdomain ); ?></p>
			<?php endif; ?>
				<div class="<?php echo esc_attr($html_prefix) ?>-support-buttons">
					<?php if ( isset($license_info->market) && $license_info->market === 'E'  && ($this->is_license_expired($license_info) || $this->is_support_expired($license_info))) : ?>
					<a href="<?php echo esc_url($lifetime_license_url); ?>" target="_blank" class="button button-secondary lifetime-license-btn" style="display:<?php echo esc_html($lt_visibility) ?>;">
						<?php esc_html_e( 'Lifetime License', $textdomain ); ?>
					</a>
				<?php endif; ?>
					<a href="<?php echo esc_url($check_account_url); ?>" target="_blank" class="button button-secondary check-account-btn" style="display:<?php echo esc_html($check_button_visibility) ?>;">
						<?php esc_html_e( 'Check Account', $textdomain ); ?>
					</a>
					
					<a href="https://cooltimeline.com/support/?utm_source=ctp_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>
						<?php if ( empty( $license_key ) && $section_id==="ctp_license_registration" ) : ?>
					<p class="<?php echo esc_attr($prefix) ?>-codecanoyn-link"><?php 
			echo esc_html__( 'If you purchased the plugin from CodeCanyon, please log in to your ', $textdomain );
			?><a href="https://codecanyon.net/downloads" target="_blank"><?php esc_html_e( 'CodeCanyon account', $textdomain ); ?></a><?php 
			echo esc_html__( ' to get your license key.', $textdomain );
		?><a href="https://help.market.envato.com/hc/en-us/articles/202822600-Where-Is-My-Purchase-Code" target="_blank"><?php esc_html_e( ' Click here to learn more.', $textdomain ); ?></a></p>
		<?php endif; ?>
		</div>
        <?php 
	}

	
	private function timeline_context_resolver(string $page): array {
		if (strpos($page, 'ctp_') === 0) {
			return [
				'key'        => 'ctp',
				'prefix'     => 'ctp',
				'plugin_name'     => 'Cool Timeline Pro',
				'section_id' => 'ctp_license_registration',
				'base'       => class_exists('\CoolTimelineProREG\CoolTimelineProBase')
								? '\CoolTimelineProREG\CoolTimelineProBase'
								: null,
				'file'       => defined('CTP_FILE') ? CTP_FILE : '',
				'version'    => defined('CTLPV') ? CTLPV : '',
				'textdomain' => 'cool-timeline',
				'review_link'=> 'https://wordpress.org/support/plugin/cool-timeline/reviews/#new-post',
				'ajax'       => ['action_refresh' => 'ctp_refresh_license_ajax', 'nonce' => 'ctp_refresh_license_nonce'],
			];
		}else if(strpos($page, 'twae_') === 0){
			return [
				'key'        => 'twae',
				'prefix'     => 'twae',
				'plugin_name'     => 'Timeline Widget Pro For Elementor',
				'section_id' => 'twae_license_registration',
				'base'       => '\TimelineWidgetAddonForElementorPro\TimelineProAddonForElementorBase',
				'file'       => defined('TWAE_PRO_FILE') ? TWAE_PRO_FILE : '',
				'version'    => defined('TWAE_PRO_VERSION') ? TWAE_PRO_VERSION : '',
				'textdomain' => 'twae',
				'review_link'=> 'https://wordpress.org/support/plugin/timeline-widget-addon-for-elementor/reviews/#new-post',
				'ajax'       => ['action_refresh' => 'twae_refresh_license_ajax', 'nonce' => 'twae_refresh_license_nonce'],
			];
		}else if(strpos($page, 'cptb_') === 0){
			return [
				'key'        => 'cptb',
				'prefix'     => 'cptb',
				'plugin_name'     => 'Timeline Builder Pro',
				'section_id' => 'cptb_license_registration',
				'base'       => '\CoolPluginsTimelineBuilder\TimelineBuilderProBase',
				'file'       => defined('cp_timeline_builder_FILE') ? cp_timeline_builder_FILE : '',
				'version'    => defined('cp_timeline_builder_V') ? cp_timeline_builder_V : '',
				'textdomain' => 'cptb',
				'review_link'=> 'https://trustpilot.com/review/coolplugins.net',
				'ajax'       => ['action_refresh' => 'cptb_refresh_license_ajax', 'nonce' => 'cptb_refresh_license_nonce'],
			];
		}
		
		else if(strpos($page,'tmdivi_') === 0){
			return [
				'key'        => 'tmdivi',
				'prefix'     => 'tmdivi',
				'plugin_name'     => 'Timeline Module for Divi (Pro)',
				'section_id' => 'tmdivi_license_registration',
				'base'       => 'Timeline_Module_Pro_For_Divi_Base',
				'file'       => defined('TM_DIVI_PRO_PLUGIN_FILE') ? TM_DIVI_PRO_PLUGIN_FILE : '',
				'version'    => defined('TM_DIVI_PRO_V') ? TM_DIVI_PRO_V : '',
				'textdomain' => 'timeline-module-for-divi',
				'review_link'=> 'https://wordpress.org/support/plugin/timeline-module-for-divi/reviews/#new-post',
				'ajax'       => ['action_refresh' => 'tmdivi_refresh_license_ajax', 'nonce' => 'tmdivi_refresh_license_nonce'],
			];
		}
		
			else if(strpos($page,'ctlb_') === 0){
			return [
				'key'        => 'ctlb',
				'prefix'     => 'ctlb',
				'plugin_name'     => 'Timeline Block Pro',
				'section_id' => 'ctlb_license_registration',
				'base'       => 'Timeline_Block_Pro_Gutenberg_Addon_Base',
				'file'       => defined('CTLB_Pro_File') ? CTLB_Pro_File : '',
				'version'    => defined('CTLBV') ? CTLBV : '',
				'textdomain' => 'timeline-block-pro',
				'review_link'=> 'https://wordpress.org/support/plugin/timeline-block/reviews/#new-post',
				'ajax'       => ['action_refresh' => 'ctlb_refresh_license_ajax', 'nonce' => 'ctlb_refresh_license_nonce'],
			];
		}
	}
    /* ------------------------------------------
	 * License helpers (storage = serialized array)
	 * option:  ctp_license_registration
	 * keys:    ctp-purchase-code, ctp-client-emailid
	 * ------------------------------------------ */

	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 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://codecanyon.net/downloads/" target="_blank">'.__('Renew now', $text_domain).'</a>'
			: ' <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 wp_kses_post($final_message);
    }
    
    /* ------------------------------------------
	 * Admin-post handlers
	 * ------------------------------------------ */
    public function action_activate_license() {
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->timeline_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->ctp_map_error_to_code('missing_key');
			wp_safe_redirect( admin_url( 'admin.php?page=timeline-addons-license&error=' . urlencode( $error_code ) ) );
			exit;
		}
		if(empty($_POST[$prefix . '_license_registration'][$prefix . '-client-emailid'])){
			$error_code = $this->ctp_map_error_to_code('missing_email');
			wp_safe_redirect( admin_url( 'admin.php?page=timeline-addons-license&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->ctp_map_error_to_code('wrong_email_format');
			wp_safe_redirect( admin_url( 'admin.php?page=timeline-addons-license&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=timeline-addons-license&activated=true' ) );
			exit;
		}
		$error_code = $this->ctp_map_error_to_code($error);
		wp_safe_redirect( admin_url( 'admin.php?page=timeline-addons-license&error=' . urlencode( $error_code ) ) );
		exit;
	}

    public function action_deactivate_license() {
		$page = $this->detect_page_from_equest();
    	$base_context    = $this->timeline_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=timeline-addons-license&deactivated=true' ) );
			exit;
		}
		if($message === 'Response Error, contact with the author or update the plugin or theme'){
        $message = 'response_error';
      }
        wp_safe_redirect( admin_url( 'admin.php?page=timeline-addons-license&error=' . urlencode( $message ) ) );
        exit;
	}

	public function detect_page_from_equest() {
		if (!empty($_POST['action'])) {
			$a = sanitize_key($_POST['action']);
			if (strpos($a, 'ctp_') === 0)  return 'ctp_license_registration';
			if (strpos($a, 'twae_') === 0) return 'twae_license_registration';
			if (strpos($a, 'cptb_') === 0) return 'cptb_license_registration';
			if (strpos($a, 'tmdivi_') === 0) return 'tmdivi_license_registration';
			if (strpos($a, 'ctlb_') === 0) return 'ctlb_license_registration';
		}

		$current = current_action(); // e.g. wp_ajax_ctp_refresh_license_ajax
		if (strpos($current, 'ctp_') !== false)  return 'ctp_license_registration';
		if (strpos($current, 'twae_') !== false) return 'twae_license_registration';
		if (strpos($current, 'cptb_') !== false) return 'cptb_license_registration';
		if (strpos($current, 'tmdivi_') !== false) return 'tmdivi_license_registration';
		if (strpos($current, 'ctlb') !== false) return 'ctlb_license_registration';


		return 'twae_license_registration'; 
	}

	function render_license_fields_from_settings( $page,$prefix ) {
		$html_prefix = $this->html_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='.$html_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 );
                }
                $html = ob_get_clean();

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

				$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,
					],
				];
				$html = wp_kses( $html, $allowed );
				// Remove submit/button inputs (keep text/email/etc.)
				$html = preg_replace(
					'#<input[^>]*\btype=["\']?(submit|button|reset)["\']?[^>]*>#i',
					'',
					$html
				);

                echo $html;

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

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