<?php
/**
 * MiniOrange Gateway Class
 *
 * This class implements MiniOrange Gateway Plan specific functions.
 * It handles OTP sending, validation, notifications, and gateway configuration.
 *
 * @package miniorange-sms-order-notification-otp-verification/helper
 * @since   1.0.0
 */

namespace WCSMSOTP\Helper;

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

use WCSMSOTP\Notifications\WcSMSNotification\WooCommerceSmsNotification;
use WCSMSOTP\Notifications\FormSMSNotification\FormSubmissionSMSNotification;
use WCSMSOTP\Objects\BaseAddOnHandler;
use WCSMSOTP\Objects\IGatewayFunctions;
use WCSMSOTP\Objects\NotificationSettings;
use WCSMSOTP\Traits\Instance;

/**
 * MiniOrange Gateway Class
 *
 * This class implements MiniOrange Gateway Plan specific functions.
 * It handles OTP sending, validation, notifications, and gateway configuration.
 */
if ( ! class_exists( 'MiniOrangeGateway' ) ) {
	/**
	 * MiniOrange Gateway Class
	 *
	 * This class implements MiniOrange Gateway Plan specific functions.
	 * It handles OTP sending, validation, notifications, and gateway configuration.
	 */
	class MiniOrangeGateway implements IGatewayFunctions {

		use Instance;

		/**
		 * Application name used in API calls.
		 *
		 * @var string
		 */
		private $application_name = 'wp_otp_verification';


		/**
		 * Register add-ons.
		 *
		 * Initializes and registers all add-ons for the gateway.
		 *
		 * @return void
		 */
		public function register_addons() {
			if ( class_exists( 'WCSMSOTP\Notifications\WcSMSNotification\WooCommerceSmsNotification' ) ) {
				WooCommerceSmsNotification::instance();
			}
			if ( class_exists( 'WCSMSOTP\Notifications\FormSMSNotification\FormSubmissionSMSNotification' ) ) {
				FormSubmissionSMSNotification::instance();
			}
		}
		/**
		 * Hourly sync.
		 *
		 * Performs hourly synchronization with the gateway server.
		 *
		 * @return void
		 */
		public function hourly_sync() {
			$customer_key = get_mo_wc_option( 'admin_customer_key' );
			$api_key      = get_mo_wc_option( 'admin_api_key' );
			if ( ! empty( $customer_key ) && ! empty( $api_key ) && is_string( $customer_key ) && is_string( $api_key ) ) {
				MoUtility::handle_mo_check_ln( false, $customer_key, $api_key );
			}
		}

		/**
		 * Flush cache.
		 *
		 * Flushes the gateway cache.
		 *
		 * @return void
		 */
		public function flush_cache() {
			// Cache flushing implementation if needed.
		}

		/**
		 * Validate license key.
		 *
		 * Validates the license key with the gateway server.
		 *
		 * @param array $post POST data array.
		 * @return void
		 */
		public function vlk( $post ) {
			// License validation implementation if needed.
		}

		/**
		 * Check license validity.
		 *
		 * Checks if the license is valid.
		 *
		 * @return bool True if license is valid, false otherwise.
		 */
		public function mclv() {
			return true;
		}

		/**
		 * Check if gateway is configured.
		 *
		 * Checks if the gateway is properly configured.
		 *
		 * @return bool True if gateway is configured, false otherwise.
		 */
		public function is_gateway_config() {
			return true;
		}

		/**
		 * Check if MiniOrange Gateway.
		 *
		 * Checks if the current gateway is MiniOrange Gateway.
		 *
		 * @return bool True if MiniOrange Gateway, false otherwise.
		 */
		public function is_mg() {
			return $this->mclv();
		}

		/**
		 * Get application name.
		 *
		 * Returns the application name for the gateway.
		 *
		 * @return string Application name.
		 */
		public function get_application_name() {
			return $this->application_name;
		}

		/**
		 * Custom WordPress mail from name.
		 *
		 * Customizes the from name for WordPress emails.
		 *
		 * @param string $original_email_from Email of user.
		 * @return string Email from name.
		 */
		public function custom_wp_mail_from_name( $original_email_from ) {
			if ( ! is_string( $original_email_from ) ) {
				return '';
			}
			return sanitize_email( $original_email_from );
		}

		/**
		 * Configure SMS template.
		 *
		 * Configures the SMS template settings.
		 *
		 * @param array $posted POST values.
		 * @return void
		 */
		public function mo_configure_sms_template( $posted ) {
			// SMS template configuration implementation if needed.
		}

		/**
		 * Configure email template.
		 *
		 * Configures the email template settings.
		 *
		 * @param array $posted POST values.
		 * @return void
		 */
		public function mo_configure_email_template( $posted ) {
			// Email template configuration implementation if needed.
		}



		/**
		 * Send OTP token.
		 *
		 * Calls the server to send OTP to the user's phone or email.
		 *
		 * @param string $auth_type OTP type - EMAIL or SMS.
		 * @param string $email     Email address of the user.
		 * @param string $phone     Phone number of the user.
		 * @return array Response array from the gateway.
		 */
		public function mo_send_otp_token( $auth_type, $email, $phone ) {
			if ( ! is_string( $auth_type ) || ! is_string( $email ) || ! is_string( $phone ) ) {
				return array(
					'status'  => 'ERROR',
					'message' => 'Invalid parameters',
				);
			}
			$auth_type = sanitize_text_field( $auth_type );
			$email     = sanitize_email( $email );
			$phone     = sanitize_text_field( $phone );
			if ( defined( 'MO_WC_TEST_MODE' ) && MO_WC_TEST_MODE ) {
				return array(
					'status' => 'SUCCESS',
					'txId'   => MoUtility::rand(),
				);
			} else {
				$content = MocURLCall::mo_send_otp_token( $auth_type, $email, $phone );
				$decoded = json_decode( $content, true );
				return $decoded;
			}
		}

		/**
		 * Send notification.
		 *
		 * Calls server APIs to send email or SMS message to the user.
		 *
		 * @param NotificationSettings $settings Notification settings object.
		 * @return string Response from the gateway.
		 */
		public function mo_send_notif( NotificationSettings $settings ) {
			if ( ! is_object( $settings ) || ! ( $settings instanceof NotificationSettings ) ) {
				return '';
			}

			$url        = '';
			$send_email = isset( $settings->send_email ) ? (bool) $settings->send_email : false;
			if ( class_exists( 'MoConstants' ) ) {
				$hostname = MoConstants::HOSTNAME;
				if ( is_string( $hostname ) && ! empty( $hostname ) ) {
					if ( $send_email ) {
						$url = $hostname . '/moas/api/notify/send';
					} else {
						$url = $hostname . '/moas/api/plugin/notify/send';
					}
				}
			}
			if ( empty( $url ) || ! is_string( $url ) ) {
				return '';
			}
			$url = esc_url_raw( $url );

			$customer_key = get_mo_wc_option( 'admin_customer_key' );
			$api_key      = get_mo_wc_option( 'admin_api_key' );
			if ( empty( $customer_key ) || empty( $api_key ) || ! is_string( $customer_key ) || ! is_string( $api_key ) ) {
				return '';
			}

			$from_email   = isset( $settings->from_email ) && is_string( $settings->from_email ) ? sanitize_email( $settings->from_email ) : '';
			$bcc_email    = isset( $settings->bcc_email ) && is_string( $settings->bcc_email ) ? sanitize_email( $settings->bcc_email ) : '';
			$from_name    = isset( $settings->from_name ) && is_string( $settings->from_name ) ? sanitize_text_field( $settings->from_name ) : '';
			$to_email     = isset( $settings->to_email ) && is_string( $settings->to_email ) ? sanitize_email( $settings->to_email ) : '';
			$subject      = isset( $settings->subject ) && is_string( $settings->subject ) ? sanitize_text_field( $settings->subject ) : '';
			$message      = isset( $settings->message ) && is_string( $settings->message ) ? wp_kses_post( $settings->message ) : '';
			$phone_number = isset( $settings->phone_number ) && is_string( $settings->phone_number ) ? sanitize_text_field( $settings->phone_number ) : '';
			$send_sms     = isset( $settings->send_sms ) ? (bool) $settings->send_sms : false;

			$fields = array(
				'customerKey' => sanitize_text_field( $customer_key ),
				'sendEmail'   => $send_email,
				'sendSMS'     => $send_sms,
				'email'       => array(
					'customerKey' => sanitize_text_field( $customer_key ),
					'fromEmail'   => $from_email,
					'bccEmail'    => $bcc_email,
					'fromName'    => $from_name,
					'toEmail'     => $to_email,
					'toName'      => $to_email,
					'subject'     => $subject,
					'content'     => $message,
				),
				'sms'         => array(
					'customerKey' => sanitize_text_field( $customer_key ),
					'phoneNumber' => $phone_number,
					'message'     => $message,
				),
			);

			$json        = wp_json_encode( $fields );
			$auth_header = MocURLCall::create_auth_header( $customer_key, $api_key );
			$response    = MocURLCall::call_api( $url, $json, $auth_header );
			return is_string( $response ) ? $response : '';
		}



		/**
		 * Validate OTP token.
		 *
		 * Calls the server to validate the OTP.
		 *
		 * @param string $tx_id     Transaction ID from session.
		 * @param string $otp_token OTP token to validate.
		 * @return array Response array from the gateway.
		 */
		public function mowc_validate_otp_token( $tx_id, $otp_token ) {
			if ( ! is_string( $tx_id ) || ! is_string( $otp_token ) ) {
				return array(
					'status'  => 'ERROR',
					'message' => 'Invalid parameters',
				);
			}
			$tx_id     = sanitize_text_field( $tx_id );
			$otp_token = sanitize_text_field( $otp_token );
			if ( defined( 'MO_WC_TEST_MODE' ) && MO_WC_TEST_MODE ) {
				$fail_mode = defined( 'MO_WC_FAIL_MODE' ) && MO_WC_FAIL_MODE;
				return $fail_mode ? array( 'status' => '' ) : array( 'status' => 'SUCCESS' );
			} else {
				$content = MocURLCall::validate_otp_token( $tx_id, $otp_token );
				$decoded = json_decode( $content, true );
				return $decoded;
			}
		}


		/**
		 * Get config page pointers.
		 *
		 * Returns configuration page pointers for visual tour.
		 *
		 * @return array Array of visual tour templates.
		 */
		public function get_config_page_pointers() {
			if ( ! class_exists( 'MOVisualTour' ) ) {
				return array();
			}
			$visual_tour = MOVisualTour::instance();
			if ( ! is_object( $visual_tour ) || ! method_exists( $visual_tour, 'tour_template' ) ) {
				return array();
			}
			$message   = esc_html__( 'Check the links here to see how to change email/sms template, custom gateway, senderID, etc.', 'miniorange-sms-order-notification-otp-verification' );
			$next_text = esc_html__( 'Next', 'miniorange-sms-order-notification-otp-verification' );
			$template  = $visual_tour->tour_template(
				'configuration_instructions',
				'right',
				'',
				'<br>' . esc_html( $message ),
				$next_text,
				'emailSms.svg',
				1
			);
			return is_array( $template ) ? array( $template ) : array();
		}
	}
}
