<?php
/**
 * External Popup Template Class
 *
 * This class handles all functionality related to the external popup template.
 * It extends the Template class and implements the MoITemplate interface.
 *
 * @package miniorange-sms-order-notification-otp-verification/helper/templates
 */

namespace WCSMSOTP\Helper\Templates;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use WCSMSOTP\Objects\MoITemplate;
use WCSMSOTP\Objects\Template;
use WCSMSOTP\Traits\Instance;
use WCSMSOTP\Helper\MoUtility;

/**
 * External Popup Template Class
 *
 * This class handles all functionality related to the external popup template.
 * It extends the Template class and implements the MoITemplate interface.
 */
if ( ! class_exists( 'ExternalPopup' ) ) {
	/**
	 * External Popup Template Class
	 *
	 * This class handles all functionality related to the external popup template.
	 * It extends the Template class and implements the MoITemplate interface.
	 */
	class ExternalPopup extends Template implements MoITemplate {

		use Instance;

		/**
		 * Constructor.
		 *
		 * Declares variables of the class on initialization.
		 */
		protected function __construct() {
			$this->key                = 'EXTERNAL';
			$this->template_editor_id = 'customEmailMsgEditor3';
			$this->required_tags      = array_merge(
				$this->required_tags,
				array(
					'{{PHONE_FIELD_NAME}}',
					'{{SEND_OTP_BTN_ID}}',
					'{{VERIFICATION_FIELD_NAME}}',
					'{{VALIDATE_BTN_ID}}',
					'{{SEND_OTP_BTN_ID}}',
					'{{VERIFY_CODE_BOX}}',
				)
			);
			parent::__construct();
		}

		/**
		 * Get default template HTML.
		 *
		 * This function initializes the default HTML of the PopUp Template
		 * to be used by the plugin. This function is called only during
		 * plugin activation or when user resets the templates. In both
		 * cases the plugin initializes the template to the default value
		 * that the plugin ships with.
		 *
		 * @param array $templates The template array to be populated.
		 * @note The html content has been minified. Check helper/templates/templates.html
		 * @return array
		 */
		public function get_defaults( $templates ) {
			if ( ! is_array( $templates ) ) {
				$templates = array();
			}
			$template_url = MOV_WC_URL . 'includes/html/externalphone.min.html';
			if ( ! is_string( $template_url ) || empty( $template_url ) ) {
				return $templates;
			}
			$pop_up_templates_request = wp_remote_get( esc_url_raw( $template_url ) );

			if ( is_wp_error( $pop_up_templates_request ) ) {
				return $templates;
			}
			$response_code = wp_remote_retrieve_response_code( $pop_up_templates_request );
			if ( 200 !== $response_code ) {
				return $templates;
			}
			$template_body = wp_remote_retrieve_body( $pop_up_templates_request );
			if ( ! empty( $template_body ) && is_string( $template_body ) ) {
				$templates[ $this->get_template_key() ] = $template_body;
			}
			return $templates;
		}
		/**
		 * Parse template and replace tags with appropriate content.
		 *
		 * This function is used to parse the template and replace the
		 * tags with the appropriate content. Some of the contents are
		 * not shown if the admin/user is just previewing the pop-up.
		 *
		 * @param string $template The HTML Template.
		 * @param string $message  The message to be shown in the popup.
		 * @param string $otp_type The otp type invoked.
		 * @param bool   $from_both Does user have the option to choose between email and sms verification.
		 * @return string
		 */
		public function parse( $template, $message, $otp_type, $from_both ) {
			$from_both = (bool) $from_both;
			$otp_type  = sanitize_text_field( $otp_type );
			$message   = sanitize_text_field( $message );

			$required_scripts   = $this->getRequiredScripts();
			$extra_post_data    = $this->preview ? '' : mowc_extra_wc_post_data();
			$extra_form_fields  = '<input type="hidden" name="mo_external_popup_option" value="' . esc_attr( 'mo_ajax_form_validate' ) . '" />';
			$extra_form_fields .= '<input type="hidden" id="mopopup_wpnonce" name="mopopup_wpnonce" value="' . esc_attr( wp_create_nonce( $this->nonce ) ) . '"/>';

			$jquery_url = ! empty( $this->jquery_url ) ? esc_url( $this->jquery_url ) : '';
			$css_url    = defined( 'MOV_WC_CSS_URL' ) ? esc_url( MOV_WC_CSS_URL ) : '';
			$loader_img = ! empty( $this->img ) ? wp_kses_post( $this->img ) : '';

			$template  = str_replace( '{{JQUERY}}', $jquery_url, $template );
			$template  = str_replace( '{{FORM_ID}}', esc_attr( 'mo_validate_form' ), $template );
			$template  = str_replace( '{{GO_BACK_ACTION_CALL}}', esc_js( 'mo_validation_goback();' ), $template );
			$template  = str_replace( '{{MO_CSS_URL}}', $css_url, $template );
			$template  = str_replace( '{{OTP_MESSAGE_BOX}}', esc_attr( 'mo_message' ), $template );
			$template  = str_replace( '{{REQUIRED_FORMS_SCRIPTS}}', wp_kses( $required_scripts, MoUtility::mowc_allow_html_array() ), $template );
			$template  = str_replace( '{{HEADER}}', esc_html( mowc_( 'Validate OTP (One Time Passcode)' ) ), $template );
			$template  = str_replace( '{{GO_BACK}}', wp_kses_post( mowc_( '&larr; Go Back' ) ), $template );
			$template  = str_replace( '{{MESSAGE}}', esc_html( mowc_( $message ) ), $template );
			$template  = str_replace( '{{REQUIRED_FIELDS}}', $extra_form_fields, $template );
			$template  = str_replace( '{{PHONE_FIELD_NAME}}', esc_attr( 'mo_phone_number' ), $template );
			$template  = str_replace( '{{OTP_FIELD_TITLE}}', esc_html( mowc_( 'Enter Code' ) ), $template );
			$template  = str_replace( '{{VERIFY_CODE_BOX}}', esc_attr( 'mowc_validate_otp' ), $template );
			$template  = str_replace( '{{VERIFICATION_FIELD_NAME}}', esc_attr( 'mo_otp_token' ), $template );
			$template  = str_replace( '{{VALIDATE_BTN_ID}}', esc_attr( 'validate_otp' ), $template );
			$template  = str_replace( '{{VALIDATE_BUTTON_TEXT}}', esc_html( mowc_( 'Validate' ) ), $template );
			$template  = str_replace( '{{SEND_OTP_TEXT}}', esc_html( mowc_( 'Send OTP' ) ), $template );
			$template  = str_replace( '{{SEND_OTP_BTN_ID}}', esc_attr( 'send_otp' ), $template );
			$template  = str_replace( '{{EXTRA_POST_DATA}}', wp_kses_post( $extra_post_data ), $template );
			$template .= $this->getExtraFormFields();
			return $template;
		}

		/**
		 * Get extra form fields HTML.
		 *
		 * Returns necessary form elements for the template.
		 * Includes mostly hidden forms/fields.
		 *
		 * @return string
		 */
		private function getExtraFormFields() {
			$ffields = '<form name="f" method="post" action="" id="validation_goBack_form">
                            <input id="validation_goBack" name="option" value="' . esc_attr( 'validation_goBack' ) . '" type="hidden"/>
                        </form>';
			return $ffields;
		}

		/**
		 * Get required scripts HTML.
		 *
		 * This function is used to replace the {{SCRIPTS}} in the template
		 * with the appropriate scripts. These scripts are required
		 * for the popup to work. Scripts are not added if the form is in
		 * preview mode.
		 *
		 * @return string
		 */
		private function getRequiredScripts() {
			$scripts = '<style>.mo_customer_validation-modal{display:block!important}</style>';
			if ( ! $this->preview ) {
				do_action( 'mowc_include_js' );
				wp_register_script( 'moExternalPopUps', MOV_WC_URL . 'includes/js/moExternalPopUp.js', array( 'jquery' ), MOV_WC_VERSION, false );
				$current_url = MoUtility::current_page_url();
				if ( empty( $current_url ) ) {
					$current_url = function_exists( 'wp_login_url' ) ? wp_login_url() : home_url();
				}

				wp_localize_script(
					'moExternalPopUps',
					'moExternalPopUps',
					array(
						'secure_site_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
						'resend_otp_text' => esc_js( mowc_( 'Resend OTP' ) ),
						'home_url'        => esc_url( home_url() ),
						'login_page_url'  => esc_url( $current_url ),
					)
				);
				wp_print_scripts( 'moExternalPopUps' );
			} else {
				// Register and enqueue preview script for preview mode.
				$script_handle = 'mo-popup-preview';
				if ( ! wp_script_is( $script_handle, 'registered' ) ) {
					wp_register_script(
						$script_handle,
						MOV_WC_URL . 'includes/js/mo-popup-preview.js',
						array( 'jquery' ),
						MOV_WC_VERSION,
						false
					);
				}

				// Localize script with preview mode flag.
				wp_localize_script(
					$script_handle,
					'moExternalPreview',
					array(
						'isPreview' => true,
					)
				);

				// Print script immediately since this is called during HTML output.
				wp_print_scripts( $script_handle );
			}
			return $scripts;
		}
	}
}
