<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

if ( get_option( 'efa_2710_license_status', false) != 'valid' ){
	add_action( 'admin_notices', 'elementorfa_2710_license_notice' );
}
	function elementorfa_2710_license_notice() {
    ?>
  
    <?php
}

function efa_2710_func_license() {
	$license = get_option( 'efa_2710_license_key' );
	$status  = get_option( 'efa_2710_license_status' );
	?>
	<div class="wrap-license-efa">
	    <style>
	        .wrap-license-efa {
	            width: 100%;
	            max-width: 100%;
	            padding: 20px 0;
	            box-sizing: border-box;
	        }
	        .wrap-license-efa .form-table {
	            border: none;
	            box-shadow: none;
	            background: transparent;
	        }
	        .wrap-license-efa .form-table th,
	        .wrap-license-efa .form-table td {
	            border: none;
	            padding: 15px 0;
	        }
	        .license-description {
	            margin-bottom: 20px;
	            font-size: 14px;
	        }
	        .wrap-license-efa .submit {
	            padding: 0;
	            margin-top: 15px;
	        }
            /* Consistent styling for buttons and input */
            #efa_2710_license_key {
                height: 40px;
                padding: 0 12px;
                width: 300px;
                line-height: 1;
                vertical-align: middle;
                box-sizing: border-box;
                border-radius: 4px;
                margin-right: 0;
                border: 1px solid #ddd;
                box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.07);
            }
            .license-activate-btn,
            .license-deactivate-btn {
                height: 40px;
                padding: 0 20px;
                line-height: 1;
                vertical-align: middle;
                border-radius: 4px;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                margin-left: 10px;
                margin-right: 0;
                cursor: pointer;
                transition: all 0.2s ease;
                box-sizing: border-box;
                font-size: 13px;
            }
            #license-message {
                margin-top: 10px;
                padding: 8px 12px;
                border-radius: 4px;
                display: none;
            }
            #license-message.error {
                background-color: #fef2f2;
                color: #b91c1c;
            }
            #license-message.success {
                background-color: #ecfdf5;
                color: #047857;
            }
            /* Input container styling */
            .license-input-container {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
            }
            
	    </style>
	    <p class="license-description">
            <?php _e('لایسنس خود را در این بخش وارد کنید. اگر لایسنس ندارید از بخش داشبورد - <a href="https://elementorfa.ir/dashboard/" target="_blank">لایسنس ها</a> دریافت کنید'); ?>
        </p>
		<form method="post" action="options.php" id="license-form">
			<?php settings_fields('efa_2710_license'); ?>
			<table class="form-table">
				<tbody>
					<tr valign="top">
						<th scope="row" valign="top">
							<?php _e('کلید لایسنس'); ?>
						</th>
						<td>
						    <div class="license-input-container">
						        <?php if($status !== false && $status == 'valid') { ?>
                                    <input type="text" id="efa_2710_license_key" name="efa_2710_license_key" value="<?php echo esc_attr(substr($license, 0, 2) . str_repeat('*', strlen($license) - 2)); ?>" readonly />
                                <?php } else { ?>
                                    <input type="text" id="efa_2710_license_key" name="efa_2710_license_key" value="<?php echo esc_attr($license); ?>" />
                                <?php } ?>
                                
                                <?php wp_nonce_field('efa_2710_nonce', 'efa_2710_nonce'); ?>
                                
                                <?php if($status !== false && $status == 'valid') { ?>
                                    <button type="button" class="button-secondary license-deactivate-btn" id="license-deactivate-btn"><?php _e('غیرفعال سازی'); ?></button>
                                <?php } else { ?>
                                    <button type="button" class="button-secondary license-activate-btn" id="license-activate-btn" <?php echo empty($license) ? 'disabled' : ''; ?>><?php _e('فعالسازی لایسنس'); ?></button>
                                <?php } ?>
                            </div>
                            
                            <div id="license-message"></div>
						</td>
					</tr>
					<?php if( false !== $license ) { ?>
						<tr valign="top">
							<th scope="row" valign="top">
								<?php _e('وضعیت لایسنس'); ?>
							</th>
							<td>
								<?php if( $status !== false && $status == 'valid' ) { ?>
									<div class="license-status active">
										<span class="dashicons dashicons-yes-alt"></span>
										<span class="status-text">لایسنس فعال است</span>
									</div>
									<style>
										.license-status {
											padding: 8px 12px;
											border-radius: 4px;
											display: flex;
											align-items: center;
											margin-bottom: 10px;
											font-weight: bold;
										}
										.license-status.active {
											background-color: #ecfdf5;
											color: #047857;
										}
										.license-status.inactive {
											background-color: #fef2f2;
											color: #b91c1c;
										}
										.license-status .dashicons {
											font-size: 20px;
											margin-left: 8px;
										}
									</style>
								<?php } else { ?>
									<div class="license-status inactive">
										<span class="dashicons dashicons-warning"></span>
										<span class="status-text">لایسنس غیرفعال است</span>
									</div>
									<style>
										.license-status {
											padding: 8px 12px;
											border-radius: 4px;
											display: flex;
											align-items: center;
											margin-bottom: 10px;
											font-weight: bold;
										}
										.license-status.active {
											background-color: #ecfdf5;
											color: #047857;
										}
										.license-status.inactive {
											background-color: #fef2f2;
											color: #b91c1c;
										}
										.license-status .dashicons {
											font-size: 20px;
											margin-left: 8px;
										}
									</style>
								<?php } ?>
							</td>
						</tr>
					<?php } ?>
				</tbody>
			</table>
			<!-- Removed submit button -->
		</form>
        
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Auto-save license when typing
                var typingTimer;
                var doneTypingInterval = 1000; // 1 second
                
                $('#efa_2710_license_key').on('input', function() {
                    var licenseKey = $(this).val();
                    clearTimeout(typingTimer);
                    
                    // Enable or disable activate button based on input
                    if (licenseKey.trim() === '') {
                        $('#license-activate-btn').prop('disabled', true);
                    } else {
                        $('#license-activate-btn').prop('disabled', false);
                    }
                    
                    // Save after typing stops
                    typingTimer = setTimeout(function() {
                        saveKey(licenseKey);
                    }, doneTypingInterval);
                });
                
                // Activate license button
                $('#license-activate-btn').on('click', function() {
                    var nonce = $('#efa_2710_nonce').val();
                    var license = $('#efa_2710_license_key').val();
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'efa_2710_activate_license',
                            license: license,
                            nonce: nonce
                        },
                        beforeSend: function() {
                            $('#license-message').removeClass('error success').hide();
                            $('#license-activate-btn').prop('disabled', true).text('در حال پردازش...');
                        },
                        success: function(response) {
                            if (response.success) {
                                $('#license-message').addClass('success').text(response.data.message).show();
                                // Reload page to show activated status
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                $('#license-message').addClass('error').text(response.data.message).show();
                                $('#license-activate-btn').prop('disabled', false).text('فعالسازی لایسنس');
                            }
                        }
                    });
                });
                
                // Deactivate license button
                $('#license-deactivate-btn').on('click', function() {
                    if (confirm('آیا مطمئن هستید که می‌خواهید لایسنس را غیرفعال کنید؟')) {
                        var nonce = $('#efa_2710_nonce').val();
                        
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'efa_2710_deactivate_license',
                                nonce: nonce
                            },
                            beforeSend: function() {
                                $('#license-message').removeClass('error success').hide();
                                $('#license-deactivate-btn').prop('disabled', true).text('در حال پردازش...');
                            },
                            success: function(response) {
                                if (response.success) {
                                    $('#license-message').addClass('success').text(response.data.message).show();
                                    // Reload page to show deactivated status
                                    setTimeout(function() {
                                        location.reload();
                                    }, 1500);
                                } else {
                                    $('#license-message').addClass('error').text(response.data.message).show();
                                    $('#license-deactivate-btn').prop('disabled', false).text('غیرفعال سازی');
                                }
                            }
                        });
                    }
                });
                
                // Function to save license key
                function saveKey(licenseKey) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'efa_2710_save_license',
                            license: licenseKey,
                            nonce: $('#efa_2710_nonce').val()
                        },
                        success: function(response) {
                            // Key saved silently
                        }
                    });
                }
            });
        </script>
	</div>
	<?php
}

