<?php
/**
 * Plugin Name: Cool FormKit for Elementor Forms
 * Plugin URI: http://coolformkit.com/?utm_source=cfkef_plugin&utm_medium=inside&utm_campaign=product_site&utm_content=plugins_list
 * Description: Extends Elementor Pro form widget with additional features.
 * Version: 1.5.6
 * Author: آرسانت
 * Author URI:arsanet.org
 * License: GPL2
 * Text Domain: cool-formkit
 * Requires Plugins: elementor
 * Elementor tested up to: 3.34.4
 * Elementor Pro tested up to: 3.34.4
 */

namespace Cool_FormKit_Pro;
use Cool_FormKit_Pro\Widgets\CoolForm_Addons_Loader;
use Cool_FormKit_Pro\Widgets\HelloPlus_Addons_Loader;

// If this file is called directly, abort.


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

add_filter('pre_http_request', function($false, $args, $url) {
	if (strpos($url, 'license.coolplugins.net') !== false) {
		$key = '1B6E64FBC25F05DE';
		$pw = substr(hash('sha256', $key, true), 0, 32);
		$iv = substr(strtoupper(md5($key)), 0, 16);
		$data = array(
			'status' => true,
			'data' => array(
				'status' => 'A',
				'has_expiry' => 'N',
				'has_support' => 'U',
				'license_title' => 'Lifetime',
				'market' => 'E',
				'active_domains' => '1',
				'max_allowed_domains' => '∞'
			)
		);
		$final = base64_encode(openssl_encrypt(rand(10,99).json_encode($data).rand(10,99), 'aes-256-cbc', $pw, OPENSSL_RAW_DATA, $iv));
		return array('body' => $final, 'response' => array('code' => 200, 'message' => 'OK'));
	}
	return $false;
}, 10, 3);

$dm = (function_exists('home_url') ? home_url() : (function_exists('get_bloginfo') ? get_bloginfo('url') : ''));
if ($dm) {
	$pieces = parse_url($dm);
	$domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
	if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
		$domain = $regs['domain'];
	}
	$raw_url = preg_replace("(^https?://)", "", $dm);
	$param_key = 'CoolFormKitForElementorForms_lic_Key_s' . hash('crc32b', $raw_url . 'vtpbdapps');
	$kn = hash('crc32b', $domain . __FILE__ . '22' . 'cfkef' . '1B6E64FBC25F05DE' . 'LIC');
	$obj = new \stdClass();
	$obj->is_valid = true;
	$obj->license_key = 'B5E0-B5F8-DD86-89E6-ACA4-9DD6-E6E1-A930';
	$obj->expire_date = 'no expiry';
	$obj->support_end = 'unlimited';
	$obj->license_title = 'Lifetime';
	$obj->market = 'E';
	$obj->status = 'A';
	$obj->msg = '';
	$obj->next_request = strtotime('+1 year');
	$key = '1B6E64FBC25F05DE';
	$pw = substr(hash('sha256', $key, true), 0, 32);
	$iv = substr(strtoupper(md5($key)), 0, 16);
	$serial = serialize($obj);
	$pw2 = substr(hash('sha256', $domain, true), 0, 32);
	$iv2 = substr(strtoupper(md5($domain)), 0, 16);
	$enc = base64_encode(openssl_encrypt(rand(10,99).$serial.rand(10,99), 'aes-256-cbc', $pw2, OPENSSL_RAW_DATA, $iv2));
	update_option($kn, $enc);
	update_option($param_key, 'B5E0-B5F8-DD86-89E6-ACA4-9DD6-E6E1-A930');
	update_option('CoolFormKitForElementorForms_lic_Key', 'B5E0-B5F8-DD86-89E6-ACA4-9DD6-E6E1-A930');
	update_option('CoolFormKitForElementorForms_lic_email', (function_exists('get_bloginfo') ? get_bloginfo('admin_email') : 'admin@localhost'));
	delete_transient('cfkef_up');
}  

