<?php
/**
 * Error Popup Template Class
 *
 * This class handles all functionality related to the error 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\Helper\MoUtility;
use WCSMSOTP\Objects\MoITemplate;
use WCSMSOTP\Objects\Template;
use WCSMSOTP\Traits\Instance;

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

		use Instance;

		/**
		 * Constructor.
		 *
		 * Declares variables of the class on initialization.
		 */
		protected function __construct() {
			$this->key                = 'ERROR';
			$this->template_editor_id = 'customEmailMsgEditor4';
			$this->required_tags      = array_diff( $this->required_tags, array( '{{FORM_ID}}', '{{REQUIRED_FIELDS}}' ) );
			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 for public release.
		 * @return array
		 */
		public function get_defaults( $templates ) {
			if ( ! is_array( $templates ) ) {
				$templates = array();
			}
			$template_url = MOV_WC_URL . 'includes/html/error.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;
			$from_both_string = $from_both ? 'true' : 'false';
			$otp_type         = sanitize_text_field( $otp_type );
			$message          = sanitize_text_field( $message );

			$required_scripts = $this->getRequiredFormsSkeleton( $otp_type, $from_both_string );
			$jquery_url       = ! empty( $this->jquery_url ) ? esc_url( $this->jquery_url ) : '';
			$css_url          = defined( 'MOV_WC_CSS_URL' ) ? esc_url( MOV_WC_CSS_URL ) : '';
			$template         = str_replace( '{{JQUERY}}', $jquery_url, $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( '{{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 );

			return $template;
		}

		/**
		 * Get required forms skeleton HTML.
		 *
		 * This function is used to replace the {{REQUIRED_FORMS_SCRIPTS}} in the template
		 * with the appropriate scripts and forms. These forms and scripts are required
		 * for the popup to work.
		 *
		 * @param string $otp_type  The otp type invoked.
		 * @param string $from_both  Does user have the option to choose between email and sms verification.
		 * @return string
		 */
		private function getRequiredFormsSkeleton( $otp_type, $from_both ) {
			$required_fields = '<form name="f" method="post" action="" id="validation_goBack_form">
				<input id="validation_goBack" name="option" value="' . esc_attr( 'validation_goBack' ) . '" type="hidden"/>
			</form>{{SCRIPTS}}';
			$required_fields = str_replace( '{{SCRIPTS}}', $this->getRequiredScripts(), $required_fields );
			return $required_fields;
		}

		/**
		 * 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 void
		 */
		private function getRequiredScripts() {
			/*
			* Load a small, dedicated script for the Error popup.
			* This script only defines the global `mo_validation_goback()`
			* function used by the template, without touching the default
			* OTP popup behaviour.
			*/
			$script_handle = 'mo-error-popup';

			if ( ! wp_script_is( $script_handle, 'registered' ) ) {
				wp_register_script(
					$script_handle,
					MOV_WC_URL . 'includes/js/mo-error-popup.js',
					array(),
					MOV_WC_VERSION,
					false
				);
			}

			wp_print_scripts( $script_handle );
		}
	}
}