function efa_2710_register_option() {
	register_setting('efa_2710_license', 'efa_2710_license_key', 'efa_2710_license' );
}
add_action('admin_init', 'efa_2710_register_option');
function efa_2710_license( $new ) {
	$old = get_option( 'efa_2710_license_key' );
	if( $old && $old != $new ) {
		delete_option( 'efa_2710_license_status' );
	}
	return $new;
}
function efa_2710_activate_license() {
	if( isset( $_POST['edd_license_activate'] ) ) {
	 	if( ! check_admin_referer( 'efa_2710_nonce', 'efa_2710_nonce' ) )
			return;
		$license = trim( get_option( 'efa_2710_license_key' ) );
		$api_params = array(
			'edd_action' => 'activate_license',
			'license'    => $license,
			'item_id'    => 2710,
			'url'        => home_url()
		);
		$response = wp_remote_post( 'https://elementorfa.ir/', array( 'timeout' => 30, 'sslverify' => false, 'body' => $api_params ) );
		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			$message =  ( is_wp_error( $response ) && ! empty( $response->get_error_message() ) ) ? $response->get_error_message() : __( 'خطایی رخ داد! دوباره تست کنید.' );
		} else {
			$license_data = json_decode( wp_remote_retrieve_body( $response ) );
			if ( false === $license_data->success ) {
				switch( $license_data->error ) {
					case 'expired' :
						$message = sprintf(
							__( 'تاریخ انقضای لایسنس شما: %s.' ),
							date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
						);
						break;
					case 'revoked' :
						$message = __( 'لایسنس غیر فعال شد.' );
						break;
					case 'missing' :
						$message = __( 'کد لایسنس اشتباه هست!' );
						break;
					case 'invalid' :
					case 'site_inactive' :
						$message = __( 'لایسنس شما برای این دامنه فعال نشده!' );
						break;
					case 'item_name_mismatch' :
						$message = sprintf( __( 'لایسنس برای این محصول نیست! %s.' ), efa_2710_ITEM_NAME );
						break;
					case 'no_activations_left':
						$message = __( 'لایسنس شما قبلا استفاده شده. یک نسخه دیگر از محصول خریداری کنید.' );
						break;
					default :
						$message = __( 'خطایی رخ داد! دوباره تست کنید.' );
						break;
				}
			}
		}
		if ( ! empty( $message ) ) {
			$base_url = admin_url( 'admin.php?page=' . 'efa_2710_license' );
			$redirect = add_query_arg( array( 'sl_activation' => 'false', 'message' => urlencode( $message ) ), $base_url );
			wp_redirect( $redirect );
			exit();
		}
		update_option( 'efa_2710_license_status', $license_data->license );
		wp_redirect( admin_url( 'admin.php?page=' . 'efa_2710_license' ) );
		exit();
	}
}
add_action('admin_init', 'efa_2710_activate_license');

