<?php

namespace KaliForms\Inc;

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

use KaliForms\Inc\Backend\Conditional_Thank_You;
use KaliForms\Inc\Backend\Modula_Integration;
use KaliForms\Inc\Backend\Multiple_Entries_Prevention;
use KaliForms\Inc\Backend\Views\Store_Page;
use KaliForms\Inc\Frontend\Conditional_Logic;
use KaliForms\Inc\Frontend\Form_Scripting;
use KaliForms\Inc\Pro_Form_Fields;
use KaliForms\Inc\Utils\KaliForms_Store;

/**
 * Class KaliForms_Pro
 *
 * @package Inc
 */
class KaliForms_Pro
{
	/**
	 * Plugin slug
	 *
	 * @var string
	 */
	protected $slug = 'kaliforms-pro';

	/**
	 * Parent plugin slug
	 *
	 * @var string
	 */
	protected $parent_slug = 'kaliforms';

	/**
	 * KaliForms_Pro constructor.
	 */
	public function __construct()
	{
		add_action('admin_head', [$this, 'check_if_kaliforms_is_installed']);
		add_action('plugins_loaded', [$this, 'hook_into_main'], 8);
	}

	/**
	 * Returns an instance of the plugin
	 *
	 * @return KaliForms_Pro
	 */
	public static function get_instance()
	{
		static $inst;
		if (!$inst) {
			$inst = new KaliForms_Pro();
		}

		return $inst;
	}

	/**
	 * Checks if kaliforms is installed, and if not .. display a notice
	 */
	public function check_if_kaliforms_is_installed()
	{
		$plugins = get_plugins();
		$status  = array_key_exists('kali-forms/kali-forms.php', $plugins)
			? 'installed' : 'not-installed';

		if ($status === 'installed') {
			$status = is_plugin_active('kali-forms/kali-forms.php') ? 'active'
				: 'installed';
		}

		if ($status === 'active') {
			return;
		}

		$action = '';
		$url    = '';
		$label  = '';
		switch ($status) {
			case 'installed':
				//activate plugin
				$label  = esc_html__('Activate', 'kaliforms');
				$action = 'activate';
				$url    = add_query_arg(
					[
						'action' => 'activate',
						'plugin' => rawurlencode(
							'kali-forms/kali-forms.php'
						),
						'plugin_status' => 'all',
						'paged' => '1',
						'_wpnonce' => wp_create_nonce(
							'activate-plugin_kali-forms/kali-forms.php'
						),
					],
					admin_url('plugins.php')
				);
				break;
			case 'not-installed':
				//install & activate plugin
				$label  = esc_html__('Install & activate', 'kaliforms');
				$action = 'install';
				$url    =
					'https://downloads.wordpress.org/plugin/kali-forms.latest-stable.zip';
				break;
		}

		$html =
			'<div class="notice" style="background: #e9eff3;padding: 40px;border: 10px solid #fff;text-align:center;">';
		$html .= '<h1 style="text-align:center; margin-bottom:15px">';
		$html .= esc_html__('Install & Activate Kali Forms', 'kaliforms');
		$html .= '</h1>';
		$html .= '<h4>' . esc_html__(
			'To use Kali Forms Pro, you also need to install & activate Kali Forms Lite.'
		) . '</h4>';
		$html .= '<a href="' . esc_url($url) . '" data-download-url="' .
			esc_url($url) . '" data-action="' . esc_attr($action) .
			'" class="button button-primary button-hero" id="install-kali-forms" style="line-height: 23px;padding: 12px 36px;">' .
			$label . '</a>';
		$html .= '</div>';

		echo $html;
	}

	/**
	 * Small check to see if plugin is installed
	 */
	public function kaliforms_installed()
	{
		$plugins = get_plugins();
		$status  = array_key_exists('kali-forms/kali-forms.php', $plugins)
			? 'installed' : 'not-installed';

		return $status === 'installed';
	}