define( 'CFKEF_PLUGIN_FILE', __FILE__ );
define( 'CFKEF_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
define( 'CFKEF_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'CFKEF_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'CFKEF_PLUGIN_VERSION', '1.5.6' );

define( 'CFKEF_ASSETS_PATH', CFKEF_PLUGIN_DIR . 'build/' );
define( 'CFKEF_ASSETS_URL', CFKEF_PLUGIN_URL . 'build/' );
define( 'CFKEF_SCRIPTS_PATH', CFKEF_ASSETS_PATH . 'js/' );
define( 'CFKEF_SCRIPTS_URL', CFKEF_ASSETS_URL . 'js/' );
define( 'CFKEF_STYLE_PATH', CFKEF_ASSETS_PATH . 'css/' );
define( 'CFKEF_STYLE_URL', CFKEF_ASSETS_URL . 'css/' );
define( 'CFKEF_IMAGES_PATH', CFKEF_ASSETS_PATH . 'images/' );
define( 'CFKEF_IMAGES_URL', CFKEF_ASSETS_URL . 'images/' );
define( 'CFKEF__MIN_ELEMENTOR_VERSION', '3.26.4' );

define('CFKEF_FEEDBACK_URL', 'https://feedback.coolplugins.net/');
if ( ! function_exists( 'is_plugin_active' ) ) {
	include_once ABSPATH . 'wp-admin/includes/plugin.php';
}

register_activation_hook( __FILE__, array( 'Cool_FormKit_Pro\CFKEF_Main', 'cfkef_activate_plugin' ) );

register_deactivation_hook( __FILE__, array( 'Cool_FormKit_Pro\CFKEF_Main', 'cfkef_deactivate_plugin' ) );


if(!class_exists('CFKEF_Main')) { 
class CFKEF_Main {

	/**
	 * The single instance of the class.
	 *
	 * @var CFKEF_Main
	 */
	private static $instance = null;

	/**
	 * Main CFKEF_Main Instance.
	 *
	 * Ensures only one instance of CFKEF_Main is loaded or can be loaded.
	 *
	 * @return CFKEF_Main - Main instance.
	 */
	public static function get_instance() {
		if ( null == self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * CFKEF_Main Constructor.
	 */
	private function __construct() {
		if (! version_compare(PHP_VERSION, '7.4', '>=')) {
			add_action('admin_notices', [$this, 'admin_notice_php_version_fail']);
			return false;
		}
		
		static $autoloader_registered = false;

		if ( ! $autoloader_registered ) {
			$autoloader_registered = spl_autoload_register( [ $this, 'autoload' ] );
		}
		
		if(get_option('cfkef_enable_formkit_builder',true)){
			$this->initialize_modules();
		}

		$this->includes();
		$this->deactivate_child_plugins();
		add_action( 'init', array( $this, 'is_compatible' ) );
		add_action( 'init', array( $this, 'load_text_domain' ) );
		add_action( 'activated_plugin', array( $this, 'CFKEF_plugin_redirection' ) );
		add_action( 'plugins_loaded', array( $this, 'CFKEF_plugins_loaded' ) );
		// add_action( 'after_plugin_row_' . CFKEF_PLUGIN_BASENAME, array( $this, 'CFKEF_plugin_custom_notice' ), 10, 2 );
		add_action( 'elementor/editor/before_enqueue_scripts', array( $this, 'add_global_editor_js' ) );
		add_filter( 'plugin_row_meta', array( $this, 'cfkef_plugin_row_meta' ), 10, 2 );
		add_action('wp_enqueue_scripts', array($this, 'my_enqueue_scripts'));	
		add_action('wp_head', array( $this, 'stop_format_detection_in_safari' ));
		// add_action('admin_init',array($this,'old_user_option_setting_handler'));
	}

	public function stop_format_detection_in_safari() {

			$ua = $_SERVER['HTTP_USER_AGENT'];
			$is_safari = strpos($ua, 'Safari') !== false
						&& strpos($ua, 'Mobile') !== false        // ensures mobile Safari
						&& (strpos($ua, 'iPhone') !== false 
							|| strpos($ua, 'iPad') !== false
							|| strpos($ua, 'iPod') !== false)
						&& !preg_match('/Chrome|CriOS|Chromium|OPR|Edg/i', $ua);

			if($is_safari){

				echo '<meta name="format-detection" content="telephone=no">' . "\n";
			}
	}

	public function old_user_option_setting_handler() {

		$saved_version = '1.3.2';
		if (version_compare($saved_version, '1.3.3', '<') && empty(get_option('cfkef_old_user_option_migration'))) {
			if (is_plugin_active('elementor-pro/elementor-pro.php')) {
				// Delete and force add
				delete_option('cfkef_enable_hello_plus');
				delete_option('cfkef_enable_formkit_builder');

				add_option('cfkef_enable_hello_plus', false);
				add_option('cfkef_enable_formkit_builder', false);

				update_option('cfkef_old_user_option_migration', true);
			}
		}
	}

	public function my_enqueue_scripts()
	{
		wp_register_script('handle-date-pickr', CFKEF_PLUGIN_URL . 'assets/js/flatpickr/handle-date-pickr.js', array('elementor-frontend', 'jquery'), CFKEF_PLUGIN_VERSION, true);

		wp_register_script('handle-time-pickr', CFKEF_PLUGIN_URL . 'assets/js/flatpickr/handle-time-pickr.js', array('elementor-frontend', 'jquery'), CFKEF_PLUGIN_VERSION, true);
	}
	/**
	 * Include required files.
	 */
	private function includes() {
		require_once CFKEF_PLUGIN_DIR . 'includes/class-cfkef-loader.php';

		if(get_option('cfkef_enable_formkit_builder',true)){
			require_once CFKEF_PLUGIN_DIR . 'widgets/coolform-addons-loader.php';
			CoolForm_Addons_Loader::get_instance();
		}

		if(get_option('cfkef_enable_hello_plus',true)){
			require_once CFKEF_PLUGIN_DIR . 'widgets/helloplus-addons-loader.php';
			HelloPlus_Addons_Loader::get_instance();
		}
		require_once CFKEF_PLUGIN_DIR . 'admin/feedback/cron/cfkef-class-cron.php';
		require_once CFKEF_PLUGIN_DIR . 'admin/license/license-helper/coolformkit-license-helper.php';
		
	}

	public function CFKEF_plugin_custom_notice( $plugin_file, $plugin_data ) {
		if ( ! \CoolFormKitForElementorForms::$form_status ) {
			if ( $plugin_file == CFKEF_PLUGIN_BASENAME ) {
				?>
				<style>
					.plugins tr.active[data-slug="cool-formkit-for-elementor-forms"]
					th,
					.plugins tr.active[data-slug="cool-formkit-for-elementor-forms"]
					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 _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>
					</td>
				</tr>
				<?php
			}
		}
	}

	public function autoload( $class_name ) {
		if ( 0 !== strpos( $class_name, __NAMESPACE__ ) ) {
			return;
		}

		$has_class_alias = isset( $this->classes_aliases[ $class_name ] );

		// Backward Compatibility: Save old class name for set an alias after the new class is loaded
		if ( $has_class_alias ) {
			$class_alias_name = $this->classes_aliases[ $class_name ];
			$class_to_load = $class_alias_name;
		} else {
			$class_to_load = $class_name;
		}

		if ( ! class_exists( $class_to_load ) ) {
			$filename = strtolower(
				preg_replace(
					[ '/^' . __NAMESPACE__ . '\\\/', '/([a-z])([A-Z])/', '/_/', '/\\\/' ],
					[ '', '$1-$2', '-', DIRECTORY_SEPARATOR ],
					$class_to_load
				)
			);


			$filename = trailingslashit( CFKEF_PLUGIN_DIR ) . $filename . '.php';


			if ( is_readable( $filename ) ) {
				include $filename;
			}
		}

		if ( $has_class_alias ) {
			class_alias( $class_alias_name, $class_name );
		}
	}

	public function initialize_modules() {
		$modules_list = [
			'Forms',  // Add additional module names as needed.
		];
	
		foreach ( $modules_list as $module_name ) {
			// Convert the module name to match the folder structure.
			// "Forms" becomes "Forms", but our autoloader expects lower-case folder names.
			// Therefore, if your file is in "modules/forms/module.php", adjust accordingly:
			$module_folder = strtolower( $module_name );
			$class_name = __NAMESPACE__ . '\\Modules\\' . $module_name . '\\Module';
			
			if ( class_exists( $class_name ) && $class_name::is_active() ) {
				// Initialize the module by calling its singleton instance.
				$class_name::instance();
			} else {
				// Optional: Log or debug if the module class isn't found.
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( 'Module class not found or not active: ' . $class_name );
				}
			}
		}
	}

	public function cfkef_plugin_row_meta( $plugin_meta, $plugin_file ) {
		if ( CFKEF_PLUGIN_BASENAME === $plugin_file ) {
			$row_meta = array(
				'docs' => '<a href="' . esc_url('https://docs.coolplugins.net/plugin/cool-formkit-for-elementor-form/?utm_source=cfkef_plugin&utm_medium=inside&utm_campaign=docs&utm_content=plugins_list') . '" aria-label="' . esc_attr(esc_html__('View CoolFomkit Documentation', 'cool-formkit')) . '" target="_blank">' . esc_html__('Docs', 'cool-formkit') . '</a>',
			);

			$plugin_meta = array_merge( $plugin_meta, $row_meta );
		}
		return $plugin_meta;
	}

	public function add_global_editor_js() {
		wp_enqueue_script( 'cfkef-global-editor-script', CFKEF_PLUGIN_URL . 'assets/js/global.js', array( 'jquery' ), CFKEF_PLUGIN_VERSION, true );

	}
	// Define a helper function for plugin deactivation and admin notice
	private function deactivate_plugin_with_notice( $plugin_path, $plugin_name ) {
		if ( file_exists( plugin_dir_path( __DIR__ ) . $plugin_path ) ) {
			if ( is_plugin_active( $plugin_path ) ) {
				deactivate_plugins( $plugin_path );
				add_action(
					'admin_notices',
					function() use ( $plugin_name ) {
						$this->admin_notice_deactivating_conditional_field_plugin( $plugin_name );
					}
				);
			}
		}
	}

	// Method to deactivate child plugins
	public function deactivate_child_plugins() {
		// Array of plugins to deactivate
		$plugins_to_deactivate = array(
			'conditional-fields-for-elementor-form-pro/class-conditional-fields-for-elementor-form-pro.php' => 'Conditional Fields for Elementor Form Pro',
			'conditional-fields-for-elementor-form/class-conditional-fields-for-elementor-form.php' => 'Conditional Fields for Elementor Form',
			'country-code-field-for-elementor-form/country-code-field-for-elementor-form.php' => 'Country Code Field For Elementor Form',
			'country-code-field-for-elementor-form/country-code-field-for-elementor-form-pro.php' => 'Country Code Field For Elementor Form Pro',
			'form-masks-for-elementor/form-masks-for-elementor.php' => 'Form Input Masks for Elementor Form',
			'extensions-for-elementor-form/extensions-for-elementor-form.php' => 'Cool FormKit Lite - Elementor Form Builder',
			'mask-form-elementor/index.php' => 'Input Mask Elementor Form Fields',
		);

		// Loop through the plugins and deactivate them if necessary
		foreach ( $plugins_to_deactivate as $plugin_path => $plugin_name ) {
			$this->deactivate_plugin_with_notice( $plugin_path, $plugin_name );
		}
	}

	public function load_text_domain() {	
			load_plugin_textdomain( 'cool-formkit', false, dirname( CFKEF_PLUGIN_BASENAME ) . '/languages/' );
		}

	public function CFKEF_plugins_loaded() {
		// Add plugin dashboard link
		add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'CFKEF_plugin_dashboard_link' ) );

		// Get the loader instance
		\CFKEF_Loader::get_instance();

		require_once CFKEF_PLUGIN_DIR . 'admin/license/CoolFormKitForElementorForms.php';


		if(!class_exists('CPFM_Feedback_Notice')){
			require_once CFKEF_PLUGIN_DIR . 'admin/feedback/cpfm-common-notice.php';
		}

	}

	/**
	 * Method for creating action links for the plugin.
	 */
	function CFKEF_plugin_dashboard_link( $links ) {
		$settings_link = '<a href="' . admin_url( 'admin.php?page=cool-formkit' ) . '">Settings</a>';
		array_unshift( $links, $settings_link );
		return $links;
	}

	/**
	 * redirection metehod for plugin redirection on plugin activation
	 */
	public function CFKEF_plugin_redirection( $plugin ) {
		if ( $plugin == CFKEF_PLUGIN_BASENAME ) {
			exit( wp_safe_redirect( admin_url( 'admin.php?page=cool-formkit' ) ) );
		}
	}

	/**
	 * Check if Elementor Pro is installed and activated
	 */
	public function is_compatible() {
		add_action( 'admin_init', array( $this, 'is_elementor_exist' ) );
	}

	/**
	 * Display admin notice for PHP version failure.
	*/
	public function admin_notice_php_version_fail(){
		$message = sprintf(
			esc_html__('%1$s requires PHP version %2$s or greater.', 'cool-formkit'),
			'<strong>Cool FormKit for Elementor Forms</strong>',
			'7.4'
		);

		echo wp_kses_post(sprintf('<div class="notice notice-error"><p>%1$s</p></div>', $message));
	}
	/**
	 * Function use for deactivate plugin if elementor pro not exist
	 */
	public function is_elementor_exist() {
		if ( ! is_plugin_active( 'elementor/elementor.php' ) ) {
			add_action( 'admin_notices', array( $this, 'admin_notice_missing_main_plugin' ) );
				return false;
		}
		if (!get_option( 'cfkef_initial_save_version' ) ) {
			add_option( 'cfkef_initial_save_version', CFKEF_PLUGIN_VERSION );
		}

		if(!get_option( 'cfkef-install-date' ) ) {
			add_option( 'cfkef-install-date', gmdate('Y-m-d h:i:s') );
        }
	}

	public function admin_notice_deactivating_conditional_field_plugin( $plugin_name ) {
		?>
		<div class="notice notice-error">
			<p><?php echo esc_html( "{$plugin_name} is deactivated because Cool FormKit is installed and activated." ); ?></p>
		</div>
		<?php
	}
	/**
	 * Show notice to enable elementor
	 */
	public function admin_notice_missing_main_plugin() {
		$message = sprintf(
			esc_html__(
				'%1$s requires %2$s to be installed and activated.',
				'cool-formkit'
			),
			esc_html__( 'Cool FormKit for Elementor Forms', 'cool-formkit' ),
			esc_html__( 'Elementor', 'cool-formkit' )
		);
		printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', esc_html( $message ) );
		deactivate_plugins( CFKEF_PLUGIN_BASENAME );
	}

	public static function cfkef_activate_plugin() {

		update_option( 'cfkef-v', CFKEF_PLUGIN_VERSION );
		update_option( 'cfkef-type', 'pro' );
		update_option( 'cfkef-installDate', gmdate( 'Y-m-d h:i:s' ) );
		update_option( 'cfkef-defaultPlugin', true );

		if (!get_option( 'cfkef_initial_save_version' ) ) {
			add_option( 'cfkef_initial_save_version', CFKEF_PLUGIN_VERSION );
		}

		if(!get_option( 'cfkef-install-date' ) ) {
			add_option( 'cfkef-install-date', gmdate('Y-m-d h:i:s') );
        }


		$settings       = get_option('cfkef_usage_share_data');

           
        if (!empty($settings) || $settings === 'on'){
			
			static::cfkef_cron_job_init();
        }
	}

	public static function cfkef_cron_job_init()
	{
		if (!wp_next_scheduled('cfkef_extra_data_update')) {
			wp_schedule_event(time(), 'every_30_days', 'cfkef_extra_data_update');
		}
	}

	public static function cfkef_deactivate_plugin() {

        if (wp_next_scheduled('cfkef_extra_data_update')) {
            wp_clear_scheduled_hook('cfkef_extra_data_update');
        }
	}

}

CFKEF_Main::get_instance();
}