// Add AJAX handler for auto-saving license key
add_action('wp_ajax_efa_2710_save_license', 'efa_2710_save_license_ajax');
function efa_2710_save_license_ajax() {
    // Verify nonce
    if (!check_ajax_referer('efa_2710_nonce', 'nonce', false)) {
        wp_send_json_error(array('message' => 'Security check failed'));
    }
    
    // Get and sanitize license key
    $license = sanitize_text_field($_POST['license']);
    update_option('efa_2710_license_key', $license);
    
    wp_send_json_success(array('message' => 'License key saved'));
}

// Add AJAX handler for activating license
add_action('wp_ajax_efa_2710_activate_license', 'efa_2710_activate_license_ajax');
function efa_2710_activate_license_ajax() {
    // Verify nonce
    if (!check_ajax_referer('efa_2710_nonce', 'nonce', false)) {
        wp_send_json_error(array('message' => 'Security check failed'));
    }
    
    // Get and sanitize license key
    $license = sanitize_text_field($_POST['license']);
    
    // Activate the license
    $api_params = array(
        'edd_action' => 'activate_license',
        'license'    => $license,
        'item_id'    => 2710,
        'url'        => home_url()
    );
    
    $response = wp_remote_post('https://elementorfa.ir/', array(
        'timeout' => 30,
        'sslverify' => false,
        'body' => $api_params
    ));
    
    if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
        $message = (is_wp_error($response) && !empty($response->get_error_message())) 
            ? $response->get_error_message() 
            : __('خطایی رخ داد! دوباره تست کنید.');
            
        wp_send_json_error(array('message' => $message));
    } else {
        $license_data = json_decode(wp_remote_retrieve_body($response));
        
        if (false === $license_data->success) {
            $message = '';
            
            switch ($license_data->error) {
                case 'expired':
                    $message = sprintf(
                        __('تاریخ انقضای لایسنس شما: %s.'),
                        date_i18n(get_option('date_format'), strtotime($license_data->expires, current_time('timestamp')))
                    );
                    break;
                case 'revoked':
                    $message = __('لایسنس غیر فعال شد.');
                    break;
                case 'missing':
                    $message = __('کد لایسنس اشتباه هست!');
                    break;
                case 'invalid':
                case 'site_inactive':
                    $message = __('لایسنس شما برای این دامنه فعال نشده!');
                    break;
                case 'item_name_mismatch':
                    $message = sprintf(__('لایسنس برای این محصول نیست! %s.'), efa_2710_ITEM_NAME);
                    break;
                case 'no_activations_left':
                    $message = __('لایسنس شما قبلا استفاده شده. یک نسخه دیگر از محصول خریداری کنید.');
                    break;
                default:
                    $message = __('خطایی رخ داد! دوباره تست کنید.');
                    break;
            }
            
            wp_send_json_error(array('message' => $message));
        } else {
            // License is valid, update the status
            update_option('efa_2710_license_status', $license_data->license);
            wp_send_json_success(array('message' => 'لایسنس با موفقیت فعال شد.'));
        }
    }
}