	/**
	 * Hooks into main plugin
	 *
	 * @return void
	 */
	public function hook_into_main()
	{
		/**
		 * Admin enqueue script
		 */
		add_action('admin_enqueue_scripts', [$this, 'admin_enqueue'], 98);

		if (!defined('KALIFORMS_VERSION')) {
			return;
		}

		if (version_compare(KALIFORMS_VERSION, '1.4.0', '>=')) {
			add_action(
				$this->parent_slug . '_after_load_script_function',
				[
					$this,
					'enqueue',
				],
				98
			);
		} else {
			add_action('wp_enqueue_scripts', [$this, 'enqueue'], 98);
		}

		/**
		 * Save the instance in the main array
		 */
		add_filter(
			$this->parent_slug . '_hook_external_plugins',
			[
				$this,
				'return_an_instance',
			]
		);
		add_filter(
			$this->parent_slug . '_predefined_forms',
			[
				$this,
				'predefined_forms',
			]
		);

		new Form_Scripting();
		new Conditional_Logic();
		new Conditional_Thank_You();
		new Multiple_Entries_Prevention();
		new Modula_Integration();

		$this->network() ? add_action(
			'network_admin_menu',
			[
				$this,
				'register_network_menu',
			]
		) : add_action('admin_menu', [$this, 'register_submenus']);

		/**
		 * Hook after the main plugin finished construction
		 */
		add_action(
			$this->parent_slug . '_after_construction',
			[
				$this,
				'init_pro_features',
			]
		);

		$store = KaliForms_Store::get_instance();
	}

	/**
	 * Initiates pro features
	 *
	 * @return void
	 */
	public function init_pro_features()
	{
		$form_fields = new Pro_Form_Fields();
	}

	/**
	 * Returns an instance of the plugin in the main plugin object
	 *
	 * @param [type] $plugins
	 * @return void
	 */
	public function return_an_instance($plugins)
	{
		$plugins[$this->slug] = $this;

		return $plugins;
	}

	/**
	 * Predefined forms
	 *
	 * @param [type] $forms
	 * @return void
	 */
	public function predefined_forms($forms)
	{
		foreach ($forms as $k => $v) {
			$forms[$k]['pro'] = false;
		}

		return $forms;
	}

	/**
	 * Register submenus
	 *
	 * @return void
	 */
	public function register_submenus()
	{
		// add_submenu_page(
		//     'edit.php?post_type=kaliforms_forms',
		//     esc_html__('License', 'kaliforms'),
		//     esc_html__('License', 'kaliforms'),
		//     'manage_options',
		//     'kaliforms-license',
		//     new License_Page()
		// );

		add_submenu_page(
			'edit.php?post_type=kaliforms_forms',
			esc_html__('Licensing', 'kaliforms'),
			esc_html__('Licensing', 'kaliforms'),
			'manage_options',
			'kaliforms-store-auth',
			new Store_Page()
		);
	}

	/**
	 * Registers the network menu
	 */
	public function register_network_menu()
	{
		add_menu_page(
			esc_html__('Kali Forms', 'kaliforms'),
			esc_html__('Kali Forms', 'kaliforms'),
			'manage_options',
			'kaliforms-store-auth',
			new Store_Page()
		);
	}

	/**
	 * Admin enqueue scripts
	 *
	 * @return void
	 */
	public function admin_enqueue()
	{
		$screen = get_current_screen();
		if ('kaliforms_forms' === get_post_type() && 'post' === $screen->base) {
			wp_enqueue_script(
				'kaliforms-forms-pro',
				KALIFORMS_PRO_URL . 'assets/backend/js/kaliforms-pro.js',
				[],
				KALIFORMS_PRO_VERSION,
				false
			);
		}

		wp_register_script(
			'kaliforms-extensions',
			KALIFORMS_PRO_URL . 'assets/extensions/js/kaliforms-extensions.js',
			[
				'jquery',
				'updates',
			],
			KALIFORMS_PRO_VERSION,
			true
		);
		wp_localize_script(
			'kaliforms-extensions',
			'KaliFormsExtensions',
			['ajax_nonce' => wp_create_nonce('kaliforms_extensions_nonce')]
		);

		if (in_array(
			$screen->base,
			[
				'kaliforms_forms_page_kaliforms-store-auth',
				'toplevel_page_kaliforms-store-auth-network',
			]
		)) {
			wp_enqueue_script(
				'kaliforms-store',
				KALIFORMS_PRO_URL . 'assets/store/js/store.js',
				['wp-i18n'],
				KALIFORMS_PRO_VERSION,
				true
			);

			wp_enqueue_style(
				'kaliforms-store',
				KALIFORMS_PRO_URL . 'assets/store/css/store.css',
				[],
				KALIFORMS_PRO_VERSION
			);

			$store = KaliForms_Store::get_instance();
			$auth  = $store->get_stored_auth();

			$authUrl = KALIFORMS_API . 'store/auth?redirect=' . admin_url();
			if ($this->network()) {
				$authUrl .= '&network=1';
			}
			wp_localize_script(
				'kaliforms-store',
				'KaliFormsStore',
				[
					'authUrl' => $authUrl,
					'auth' => !is_wp_error($auth) &&
						!empty($auth['access_token']),
					'accessToken' => !is_wp_error($auth) &&
						!empty($auth['access_token']) ? $auth['access_token']
						: null,
					'oldLicensing' => get_option(
						'kaliforms_pro_old_licensing',
						false
					),
					'ajax_nonce' => wp_create_nonce('kaliforms_store_nonce'),
					'url' => home_url(),
					'neededPluginData' => $store->get_needed_plugin_data(),
					'network' => $this->network(),
				]
			);
		}

		if ('kaliforms_forms_page_kaliforms-extensions' === $screen->base) {
			wp_enqueue_script('kaliforms-extensions');
		}

		if (is_admin() && !$this->kaliforms_installed()) {
			wp_enqueue_script('kaliforms-extensions');
		}
	}

