<?php

require_once dirname( __FILE__ ) . '/esign-forminator-form-settings-exception.php';

/**
 * Class Forminator_Addon_Esignature_Form_Settings
 * Handle how form settings displayed and saved
 *
 * @since 1.0 Esignature Addon
 */
class Forminator_Addon_Esignature_Form_Settings extends Forminator_Addon_Form_Settings_Abstract {

	/**
	 * @var Forminator_Addon_Esignature
	 * @since 1.0 Esignature Addon
	 */
	protected $addon;

	/**
	 * @var Forminator_Addon_Esignature_CustomField
	 * @since 1.7 Esignature Custom Fields
	 */
	protected $custom_fields;

	/**
	 * Forminator_Addon_Esignature_Form_Settings constructor.
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param Forminator_Addon_Abstract $addon
	 * @param                           $form_id
	 *
	 * @throws Forminator_Addon_Exception
	 */
	public function __construct( Forminator_Addon_Abstract $addon, $form_id ) {
		
		parent::__construct( $addon, $form_id );

		$this->_update_form_settings_error_message = __(
			'The update to your settings for this form failed, check the form input and try again.',
			'forminator'
		);
	}

	/**
	 * Esignature Form Settings wizard
	 *
	 * @since 1.0 Esignature Addon
	 * @return array
	 */
	public function module_settings_wizards() {
		
		// numerical array steps.
		return array(
			array(
				'callback'     => array( $this, 'esignature_settings_option' ),
				'is_completed' => array( $this, 'esignature_settings_option_is_completed' ),
			),
			
			
		);
	}

	/**
	 * Esignature Form Settings wizard
	 *
	 * @since 1.0 Esignature Addon
	 * @return array
	 */
	public function form_settings_wizards()
	{
		// numerical array steps.
		return array(
			array(
				'callback'     => array($this, 'esignature_settings_option'),
				'is_completed' => array($this, 'esignature_settings_option_is_completed'),
			),


		);
	}