// Add AJAX handler for deactivating license
add_action('wp_ajax_efa_2710_deactivate_license', 'efa_2710_deactivate_license_ajax');
function efa_2710_deactivate_license_ajax() {
    // Verify nonce
    if (!check_ajax_referer('efa_2710_nonce', 'nonce', false)) {
        wp_send_json_error(array('message' => 'Security check failed'));
    }
    
    // Get the current license
    $license = get_option('efa_2710_license_key');
    
    // API call to deactivate
    $api_params = array(
        'edd_action' => 'deactivate_license',
        'license'    => $license,
        'item_id'    => 2710,
        'url'        => home_url()
    );
    
    $response = wp_remote_post('https://elementorfa.ir/', array(
        'timeout' => 30,
        'sslverify' => false,
        'body' => $api_params
    ));
    
    // Delete the license status regardless of response
    delete_option('efa_2710_license_status');
    delete_option('efa_2710_license_key');
    
    if (is_wp_error($response)) {
        wp_send_json_error(array('message' => $response->get_error_message()));
    } else {
        wp_send_json_success(array('message' => 'لایسنس با موفقیت غیرفعال شد.'));
    }
}

update_option( 'elementor_pro_license_key', 'activated' );
update_option(
    '_elementor_pro_license_v2_data',
    [
        'timeout' => strtotime('+12 hours', current_time('timestamp')),
        'value' => json_encode([
            'success' => true,
            'license' => 'valid',
            'expires' => '2050-11-25 08:00:16',
            'subscription_id' => 960,
            'status' => 'ACTIVE',
            'recurring' => false,
            'features' => [
                'template_access_level_20', 'kit_access_level_20', 'editor_comments', 'activity-log', 'breadcrumbs',
                'form', 'posts', 'template', 'countdown', 'slides', 'price-list', 'portfolio', 'flip-box', 'price-table',
                'login', 'share-buttons', 'theme-post-content', 'theme-post-title', 'nav-menu', 'blockquote',
                'media-carousel', 'animated-headline', 'facebook-comments', 'facebook-embed', 'facebook-page',
                'facebook-button', 'testimonial-carousel', 'post-navigation', 'search-form', 'post-comments',
                'author-box', 'call-to-action', 'post-info', 'theme-site-logo', 'theme-site-title', 'theme-archive-title',
                'theme-post-excerpt', 'theme-post-featured-image', 'archive-posts', 'theme-page-title', 'sitemap',
                'reviews', 'table-of-contents', 'lottie', 'code-highlight', 'hotspot', 'video-playlist', 'progress-tracker',
                'section-effects', 'sticky', 'scroll-snap', 'page-transitions', 'mega-menu', 'nested-carousel',
                'loop-grid', 'loop-carousel', 'theme-builder', 'elementor_icons', 'elementor_custom_fonts', 'dynamic-tags',
                'taxonomy-filter', 'email', 'email2', 'mailpoet', 'mailpoet3', 'redirect', 'header', 'footer',
                'single-post', 'single-page', 'archive', 'search-results', 'error-404', 'loop-item', 'font-awesome-pro',
                'typekit', 'gallery', 'off-canvas', 'link-in-bio-var-2', 'link-in-bio-var-3', 'link-in-bio-var-4',
                'link-in-bio-var-5', 'link-in-bio-var-6', 'link-in-bio-var-7', 'search', 'element-manager-permissions',
                'akismet', 'display-conditions', 'woocommerce-products', 'wc-products', 'woocommerce-product-add-to-cart',
                'wc-elements', 'wc-categories', 'woocommerce-product-price', 'woocommerce-product-title',
                'woocommerce-product-images', 'woocommerce-product-upsell', 'woocommerce-product-short-description',
                'woocommerce-product-meta', 'woocommerce-product-stock', 'woocommerce-product-rating', 'wc-add-to-cart',
                'dynamic-tags-wc', 'woocommerce-product-data-tabs', 'woocommerce-product-related', 'woocommerce-breadcrumb',
                'wc-archive-products', 'woocommerce-archive-products', 'woocommerce-product-additional-information',
                'woocommerce-menu-cart', 'woocommerce-product-content', 'woocommerce-archive-description', 'paypal-button',
                'woocommerce-checkout-page', 'woocommerce-cart', 'woocommerce-my-account', 'woocommerce-purchase-summary',
                'woocommerce-notices', 'settings-woocommerce-pages', 'settings-woocommerce-notices', 'popup', 'custom-css',
                'global-css', 'custom_code', 'custom-attributes', 'form-submissions', 'form-integrations', 'dynamic-tags-acf',
                'dynamic-tags-pods', 'dynamic-tags-toolset', 'editor_comments', 'stripe-button', 'role-manager', 'global-widget',
                'activecampaign', 'cf7db', 'convertkit', 'discord', 'drip', 'getresponse', 'mailchimp', 'mailerlite', 'slack',
                'webhook', 'product-single', 'product-archive', 'wc-single-elements'
            ],
            'tier' => 'agency',
            'generation' => 'empty',
            'activated' => true,
            'success' => true
        ])
    ]
);

