<?php

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

/**
 * Class Forminator_Addon_Esignature
 * Esignature Addon Main Class
 *
 * @since 1.0 Esignature Addon
 */
 class ForminatorAddon_Esignature extends Forminator_Addon_Abstract {

	/**
	 * @var self|null
	 */
	private static $_instance = null;

	protected $_slug                   = 'esignature';
	protected $_version                = '0.0.1';
	protected $_min_forminator_version = '1.1';
	protected $_short_title            = 'WP E-Signature';
	protected $_title                  = 'WP E-Signature';
	protected $_url                    = 'https://www.approveme.com/';
	protected $_full_path              = __FILE__;
	protected $_position               = 8;

	protected $_form_settings = 'Forminator_Addon_Esignature_Form_Settings';
	protected $_form_hooks    = 'Forminator_Addon_Esignature_Form_Hooks';




	/**
	 * Forminator_Addon_Esignature constructor.
	 *
	 * @since 1.0 Esignature Addon
	 */

	 
	public function __construct() {
		// late init to allow translation.
		$this->_description                = __( 'Get awesome by your form.', 'forminator' );
		$this->_activation_error_message   = __( 'Sorry but we failed to activate Esignature Integration, don\'t hesitate to contact us', 'forminator' );
		$this->_deactivation_error_message = __( 'Sorry but we failed to deactivate Esignature Integration, please try again', 'forminator' );

		$this->_update_settings_error_message = __(
			'Sorry, we failed to update settings, please check your form and try again',
			'forminator'
		);

		$this->_icon     = ESIGN_FORMINATOR_ASSETS_DIR_URI . '/images/icon.png';
		$this->_icon_x2  = ESIGN_FORMINATOR_ASSETS_DIR_URI . '/images/esigicon@2x.png';
		$this->_image    = ESIGN_FORMINATOR_ASSETS_DIR_URI . '/images/icon.png';
		$this->_image_x2 = ESIGN_FORMINATOR_ASSETS_DIR_URI . '/images/esigicon@2x.png';

		
	}

	/**
	 * Get path to assets folder
	 *
	 * @return string
	 */
	public function assets_path(): string
	{
		return ESIGN_FORMINATOR_ASSETS_DIR_URI . '/images/';
	}

	/**
	 * Get Instance
	 *
	 * @since 1.0 Esignature Addon
	 * @return self|null
	 */
	public static function get_instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}


		/**
	 * Override on is_connected
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @return bool
	 */
	public function is_connected() {

		
		try {
			
			// check if its active.
		/*	if ( ! $this->is_active() ) {
				
				throw new Forminator_Addon_Esignature_Exception( __( 'Esignature is not active', 'forminator' ) );
			} */
		 
			// if user completed Esign Setup.
			$is_connected = $this->isEsignSetupCompleted();

		} catch ( Forminator_Addon_Esignature_Exception $e ) {
			$is_connected = false;
		}
		
		/**
		 * Filter connected status of Esignature
		 *
		 * @since 1.2
		 *
		 * @param bool $is_connected
		 */
		$is_connected = apply_filters( 'forminator_addon_esignature_is_connected', $is_connected );

		return $is_connected;



	}

	/**
	 * Check if Esignature is connected with current form
	 *
	 * @since 1.0 Esignature Addon
	 *
	 * @param $form_id
	 *
	 * @return bool
	 */
	public function is_form_connected( $form_id ) {

			try {
			$form_settings_instance = null;
			if ( ! $this->is_connected() ) {
				throw new Forminator_Addon_Esignature_Exception( __( ' Esignature is not connected', 'forminator' ) );
			}

			$form_settings_instance = $this->get_addon_settings( $form_id, 'form' );
			if ( ! $form_settings_instance instanceof Forminator_Addon_Esignature_Form_Settings ) {
				throw new Forminator_Addon_Activecampaign_Exception( __( 'Invalid Form Settings of Esignature', 'forminator' ) );
			}

			// Mark as active when there is at least one active connection.
			if ( false === $form_settings_instance->find_one_active_connection() ) {
				throw new Forminator_Addon_Esignature_Exception( __( 'No active Esignature connection found in this form', 'forminator' ) );
			}

			$is_form_connected = true;

		} catch ( Forminator_Addon_Esignature_Exception $e ) {
			$is_form_connected = false;
			forminator_addon_maybe_log( __METHOD__, $e->getMessage() );
		}

		/**
		 * Filter connected status of ActiveCampaign with the form
		 *
		 * @since 1.2
		 *
		 * @param bool                                               $is_form_connected
		 * @param int                                                $form_id                Current Form ID.
		 * @param Forminator_Addon_Activecampaign_Form_Settings|null $form_settings_instance Instance of form settings, or null when unavailable.
		 *
		 */
		$is_form_connected = apply_filters( 'forminator_addon_esignature_is_form_connected', $is_form_connected, $form_id, $form_settings_instance );

		return $is_form_connected;
		
	}
        
     

	/**
	 * Setting wizard of WP Esignature
	 *
	 * @since 1.0 WP Esignature Addon
	 * @return array
	 */
	public function settings_wizards() {
		return array(
			array(
				'callback'     => array( $this, 'setupEsign' ),
				'is_completed' => array( $this, 'isEsignSetupCompleted' ),
			),
		);
	}

	/**
	 * Setup Esignature Wizard
	 *
	 * @since 1.0 WP Esignature Addon
	 *
	 * @param     $submitted_data
	 * @param int $form_id
	 *
	 * @return array
	 */




	public function setupEsign( $submitted_data, $form_id = 0 ) {

		$settings_values  = $this->get_settings_values();
		$template         = forminator_addon_esign_dir() . 'admin/integration/views/setup-esign-integration.php';
		$template_success = forminator_addon_esign_dir() . 'admin/integration/views/setup-esign-integration-success.php';
		$template_params  = array(
			'identifier'    => '',
			'esign_forminator_enable' => '',
			'error_message' => '',
		);
		$has_errors       = false;
		$show_success     = false;
		$is_submit        = ! empty( $submitted_data );

		foreach ( $template_params as $key => $value ) {
			if ( isset( $submitted_data[ $key ] ) ) {
				$template_params[ $key ] = $submitted_data[ $key ];
			} elseif ( isset( $settings_values[ $key ] ) ) {
				$template_params[ $key ] = $settings_values[ $key ];
			}
		}

		if ( $is_submit ) {
			
			$esign_enable = isset( $submitted_data['esign_forminator_enable'] ) ? $submitted_data['esign_forminator_enable'] : '';
			$identifier = isset( $submitted_data['identifier'] ) ? $submitted_data['identifier'] : '';

			

			if ( !empty($esign_enable)) {
				// validate api.
				try {

					

					if ( ! forminator_addon_is_active( $this->_slug ) ) {
						$activated = Forminator_Addon_Loader::get_instance()->activate_addon( $this->_slug );
						if ( ! $activated ) {
							throw new Forminator_Addon_Esignature_Exception( Forminator_Addon_Loader::get_instance()->get_last_error_message() );
						}
					}

					$settings_values = array(
						'esign_forminator_enable' => $esign_enable,
						'identifier' => $identifier,
					);
					$this->saveSettingsValues( $settings_values );

					// no form_id its on global settings.
					if ( empty( $form_id ) ) {
						$show_success = true;
					}
				} catch ( Forminator_Addon_Esignature_Exception $e ) {
					$template_params['error_message'] = $e->getMessage();
					$has_errors                       = true;
				}
			}
		}

		if ( $show_success ) {
			$template = $template_success;
		}

		$buttons = array();

		if ( $show_success ) {
			$buttons['close'] = array(
				'markup' => self::get_button_markup( esc_html__( 'Close', 'forminator' ), 'sui-button-ghost forminator-addon-close forminator-integration-popup__close' ),
			);
                        
                        $html  = '<div class="forminator-integration-popup__header">';
						/* translators: ... */
						$html .= '<h3 id="dialogTitle2" class="sui-box-title sui-lg" style="overflow: initial; text-overflow: none; white-space: normal;">' . sprintf( __( 'WP E-Signature Added', 'esign' ), ) . '</h3>';
					$html .= '</div>';
					$html .= '<p class="sui-description" style="text-align: center;">' . __( 'You can now go to your forms and assign them to this integration.' ) . '</p>';

					return array(
						'html'         => $html,
						'buttons'      => array(
							'close' => array(
								'markup' => self::get_button_markup( esc_html__( 'Close', 'esign' ), 'forminator-addon-close forminator-integration-popup__close' ),
							),
						),
						'redirect'     => false,
						'has_errors'   => false,
						'notification' => array(
							'type' => 'success',
							'text' => '<strong>' . $this->get_title() . '</strong> ' . __( 'is connected successfully.' ),
						),
					);
                        
                        
                        
		} else {
			if ( $this->is_connected() ) {
				$buttons['disconnect'] = array(
					'markup' => self::get_button_markup( esc_html__( 'Disconnect', 'esign' ), 'sui-button-ghost forminator-addon-disconnect' ),
				);
				$buttons['submit']     = array(
					'markup' => '<div class="sui-actions-right">' .
								self::get_button_markup( esc_html__( 'Save', 'esign' ), 'forminator-addon-connect' ) .
								'</div>',
				);
			} else {
				$buttons['submit'] = array(
					'markup' => '<div class="sui-actions-right">' .
								self::get_button_markup( esc_html__( 'CONNECT', 'esign' ), 'forminator-addon-connect' ) .
								'</div>',
				);
			}
		}

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

	public function isEsignSetupCompleted() {

		$setting_values = $this->get_settings_values();
		
		// check esign_forminator_enable.
		return isset($setting_values['esign_forminator_enable'] );
		
	}

	final public function saveSettingsValues( $values ) {
		
		$addon_slug = $this->get_slug();
		$all_values = $this->get_all_settings_values();

		/**
		 * Filter settings values of addon to be saved
		 *
		 * `$addon_slug` is current slug of addon that will on save.
		 * Example : `malchimp`, `zapier`, `etc`
		 *
		 * @since 1.1
		 *
		 * @param mixed $values
		 */
                
		$values = apply_filters( 'forminator_addon_' . $addon_slug . '_save_settings_values', $values );

		if ( empty( $this->multi_global_id ) ) {
			$this->multi_global_id = uniqid( '', true );
		}

		if ( $this->is_multi_global ) {
			$all_values[ $this->multi_global_id ] = forminator_sanitize_array_field( $values );
		} else {
			$all_values = array(
				$this->multi_global_id => forminator_sanitize_array_field( $values ),
			);
		}

		update_option( $this->getSettingsOptionsName(), $all_values );
	}

	final public function getSettingsOptionsName() {
            
		$addon_slug            = $this->get_slug();
		$addon                 = $this;
		$settings_options_name = 'forminator_addon_' . $this->get_slug() . '_settings';

		/**
		 * Filter wp options name for saving addon settings
		 *
		 * @since 1.1
		 *
		 * @param string                    $settings_options_name
		 * @param Forminator_Addon_Abstract $addon Addon instance.
		 */
                
		$settings_options_name = apply_filters( 'forminator_addon_' . $addon_slug . '_settings_options_name', $settings_options_name, $addon);
                return $settings_options_name;
                
	}
        
        /**
	 * Override settings available,
	 *
	 * @since 1.0 HubSpot Addon
	 * @return bool
	 */
	public function is_settings_available() {
		return true;
	}

	


}