	/**
	 * Setup Connection Name
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param $submitted_data
	 *
	 * @return array
	 */
	
	
	public function esignature_settings_option( $submitted_data ) {
		

		$template = forminator_addon_esign_dir() . 'admin/integration/views/esign-form-setting.php';

		$multi_id = $this->generate_multi_id();

		if ( isset( $submitted_data['multi_id'] ) ) {
			$multi_id = $submitted_data['multi_id'];
		}

	
		$form_settings_values = $this->settings_value();
		
		if ( isset( $form_settings_values ) ) {
			
			$multi_ids = array();
			foreach ( $form_settings_values as $key => $value ) {
				
				$multi_ids[] = array(
					'id'    => $key,				
				);
			}
			$multi_id = isset( $multi_ids[0]['id'] ) ? $multi_ids[0]['id'] : $multi_id;

			

		}


		

		$email_fields                 = array();
		$name_fields                 = array();
		$forminator_field_element_ids = array();
		foreach ( $this->form_fields as $form_field ) {
			// collect element ids.
			$forminator_field_element_ids[] = $form_field['element_id'];
			if ( 'email' === $form_field['type'] ) {
				$email_fields[] = $form_field;
			}
			if ( 'name' === $form_field['type'] || 'text' === $form_field['type'] || 'hidden' === $form_field['type'] ) {
				$name_fields[] = $form_field;
			}

		}

		$template_params = array(
			'fields_map'        => $this->get_multi_settings( $multi_id, 'fields_map', array()),
			'signing_logic'       => $this->get_multi_settings( $multi_id, 'signing_logic', '' ),
			'display_type'       => $this->get_multi_settings( $multi_id, 'display_type', '' ),
			'select_sad_doc'       => $this->get_multi_settings( $multi_id, 'select_sad_doc', '' ),
			'reminder_email_settings'       => $this->get_multi_settings( $multi_id, 'reminder_email_settings', '' ),
			'name_error' => '',
			'multi_id'   => $multi_id,
			'fields'            => array(),
			'form_fields'       => $name_fields,
			'email_fields'      => $email_fields,
		);

		unset( $submitted_data['multi_id'] );

		$fields                    = array(
			'signer_name' => __( 'Signer Name', 'esign' ),
			'email'     => __( 'Signer Email', 'emain' ),
			
		);
		$template_params['fields'] = $fields;

		$is_submit  = ! empty( $submitted_data );
		$has_errors = false;
		$is_close = false;
		if ( $is_submit ) {
			$fields_map = isset( $submitted_data['fields_map'] ) ? $submitted_data['fields_map'] : array();
			$signing_logic = isset( $submitted_data['signing_logic'] ) ? $submitted_data['signing_logic'] : '';
			$display_type = isset( $submitted_data['display_type'] ) ? $submitted_data['display_type'] : '';
			$select_sad_doc = isset( $submitted_data['select_sad_doc'] ) ? $submitted_data['select_sad_doc'] : '';
			$reminder_email_settings = isset( $submitted_data['reminder_email_settings'] ) ? $submitted_data['reminder_email_settings'] : '';
			$template_params['signing_logic'] = $signing_logic;
			$template_params['display_type'] = $display_type;
			$template_params['display_type'] = $display_type;
			$template_params['select_sad_doc'] = $select_sad_doc;
			$template_params['reminder_email_settings'] = $reminder_email_settings;


			try {


				if ( ! isset( $fields_map['signer_name'] ) || empty( $fields_map['signer_name'] ) ) {
					throw new Forminator_Addon_Esignature_Exception( __( 'Please Select Signer Name Form Field' ) );
				}

				if ( ! isset( $fields_map['email'] ) || empty( $fields_map['email'] ) || ! isset( $fields_map['signer_name'] ) || empty( $fields_map['signer_name'] ) ) {
					throw new Forminator_Addon_Esignature_Exception( __( 'Please Select Signer Email Form Field' ) );
				}
				

				if ( empty( $signing_logic ) ) {
					throw new Forminator_Addon_Esignature_Exception( __( 'Please Select Signing Logic ' ) );
				}

				if ( empty( $select_sad_doc ) ) {
					throw new Forminator_Addon_Esignature_Exception( __( 'Please Select sad document ' ) );
				}

				$enabled_reminder = isset($submitted_data['esign_enabled_reminder']) ? $submitted_data['esign_enabled_reminder'] : '';
				
				if( $enabled_reminder  == 'enabled'){
					
					$first_reminder_email = $reminder_email_settings['first_reminder_email'];
					$second_reminder_email = $reminder_email_settings['second_reminder_email'];
					$expire_reminder = $reminder_email_settings['expire_reminder'];					

					if ( empty( $first_reminder_email ) || strpos($first_reminder_email, '-') !== false || $first_reminder_email == '0') {
						throw new Forminator_Addon_Esignature_Exception( __( 'Please input at least 1 for First Reminder' ) );
					}elseif ( empty( $second_reminder_email ) || strpos($second_reminder_email, '-') !== false ||  $second_reminder_email == '0') {
						throw new Forminator_Addon_Esignature_Exception( __( 'Please input at least 1 for Second Reminder' ) );
					}elseif ( empty($expire_reminder) || strpos($expire_reminder, '-') !== false || $expire_reminder == '0') {
						throw new Forminator_Addon_Esignature_Exception( __( 'Please input at least 1 for Last Reminder' ) );
					}
					if (intval($second_reminder_email) <= intval($first_reminder_email)){
						throw new Forminator_Addon_Esignature_Exception( __( 'Second reminder should be Greater than First reminder' ) );
					}
					
					if (intval($expire_reminder) <= intval($second_reminder_email)){
						throw new Forminator_Addon_Esignature_Exception( __( 'Last reminder should be Greater than Second reminder' ) );
					}	
				
				}


				update_post_meta($this->formId(),'esign-forminator-meta-key',$this->get_settings_meta_key());

				$data= array(
					'fields_map'       => $fields_map,
					'signer_info'       => $fields_map,
					'signing_logic'       => $signing_logic,
					'display_type'       => $display_type,
					'select_sad_doc'       => $select_sad_doc,
					'reminder_email_settings' => $reminder_email_settings,
				);
				
				$this->save_settings( $multi_id, $data );

                                  $notification = array(
											'type' => 'success',
											'text' => '<strong>' . $this->addon->get_title() . '</strong> ' . __( 'is activated successfully.' ),
										);
				$is_close = true;

			} catch ( Forminator_Addon_Esignature_Exception $e ) {
				
				$template_params['error_message'] = $e->getMessage();
				
				$has_errors                    = true;
				$is_close = false;
			}
		}

		$buttons = array();
		if ( $this->esignature_settings_option_is_completed( array( 'multi_id' => $multi_id ) ) ) {
			$buttons['disconnect']['markup'] = Forminator_Addon_Abstract::get_button_markup(
				esc_html__( 'Deactivate', 'forminator' ),
				'sui-button-ghost sui-tooltip sui-tooltip-top-center forminator-addon-form-disconnect',
				esc_html__( 'Deactivate this Esignature Integration from this Form.', 'forminator' )
			);
                        
                        $buttons['next']['markup'] = '<div class="sui-actions-right">' .
									Forminator_Addon_Abstract::get_button_markup( esc_html__( 'Update', 'forminator' ), 'forminator-addon-next sui-button-blue' ) .
									'</div>';
                        
                       
		} else{
                    $buttons['next']['markup'] = '<div class="sui-actions-right">' .
									Forminator_Addon_Abstract::get_button_markup( esc_html__( 'Activate', 'forminator' ), 'forminator-addon-next sui-button-blue' ) .
									'</div>';
                }

		

		return array(
			'html'       => Forminator_Addon_Abstract::get_template( $template, $template_params ),
			'buttons'    => $buttons,
			'redirect'   => false,
			'has_errors' => $has_errors,
            'notification' => array(),
			'is_close'     => $is_close,
		);
	}

