<?php

namespace KaliForms\Inc\Frontend;

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

class Form_Scripting {
	/**
	 * Plugin slug
	 *
	 * @var string
	 */
	protected $slug = 'kaliforms-pro';
	/**
	 * Parent plugin slug
	 *
	 * @var string
	 */
	protected $parent_slug = 'kaliforms';

	/**
	 * Class constructor
	 */
	public function __construct() {
		if ( ! is_admin() ) {
			add_filter( $this->parent_slug . '_before_form_start', [ $this, 'add_custom_css' ] );
			add_filter( $this->parent_slug . '_before_form_end', [ $this, 'add_custom_js' ] );
			add_filter( $this->parent_slug . '_before_form_end', [ $this, 'add_calculation' ] );
		}

		/**
		 * Meta save fields
		 */
		add_filter( $this->parent_slug . '_meta_save_fields', [ $this, 'add_meta_fields' ] );
		/**
		 * Adds scripting to vars
		 */
		add_filter( $this->parent_slug . '_jsvars_object', [ $this, 'add_scripting_to_js_vars' ] );
		/**
		 * PHP Scripting areas
		 */
		add_filter( $this->parent_slug . '_before_form_process', [ $this, 'before_form_process_script' ] );
		add_filter( $this->parent_slug . '_after_form_process', [ $this, 'after_form_process_script' ] );

		add_filter( $this->parent_slug . '_before_form_process', [ $this, 'handle_password_fields' ] );
	}

	/**
	 * Handles password files ( if they need encoding, we use standard WP function or any other plugin that is hooked
	 * into )
	 */
	public function handle_password_fields( $form_data ) {
		$fields = json_decode( get_post_meta( $form_data['formId'], $this->parent_slug . '_field_components', true ), false, 512, JSON_HEX_QUOT );

		$password_fields = [];

		foreach ( $fields as $field ) {
			if ( $field->id === 'password' ) {
				$password_fields[ $field->properties->name ] = $field->properties->hashPassword;
			}
		}

		foreach ( $password_fields as $k => $v ) {
			if ( $v ) {
				$form_data[ $k ] = wp_hash_password( $form_data[ $k ] );
			}
		}

		return $form_data;
	}

	/**
	 * Runs before the form process is started
	 *
	 * @param [type] $form_data
	 *
	 * @return void
	 */
	public function before_form_process_script( $form_data ) {
		$phpBefore = get_post_meta( $form_data['formId'], $this->parent_slug . '_form_scripting_php_before', true );
		if ( $this->network() ) {
			return $form_data;
		}
		if ( $phpBefore !== '' ) {
			eval( $phpBefore );
		}

		return $form_data;
	}

	/**
	 * Runs after the form process has concluded, before thank you message is shown
	 *
	 * @param [type] $form_data
	 *
	 * @return void
	 */
	public function after_form_process_script( $form_data ) {
		$phpAfter = get_post_meta( $form_data['formId'], $this->parent_slug . '_form_scripting_php_after', true );
		if ( $this->network() ) {
			return $form_data;
		}
		if ( $phpAfter !== '' ) {
			eval( $phpAfter );
		}

		return $form_data;
	}

	/**
	 * Add scripting to JS Vars
	 *
	 * @param [type] $jsvars
	 *
	 * @return void
	 */
	public function add_scripting_to_js_vars( $jsvars ) {
		$calculator = get_post_meta( $jsvars['formId'], $this->parent_slug . '_form_calculator', true );
		$css        = get_post_meta( $jsvars['formId'], $this->parent_slug . '_form_scripting_css', true );
		$js         = get_post_meta( $jsvars['formId'], $this->parent_slug . '_form_scripting_js', true );


		$phpBefore = get_post_meta( $jsvars['formId'], $this->parent_slug . '_form_scripting_php_before', true );
		$phpAfter  = get_post_meta( $jsvars['formId'], $this->parent_slug . '_form_scripting_php_after', true );

		$jsvars['formScripting'] = [
			'calculator' => empty( $calculator ) ? '' : $calculator,
			'css'        => empty( $css ) ? '' : $css,
			'js'         => empty( $js ) ? '' : $js,
		];

		if ( $this->network() ) {
			$jsvars['formScripting']['phpBefore'] = esc_html__( '// This feature is disabled for security reasons', 'kaliforms' );
			$jsvars['formScripting']['phpAfter']  = esc_html__( '// This feature is disabled for security reasons', 'kaliforms' );

			return $jsvars;
		}

		$jsvars['formScripting']['phpBefore'] = empty( $phpBefore ) ? "" : "" . $phpBefore;
		$jsvars['formScripting']['phpAfter']  = empty( $phpAfter ) ? "" : "" . $phpAfter;

		return $jsvars;
	}