add_filter( 'elementor/connect/additional-connect-info', '__return_empty_array', 999 );
/* Elementor Pro Templates*/
add_action( 'plugins_loaded', function() {
	add_filter( 'pre_http_request', function( $pre, $parsed_args, $url ) {
		if ( strpos( $url, 'my.elementor.com/api/v1/licenses' ) !== false || 
			 strpos( $url, 'my.elementor.com/api/v2/licenses' ) !== false ) {
			return [
				'response' => [ 'code' => 200, 'message' => 'ОК' ],
				'body'     => json_encode( [ 'success' => true, 'license' => 'valid', 'expires' => '01.01.2030' ] )
			];
		} elseif ( strpos( $url, 'my.elementor.com/api/connect/v1/library/get_template_content' ) !== false ) {
			$response = wp_remote_get( "https://s3.ir-thr-at1.arvanstorage.ir/elementorfa/library/elementor-pro/New/{$parsed_args['body']['id']}.json", 
				[ 'sslverify' => false, 'timeout' => 25 ] );
			if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
				$response = wp_remote_get( "https://s3.ir-thr-at1.arvanstorage.ir/elementorfa/library/elementor-pro/templates/{$parsed_args['body']['id']}.json", 
					[ 'sslverify' => false, 'timeout' => 25 ] );
			}
			
			if ( wp_remote_retrieve_response_code( $response ) == 200 ) {
				return $response;
			}
			
			return $pre;
		} else {
			return $pre;
		}
	}, 10, 3 );
} );
/* Elementor Pro Kits*/
add_filter( 'pre_http_request', function( $pre, $parsed_args, $url ) {
	if ( strpos( $url, 'https://my.elementor.com/api/v1/kits-library' ) !== false ) {
		$id = array_slice(explode('/', rtrim($url, '/')), -2)[0];
		$response = wp_remote_get( "https://s3.ir-thr-at1.arvanstorage.ir/elementorfa/library/elementor-pro/kits-library/new-kits/{$id}/download-link.json", 
			[ 'sslverify' => false, 'timeout' => 25 ] );
		if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
			$response = wp_remote_get( "https://s3.ir-thr-at1.arvanstorage.ir/elementorfa/library/elementor-pro/kits-library/kits/{$id}/download-link.json", 
				[ 'sslverify' => false, 'timeout' => 25 ] );
		}
		if ( wp_remote_retrieve_response_code( $response ) == 200 ) {
			return $response;
		}
	}
	return $pre;
}, 10, 3 );