	private function formId(){
		// check if form id is set
		if(isset($this->form_id)){
			return $this->form_id;
		}

		if(isset($this->module_id))
		{
			return $this->module_id;
		}
		return '';
	}

	private function settings_value(){
		if(method_exists($this,'get_settings_values')){
			return $this->get_settings_values();
		} else {
			return $this->get_form_settings_values();
		}
		
	}

	private function get_multi_settings($multi_id,$type,$default){
		if(method_exists($this, 'get_multi_id_form_settings_value')){
			return $this->get_multi_id_form_settings_value($multi_id, $type,$default);
		} else {
			return $this->get_multi_id_settings($multi_id, $type, $default);
		}
	}

	private function save_settings($multi_id,$data){
		if(method_exists($this, 'save_multi_id_setting_values')){
			return $this->save_multi_id_setting_values($multi_id,$data);
		} else {
			return $this->save_multi_id_form_setting_values($multi_id,$data);
		}
	
	}

	/**
	 * Check if pick name step completed
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param $submitted_data
	 *
	 * @return bool
	 */
	public function esignature_settings_option_is_completed( $submitted_data ) {
		
		/*
		$multi_id = '';
		
		$form_settings_values = $this->get_form_settings_values();
		
		if ( isset( $form_settings_values ) ) {
			
			$multi_ids = array();
			foreach ( $form_settings_values as $key => $value ) {
				
				$multi_ids[] = array(
					'id'    => $key,				
				);
			}
			$multi_id = $multi_ids['id'];

		}

		if ( empty( $multi_id )) {
			return false;
		}

		*/

		

		return true;
	}

	
	/**
	 * Check if setup options completed
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param $submitted_data
	 *
	 * @return bool
	 */
	public function setup_options_is_completed( $submitted_data ) {
		// all settings here are optional, so it can be marked as completed.
		return true;
	}

	/**
	 * Generate multi id for multiple connection
	 *
	 * @since 1.0 Esignature Addon
	 * @return string
	 */
	public function generate_multi_id() {
		return uniqid( 'esignature_', true );
	}

	

	/**
	 * Override how multi connection displayed
	 *
	 * @since 1.0 Esignature Addon
	 * @return array
	 */
	public function get_multi_ids():array {
		$multi_ids            = array();
		$form_settings_values = $this->get_form_settings_values();
		foreach ( $form_settings_values as $key => $value ) {
			// apply some sorting if applicable.
			$multi_ids[] = array(
				'id'    => $key,
				// use name that was added by user on creating connection.
				'label' => isset( $value['name'] ) ? $value['name'] : $key,
			);
		}

		/**
		 * Filter labels of multi_id on integrations tab
		 *
		 * @since 1.2
		 *
		 * @param array $multi_ids
		 * @param array $form_settings_values
		 */
		$multi_ids = apply_filters( 'forminator_addon_Esignature_multi_id_labels', $multi_ids, $form_settings_values );

		return $multi_ids;
	}

	/**
	 * Disconnect a connection from current form
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param array $submitted_data
	 */
	public function disconnect_form( $submitted_data ) {
		$this->save_form_settings_values( array() );
		delete_post_meta($this->form_id,'esign-forminator-meta-key');
	}

	/**
	 * Check if multi_id form settings values completed
	 *
	 * @since 1.0 Active Campaign Added
	 *
	 * @param $multi_id
	 *
	 * @return bool
	 */
	public function is_multi_form_settings_complete( $multi_id ) {
		$data = array( 'multi_id' => $multi_id );

		if ( ! $this->esignature_settings_option_is_completed( $data ) ) {
			return false;
		}

		return true;
	}
}