	/**
	 *  Add meta fields
	 *
	 * @param [type] $meta
	 *
	 * @return void
	 */
	public function add_meta_fields( $meta ) {
		$meta->add_fields(
			[ 'id' => 'form_calculator', 'sanitize' => 'KaliForms\Inc\Backend\Sanitizers_Helper::sanitize_code' ],
			[ 'id' => 'form_scripting_css', 'sanitize' => 'KaliForms\Inc\Backend\Sanitizers_Helper::sanitize_code' ],
			[ 'id' => 'form_scripting_js', 'sanitize' => 'KaliForms\Inc\Backend\Sanitizers_Helper::sanitize_code' ],
			[
				'id'       => 'form_scripting_php_before',
				'sanitize' => 'KaliForms\Inc\Backend\Sanitizers_Helper::sanitize_code_php'
			],
			[
				'id'       => 'form_scripting_php_after',
				'sanitize' => 'KaliForms\Inc\Backend\Sanitizers_Helper::sanitize_code_php'
			]
		);

		return $meta;
	}

	/**
	 * Adds calculations to the form
	 *
	 * @param [type] $args
	 *
	 * @return void
	 */
	public function add_calculation( $args ) {
		if ( defined( 'REST_REQUEST' ) ) {
			return $args;
		}
		$js = get_post_meta( $args['context']->form_info['form_id'], $this->parent_slug . '_form_calculator', true );
		if ( ! empty( $js ) ) {
			$js  = preg_replace( '/^\h*\v+/m', '', $js );
			$js  = explode( "\n", $js );
			$arr = [];
			foreach ( $js as $equation ) {
				if ( empty( $equation ) ) {
					continue;
				}
				if ( in_array( substr( trim( $equation ), 0, 1 ), [ '/', '#' ] ) ) {
					continue;
				}

				$equation = preg_replace( '/\s+\/\/[^\n]+/m', '', trim( $equation ) );
				$item     = explode( '=', $equation );
				if ( empty( array_filter( $item ) ) ) {
					continue;
				}
				if ( count( $item ) < 2 ) {
					continue;
				}
				$arr[ $item[0] ] = $item[1];
			}

			$content = 'var KaliFormsEquations' . $args['context']->form_info['form_id'] . ' = {';
			foreach ( $arr as $key => $value ) {
				$content .= '"' . $key . '"' . ':"' . $value . '",';
			}
			$content .= '};';
			wp_add_inline_script(
				'kaliforms-pro',
				$content,
				'after'
			);
		}

		return $args;
	}

	/**
	 * Adds custom css to the form
	 *
	 * @param [type] $args
	 *
	 * @return void
	 */
	public function add_custom_css( $args ) {
		if ( defined( 'REST_REQUEST' ) ) {
			return $args;
		}
		$css = get_post_meta( $args['context']->form_info['form_id'], $this->parent_slug . '_form_scripting_css', true );
		if ( ! empty( $css ) ) {
			echo "<style>\n" . $css . "\n</style>";
		}

		return $args;
	}

	/**
	 * Adds custom js to the form
	 *
	 * @param [type] $args
	 *
	 * @return void
	 */
	public function add_custom_js( $args ) {
		if ( defined( 'REST_REQUEST' ) ) {
			return $args;
		}
		$js = get_post_meta( $args['context']->form_info['form_id'], $this->parent_slug . '_form_scripting_js', true );
		if ( ! empty( $js ) ) {
			wp_add_inline_script(
				'kaliforms-pro',
				$js,
				'after'
			);
		}

		return $args;
	}

	/**
	 * @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'
		);
	}
}
