<?php

require_once 'class-cool-form-kit-for-elementor-forms-base.php';
if(!class_exists("CoolFormKitForElementorForms")) {
class CoolFormKitForElementorForms {
	public $plugin_file = __FILE__;
	public $response_obj;
	public $license_message;
	public $show_message       = false;
	public $slug               = 'cfkef';
	public $plugin_version     = '';
	public $text_domain        = '';
	public static $form_status = false;
	private const CFKEF_OPTION_LICENSE_KEY = 'CoolFormKitForElementorForms_lic_Key';
    private const CFKEF_OPTION_LICENSE_EMAIL = 'CoolFormKitForElementorForms_lic_email';
	function __construct() {
		$this->license_message = get_transient( 'cfkef_license_error' );
		if ( ! empty( $this->license_message ) ) {
			$this->show_message = true;
		}

		add_action( 'admin_print_styles', array( $this, 'set_admin_style' ) );
		add_action( 'admin_enqueue_scripts', [ $this, 'set_admin_scripts' ] );
		add_action('cfkef_admin_notices', array($this, 'cfkef_display_license_error_messages'));

		add_action('admin_footer', function () {
            if (isset($_GET['page']) && $_GET['page'] === 'cool-formkit' &&
                (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 }
        });

		$this->set_plugin_data();
		$main_lic_key = 'CoolFormKitForElementorForms_lic_Key';
		$lic_key_name = Cool_Form_Kit_For_Elementor_Forms_Base::get_lic_key_param( $main_lic_key );
		$license_key  = get_option( $lic_key_name, '' );
		if ( empty( $license_key ) ) {
			$license_key = get_option( $main_lic_key, '' );
			if ( ! empty( $license_key ) ) {
				update_option( $lic_key_name, $license_key ) || add_option( $lic_key_name, $license_key );
				update_option( $main_lic_key, '' );
			}
		}
		$lice_email = get_option( 'CoolFormKitForElementorForms_lic_email', '' );
        Cool_Form_Kit_For_Elementor_Forms_Base::add_on_delete(function(){
           update_option($this->get_original_license_key(),'');
           update_option('CoolFormKitForElementorForms_lic_Key','');
        });
		if ( Cool_Form_Kit_For_Elementor_Forms_Base::check_wp_plugin( $license_key, $lice_email, $this->license_message, $this->response_obj, CFKEF_PLUGIN_FILE ) ) {
			add_action( 'admin_post_CoolFormKitForElementorForms_el_deactivate_license', array( $this, 'action_deactivate_license' ) );
			self::$form_status = true;
			add_filter(
				'plugin_row_meta',
				function( $links, $plugin_file ) {
					if ( CFKEF_PLUGIN_BASENAME == $plugin_file ) {
						$links[] = " <a class='edit coption' href='" . esc_url( admin_url( 'admin-post.php' ) . '?action=cfkef_fupc' ) . "'>Update Check</a>";
					}
					return $links;
				},
				10,
				2
			);
		} else {
			self::$form_status = false;

			add_action( 'cfkef_admin_notices', array( $this, 'cfkef_admin_notice_license_key' ) );

			if ( ! empty( $license_key ) && ! empty( $this->license_message ) ) {
				$this->show_message = true;
			}

			update_option( $lic_key_name, '' ) || add_option( $lic_key_name, '' );
			add_action( 'admin_post_CoolFormKitForElementorForms_el_activate_license', array( $this, 'action_activate_license' ) );
		}
		add_action('wp_ajax_cfkef_refresh_license_ajax', [$this, 'cfkef_handle_refresh_license_ajax']);

	}

	public function get_original_license_key(){
        return Cool_Form_Kit_For_Elementor_Forms_Base::get_lic_key_param(self::CFKEF_OPTION_LICENSE_KEY);   
    }

    public function cfkef_handle_refresh_license_ajax() {
        // Check nonce for security
        if (!wp_verify_nonce($_POST['nonce'], 'cfkef_refresh_license_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
            return;
        }

        $this->cfkef_check_user_capabilities();
            
        // Get existing license key and email
        $license_key    = get_option($this->get_original_license_key(), '');
        $license_email  = get_option(self::CFKEF_OPTION_LICENSE_EMAIL, '');

        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->cfkef_activate_license($license_key, $license_email, $error, $responseObj)) {        
            // 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' => CoolFormKitForElementorForms::getVersionAvailableMessage()
            ));
        } else {
            // Map error message to error code
            $error_code = $this->cfkef_map_error_to_code($error);
            $error_message = $this->cfkef_get_error_message($error_code);
            wp_send_json_error(array('message' => $error_message));
        }
    }

	public static function getVersionAvailableMessage(){
        // Get license info and update info for the plugin
        $update_info = Cool_Form_Kit_For_Elementor_Forms_Base::getInstance()->el_plugin_update_info();

        // 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(CFKEF_PLUGIN_FILE);

        if ( ! empty($latest_version) && version_compare(CFKEF_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.', 'cool-formkit'),
                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', 'cool-formkit'), $latest_version)),
                    esc_html(sprintf(__('%s (View details)', 'cool-formkit'), $latest_version))
                )
            );
        }
        
        return $version_available_message;
    }

	public function set_plugin_data() {
		if ( ! function_exists( 'get_plugin_data' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		if ( function_exists( 'get_plugin_data' ) ) {
			$data = get_plugin_data( $this->plugin_file, false, false );
			if ( isset( $data['Version'] ) ) {
				$this->plugin_version = $data['Version'];
			}
			if ( isset( $data['TextDomain'] ) ) {
				$this->text_domain = $data['TextDomain'];
			}
		}
	}
	private static function &get_server_array() {
		return $_SERVER;
	}
	private static function get_raw_domain() {
		if ( function_exists( 'site_url' ) ) {
			return site_url();
		}
		if ( defined( 'WPINC' ) && function_exists( 'get_bloginfo' ) ) {
			return get_bloginfo( 'url' );
		} else {
			$server = self::get_server_array();
			if ( ! empty( $server['HTTP_HOST'] ) && ! empty( $server['SCRIPT_NAME'] ) ) {
				$base_url  = ( ( isset( $server['HTTPS'] ) && $server['HTTPS'] == 'on' ) ? 'https' : 'http' );
				$base_url .= '://' . $server['HTTP_HOST'];
				$base_url .= str_replace( basename( $server['SCRIPT_NAME'] ), '', $server['SCRIPT_NAME'] );

				return $base_url;
			}
		}
		return '';
	}
	private static function get_raw_wp() {
		$domain = self::get_raw_domain();
		return preg_replace( '(^https?://)', '', $domain );
	}
	public static function get_lic_key_param( $key ) {
		$raw_url = self::get_raw_wp();
		return $key . '_s' . hash( 'crc32b', $raw_url . 'vtpbdapps' );
	}
	
    public function set_admin_scripts(){
        if(isset($_GET['page']) && sanitize_text_field( $_GET['page'] ) === 'cool-formkit'){
            wp_enqueue_script(
                'cfkef-module-dashboard-setting',
                CFKEF_PLUGIN_URL . 'admin/license/cfkef-module-dashboard-setting.js',
                array('jquery'),
                CFKEF_PLUGIN_VERSION,
                true
            );
                    
            // Localize script with AJAX nonce
            wp_localize_script('cfkef-module-dashboard-setting', 'cfkef_ajax', array(
                'nonce' => wp_create_nonce('cfkef_refresh_license_nonce')
            ));
        }
    }


	public function set_admin_style() {
		wp_register_style( 'CoolFormKitForElementorFormsLic', plugins_url( '_lic_style.css', $this->plugin_file ), 10, time() );
		if ( isset( $_GET['page'] ) && strpos( sanitize_text_field($_GET['page']), 'cool-formkit' ) !== false ) {
			wp_enqueue_style( 'CoolFormKitForElementorFormsLic' );			
		}
	}

	public function cfkef_admin_notice_license_key() {

		if ( isset( $_GET['page'] ) && (strpos( sanitize_text_field($_GET['page']), 'cool-formkit' ) !== false || strpos( sanitize_text_field($_GET['page']), 'cfkef-entries' ) !== false) ) {
			?>
			<div class="notice notice-warning is-dismissible coolformkit-license-notice">
				<p><?php _e( 'Please <a href="admin.php?page=cool-formkit&tab=license">add your license key</a>  to activate Cool FormKit plugin to get automatic updates and support' , 'cool-formkit'); ?></p>
			</div>
			<?php
		}
	}

	function action_activate_license() {
		check_admin_referer( 'el-license' );
		$license_key   = ! empty( $_POST['el_license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['el_license_key'] ) ) : '';
		$license_email = ! empty( $_POST['el_license_email'] ) ? sanitize_email( wp_unslash( $_POST['el_license_email'] ) ) : '';
		$main_lic_key  = 'CoolFormKitForElementorForms_lic_Key';
		$lic_key_name  = Cool_Form_Kit_For_Elementor_Forms_Base::get_lic_key_param( $main_lic_key );

		if($this->cfkef_activate_license($license_key, $license_email, $error, $responseObj)){
			update_option( $lic_key_name, $license_key ) || add_option( $lic_key_name, $license_key );
			update_option( 'CoolFormKitForElementorForms_lic_email', $license_email ) || add_option( 'CoolFormKitForElementorForms_lic_email', $license_email );
			update_option( '_site_transient_update_plugins', '' );

            $this->cfkef_redirect_with_success();
        }


		$error_code = $this->cfkef_map_error_to_code($error);
        $this->cfkef_redirect_with_error($error_code);
	}
	function action_deactivate_license() {

		check_admin_referer( 'el-license' );
		$message      = '';
		$main_lic_key = 'CoolFormKitForElementorForms_lic_Key';
		$lic_key_name = Cool_Form_Kit_For_Elementor_Forms_Base::get_lic_key_param( $main_lic_key );
		if ( Cool_Form_Kit_For_Elementor_Forms_Base::remove_license_key( __FILE__, $message ) ) {
			update_option( $lic_key_name, '' ) || add_option( $lic_key_name, '' );
			update_option( '_site_transient_update_plugins', '' );
		}
		wp_safe_redirect( admin_url( 'admin.php?page=' . 'cool-formkit&tab=license&deactivated=true' ) );
	}

	private function cfkef_redirect_with_success() {
        wp_safe_redirect(admin_url('admin.php?page=cool-formkit&tab=license&activated=true'));
        exit;
    }

    private function cfkef_redirect_with_error($error) {
        wp_safe_redirect(admin_url('admin.php?page=cool-formkit&tab=license&error=' . urlencode($error)));
        exit;
    }

    
    // Add new method to display error messages
    public function cfkef_display_license_error_messages() {
        if (isset($_GET['page']) && $_GET['page'] === 'cool-formkit') {
              
            // Display error message if exists
            if (isset($_GET['error'])) {
                $error_message = $this->cfkef_get_error_message($_GET['error']);
                ?>
                <div class="notice notice-error is-dismissible">
                    <p><?php echo esc_html($error_message); ?></p>
                </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!', 'cool-formkit'); ?></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!', 'cool-formkit'); ?></p>
                </div>
                <?php
            }

            // Display license message if exists
            if ($this->show_message && !empty($this->license_message)) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p><?php echo esc_html($this->license_message); ?></p>
                </div>
                <?php
            }
        }
    }

    private function cfkef_activate_license($licenseKey, $licenseEmail, &$error, &$responseObj) {    
        if (Cool_Form_Kit_For_Elementor_Forms_Base::check_wp_plugin($licenseKey, $licenseEmail, $error, $responseObj, CFKEF_PLUGIN_FILE)) {
            update_option($this->get_original_license_key(), $licenseKey);
            update_option(self::CFKEF_OPTION_LICENSE_EMAIL, $licenseEmail);
            delete_site_transient('update_plugins');
            return true;
        }
            return false;
    }

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

    public function cfkef_is_license_expired($license_info) {

        return $license_info->is_valid === 'license_expired';
    }

    public function cfkef_is_support_expired($license_info) {

        return $license_info->support_end === 'no support' || 
            ($license_info->is_valid === 'support_expired' || 
            (strtolower($license_info->support_end) !== 'unlimited' && 
            strtotime($license_info->support_end) < time()));
    }

    public function cfkef_needs_refresh($license_info) {
        return $this->cfkef_is_license_expired($license_info) || $this->cfkef_is_support_expired($license_info);
    }

    private function cfkef_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';
            }
            return 'default';
    }

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

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

    public function cfkef_pro_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 cfkef_render_expiry_message($license_info, $type = 'license'){
        $text_domain = 'cool-formkit';
        // Generate version available message using common helper
        $version_available_message = CoolFormKitForElementorForms::getVersionAvailableMessage();
        
        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;
    }

	function activated() {
		$license_info = $this->response_obj;

        if (!$license_info) {
            $license_info = Cool_Form_Kit_For_Elementor_Forms_Base::GetRegisterInfo();
        }

        $key_hash    = Cool_Form_Kit_For_Elementor_Forms_Base::get_lic_key_param( get_option( 'CoolFormKitForElementorForms_lic_Key', '' ) );
        $license_key = get_option( 'CoolFormKitForElementorForms_lic_Key' . $key_hash, '' );

		ob_start();
		?>
		<div class="cfkef-license-box">
			<div class="wrapper-header">
				<h3>🔐 <?php esc_html_e( 'Your License Info', 'cool-formkit' ); ?> </h3>
			</div>
			<div class="wrapper-body">
				<?php if ( $this->cfkef_needs_refresh( $license_info ) ) : ?>
                    <div class="cfkef-refresh-row">
                        <button type="button"
                                class="cfkef-refresh-btn"
                                id="cfkef-refresh-license-btn"
                                data-license-key="<?php echo esc_attr( $license_key ); ?>"
                                data-license-email="<?php echo esc_attr( get_option( 'CoolFormKitForElementorForms_lic_email', '' ) ); ?>">
                                <?php _e( '🔄 Check license status', 'cool-formkit' ); ?>
                        </button>
                    </div>
                <?php endif; ?>

				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<input type="hidden" name="action" value="CoolFormKitForElementorForms_el_deactivate_license"/>
					<ul>
						<li>
                            <strong><?php esc_html_e( 'Status: ', 'cool-formkit' ); ?></strong>
                            <span class="validity">
                                <?php if ( $license_info->is_valid ) : ?>
                                    <?php if ( $this->cfkef_is_license_expired( $license_info ) ) : ?>
                                        <strong>❌ <?php esc_html_e( 'License Expired', 'cool-formkit' ); ?></strong>
                                    <?php elseif ( $this->cfkef_is_support_expired( $license_info ) ) : ?>
                                        <strong>❌ <?php esc_html_e( 'Support Expired', 'cool-formkit' ); ?></strong>
                                    <?php else : ?>
                                        <strong>✅ <?php esc_html_e( 'Valid', 'cool-formkit' ); ?></strong>
                                    <?php endif; ?>
                                <?php else : ?>
                                    <strong>❌ <?php esc_html_e( 'Invalid', 'cool-formkit' ); ?></strong>
                                <?php endif; ?>
                            </span>
                        </li>
                        <li>
                            <strong><?php esc_html_e( 'License Type: ', 'cool-formkit' ); ?></strong>
                            <strong class="cfkef-license-type"><?php echo esc_html( $license_info->license_title ); ?></strong>
                        </li>
						<li>
                            <strong><?php esc_html_e( 'Plugin Updates & Support Validity: ', 'cool-formkit' ); ?></strong>
                            <span class="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', 'cool-formkit' );

                                } 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->cfkef_pro_formatLicenseDate( $license_info->expire_date ) );
                                    } elseif ( $support_end_expired ) {
                                        echo esc_html( $this->cfkef_pro_formatLicenseDate( $license_info->support_end ) );
                                    } else {
                                        echo esc_html( $this->cfkef_pro_formatLicenseDate( $license_info->expire_date ) );
                                    }
                                }
                                ?>
                            </span>
                        </li>
                        <li>
                            <strong><?php esc_html_e( 'Your License Key: ', 'cool-formkit' ); ?></strong>
                            <strong class="license-key"><?php echo esc_attr( substr( $license_info->license_key, 0, 9 ) . 'XXXXXXXX-XXXXXXXX' . substr( $license_info->license_key, -9 ) ); ?></strong>
                        </li>
					</ul>
					<?php wp_nonce_field( 'el-license' ); ?>
					<div class="cfkef-submit-button">
						<p><?php esc_html_e( 'Want to deactivate the license for any reason?', 'cool-formkit' ); ?></p>
						<?php submit_button( 'Deactivate License' ); ?>
					</div>
				</form>

				<?php if ($this->cfkef_is_license_expired($license_info)): ?>

                <div class="notice notice-error" style="margin-top: 10px; color: #d63638;">
                        <?php $this->cfkef_render_expiry_message($license_info, 'license'); ?>
                </div>

                <?php elseif ($this->cfkef_is_support_expired($license_info)): ?>

                <div class="notice notice-error" style="margin-top: 10px; color: #d63638;">
                        <?php $this->cfkef_render_expiry_message($license_info, 'support'); ?>
                </div>

                <?php endif; ?>

				<div class="cfkef-license-support">
					<p><?php esc_html_e( 'Want to know more about the license key?', 'cool-formkit' ); ?></p>
					<div class="cfkef-support-buttons">
						<a href="https://my.coolplugins.net/account/" target="_blank" class="button button-secondary"><?php esc_html_e( 'Check Account', 'cool-formkit' ); ?></a>
						<a href="https://coolformkit.com/support/?utm_source=cfkef_plugin&utm_medium=inside&utm_campaign=support&utm_content=license_dashboard" target="_blank" class="button button-secondary"><?php esc_html_e( 'Contact Support', 'cool-formkit' ); ?></a>
					</div>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	function license_form() {
		ob_start();
		?>
		<div class="cfkef-license-box">
			<div class="wrapper-header">
				<h3>🔐 <?php esc_html_e( 'Activate License', 'cool-formkit' ); ?></h3>
			</div>

			<div class="wrapper-body">
				<form class="cfkef-license-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<input type="hidden" name="action" value="CoolFormKitForElementorForms_el_activate_license"/>
					<?php
					if ( ! empty( $this->show_message ) && ! empty( get_transient( 'cfkef_license_error' ) ) ) {
						$this->license_message = get_transient( 'cfkef_license_error' );
						?>
							<div class="notice notice-error is-dismissible">
								<p><?php echo esc_html( $this->license_message ); ?></p>
							</div>
						<?php
							delete_transient( 'cfkef_license_error' );
					}
					?>
					<div class="cfkef-license-field">
						<label for="cfkef-el_license_key"><?php esc_html_e( 'License code', 'cool-formkit' ); ?></label>
						<input type="text" name="el_license_key" id="cfkef-el_license_key" size="50" placeholder="xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx" required="required">
					</div>
					<div class="cfkef-license-field">
						<label for="cfkef-el_license_email"><?php esc_html_e( 'Email Address', 'cool-formkit' ); ?></label>
						<?php
							$purchase_email = get_option( 'CoolFormKitForElementorForms_lic_email', get_bloginfo( 'admin_email' ) );
						?>
						<input type="email" name="el_license_email" id="cfkef-el_license_email" size="50" value="<?php echo esc_attr( $purchase_email ); ?>" placeholder="" required="required">
						<small><?php esc_html_e( "Plugin updates news will be sent to this email. Don't worry, we hate spam.", 'cool-formkit' ); ?></small>
					</div>
					<?php wp_nonce_field( 'el-license' ); ?>
					<?php submit_button( 'Activate License' ); ?>
					<p><?php esc_html_e( 'Activate to receive automatic plugin updates and support.', 'cool-formkit' ); ?></p>
				</form>
				<div class="cfkef-license-support">
					<p><?php esc_html_e( 'Want to know more about the license key?', 'cool-formkit' ); ?></p>
					<div class="cfkef-support-buttons">
						<a href="https://my.coolplugins.net/account/" target="_blank" class="button button-secondary"><?php esc_html_e( 'Check Account', 'cool-formkit' ); ?></a>
						<a href="https://coolformkit.com/support/?utm_source=cfkef_plugin&utm_medium=inside&utm_campaign=support&utm_content=license_dashboard" target="_blank" class="button button-secondary"><?php esc_html_e( 'Contact Support', 'cool-formkit' ); ?></a>
					</div>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
}

new CoolFormKitForElementorForms();