	/**
	 * Enqueue scripts
	 *
	 * @param $shortcode_class
	 * @return void
	 */
	public function enqueue($shortcode_class)
	{
		wp_register_script(
			'kaliforms-pro-math',
			KALIFORMS_PRO_URL . 'assets/frontend/js/kaliforms-math.js',
			[],
			KALIFORMS_PRO_VERSION
		);

		$deps_name = [
			'kaliforms-choices',
			'kaliforms-datetimepicker',
			'kaliforms-range',
			'kaliforms-rating',
		];

		foreach ($deps_name as $name) {
			wp_register_script(
				$name,
				KALIFORMS_PRO_URL . 'assets/frontend/js/' . $name . '.js',
				[],
				KALIFORMS_PRO_VERSION
			);
			wp_register_style(
				$name,
				KALIFORMS_PRO_URL . 'assets/frontend/css/' . $name . '.css',
				[],
				KALIFORMS_PRO_VERSION
			);
		}

		$deps = $this->determine_asset_load($shortcode_class);
		if ($this->elementor_preview()) {
			return;
		}
		wp_enqueue_style(
			'kaliforms-pro',
			KALIFORMS_PRO_URL . 'assets/frontend/css/kaliforms-pro.css',
			$deps['styles'],
			KALIFORMS_PRO_VERSION
		);
		wp_enqueue_script('media-editor');
		wp_enqueue_script(
			'kaliforms-pro',
			KALIFORMS_PRO_URL . 'assets/frontend/js/kaliforms-pro.js',
			$deps['scripts'],
			KALIFORMS_PRO_VERSION,
			true
		);
	}

	/**
	 * Determines what assets we need to load
	 *
	 * @param [type] $class
	 * @return array
	 */
	public function determine_asset_load($class)
	{
		$deps = [
			'scripts' => ['kaliforms-frontend'],
			'styles' => [],
		];

		$calculator = get_post_meta(
			$class->post->ID,
			$this->parent_slug . '_form_calculator',
			true
		);
		if (!empty($calculator)) {
			$deps['scripts'][] = 'kaliforms-pro-math';
		}

		foreach ($class->fields as $field) {
			if (
				$field->id === 'rating' &&
				!in_array('kaliforms-rating', $deps['scripts'])
			) {
				$deps['scripts'][] = 'jquery';
				$deps['scripts'][] = 'kaliforms-rating';
				$deps['styles'][]  = 'kaliforms-rating';
			}
			if (
				$field->id === 'range' &&
				!in_array('kaliforms-range', $deps['scripts'])
			) {
				$deps['scripts'][] = 'kaliforms-range';
				$deps['styles'][]  = 'kaliforms-range';
			}
			if (
				$field->id === 'dateTimePicker' &&
				!in_array('kaliforms-datetimepicker', $deps['scripts'])
			) {
				$deps['scripts'][] = 'kaliforms-datetimepicker';
				$deps['styles'][]  = 'kaliforms-datetimepicker';
			}

			if (
				$field->id === 'choices' &&
				!in_array('kaliforms-choices', $deps['scripts'])
			) {
				$deps['scripts'][] = 'kaliforms-choices';
				$deps['styles'][]  = 'kaliforms-choices';
			}
		}

		return $deps;
	}

	/**
	 * @return bool
	 */
	public function network()
	{
		if (!function_exists('is_plugin_active_for_network')) {
			include_once(ABSPATH . 'wp-admin/includes/plugin.php');
		}

		return is_plugin_active_for_network(
			'kali-forms-pro/kali-forms-pro.php'
		);
	}

	/**
	 * Are we within the elementor preview?
	 *
	 * @return void
	 */
	public function elementor_preview()
	{
		if (empty($_GET)) {
			return false;
		}

		if (isset($_GET['action']) && $_GET['action'] === 'elementor') {
			return true;
		}
	}
}
