<?php
/**
 * Load admin view for Form SMS Notification addon.
 *
 * @package miniorange-sms-order-notification-otp-verification/notifications/formsmsnotification/handler
 */

namespace WCSMSOTP\Notifications\FormSMSNotification\Handler;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use WCSMSOTP\Notifications\FormSMSNotification\Helper\FormSMSNotificationsList;
use WCSMSOTP\Objects\BaseAddOnHandler;
use WCSMSOTP\Helper\MoMessages;
use WCSMSOTP\Objects\BaseMessages;
use WCSMSOTP\Helper\MoConstants;
use WCSMSOTP\Traits\Instance;
use WCSMSOTP\Helper\MoFormDocs;
use WCSMSOTP\Helper\MoUtility;

/**
 * The class is used to handle all Form SMS Notifications related functionality.
 * This class hooks into all the available form submission hooks and filters
 * to provide the possibility of SMS notifications.
 */
if ( ! class_exists( 'FormSMSNotificationsHandler' ) ) {
	/**
	 * FormSMSNotificationsHandler class
	 */
	class FormSMSNotificationsHandler extends BaseAddOnHandler {

		use Instance;

		/**
		 * Instance of the FormSMSNotificationsList Class.
		 *
		 * @var FormSMSNotificationsList instance of the FormSMSNotificationsList Class */
		private $notification_settings;


		/**
		 * Constructor checks if notifications has been enabled by the admin and initializes
		 * all the class variables. This function also defines all the hooks to
		 * hook into to make the add-on functionality work.
		 */
		protected function __construct() {
			parent::__construct();

			$notification_settings = mowc_get_fmsn_option( 'notification_settings_option' );
			if ( empty( $notification_settings ) || ! is_object( $notification_settings ) ) {
				$notification_settings = FormSMSNotificationsList::instance();
			}
			$this->notification_settings = $notification_settings;

			if ( empty( mowc_get_fmsn_option( 'notification_settings_option' ) ) && ! empty( mowc_get_fmsn_option( 'notification_settings' ) ) ) {
				$old_notification_settings = get_option( 'mo_form_sms_notification_settings' );
				if ( ! empty( $old_notification_settings ) && is_array( $old_notification_settings ) ) {
					foreach ( $old_notification_settings as $notification_name => $property ) {
						if ( ! is_array( $property ) ) {
							continue;
						}
						if ( isset( $this->notification_settings->$notification_name ) ) {
							$sms_settings             = $this->notification_settings->$notification_name;
							$sms_settings->is_enabled = isset( $property['is_enabled'] ) ? $property['is_enabled'] : false;
							$sms_settings->sms_body   = isset( $property['sms_body'] ) ? sanitize_textarea_field( $property['sms_body'] ) : '';
							$sms_settings->recipient  = isset( $property['recipient'] ) ? sanitize_text_field( $property['recipient'] ) : '';
						}
					}
					mowc_update_fmsn_option( 'notification_settings_option', $this->notification_settings );
				}
			}

			add_action( 'wpcf7_before_send_mail', array( $this, 'mo_send_new_customer_sms_notif' ), 10, 1 );
			add_action( 'wpforms_ajax_submit_completed', array( $this, 'mo_wpform_send_sms_notif' ), 10, 2 );
			add_action( 'ninja_forms_after_submission', array( $this, 'mo_ninjaform_send_sms_notif' ), 10, 1 );
			add_action( 'admin_init', array( $this, 'check_admin_notifications_options' ) );
		}


		/**
		 * This function hooks into the wpcf7_before_send_mail hook
		 * to send an SMS notification to the user when he submit the Contact form.
		 *
		 * @param array $args     the extra arguments passed by the hook.
		 */
		public function mo_send_new_customer_sms_notif( $args ) {
			$this->notification_settings->get_mo_contact_form7_notif()->send_sms( $args );
		}

		/**
		 * This function hooks into the wpforms_ajax_submit_completed hook
		 * to send an SMS notification to the user when he submit the Contact form.
		 *
		 * @param array $form_id - Form id.
		 * @param array $response - Reponse message text.
		 * @return void
		 */
		public function mo_wpform_send_sms_notif( $form_id, $response ) {
			$this->notification_settings->get_mo_wpform_notif()->send_sms( array_merge( array( 'form_id' => $form_id ), $response ) );
		}

		/**
		 * This function hooks into the gform_after_submission hook
		 * to send an SMS notification to the user when he submit the Contact form.
		 *
		 * @param array $form_data The entry currently being processed.
		 */
		public function mo_ninjaform_send_sms_notif( $form_data ) {
			$this->notification_settings->get_mo_ninja_form_notif()->send_sms( $form_data );
		}

		/**
		 * Checks and updates the notification options.
		 */
		public function check_admin_notifications_options() {
			$option = isset( $_POST['option'] ) ? sanitize_text_field( wp_unslash( $_POST['option'] ) ) : '';
			if ( 'mo_form_sms_notif_settings' !== $option ) {
				return;
			}
			if ( ! current_user_can( 'manage_options' ) || ! check_admin_referer( 'mo_form_sms_notif_settings', 'mo_form_sms_notif_settings_nonce' ) ) {
				wp_die( esc_attr( MoMessages::showMessage( MoMessages::INVALID_OP ) ) );
			}

			$admin_recipient_value = MoUtility::sanitize_check( 'mo_form_admin_notif_recipient', $_POST );

			foreach ( $this->notification_settings as $notification_name => $notification_setting ) {
				if ( ! is_object( $notification_setting ) ) {
					continue;
				}
				$textarea_tag  = sanitize_key( $notification_name ) . '_smsbody';
				$recipient_tag = sanitize_key( $notification_name ) . '_recipient';
				$notification  = $this->notification_settings->$notification_name;

				if ( ! is_object( $notification ) ) {
					continue;
				}

				$textar_tag       = isset( $_POST[ $textarea_tag ] ) ? sanitize_textarea_field( wp_unslash( $_POST[ $textarea_tag ] ) ) : null;
				$default_sms_body = isset( $notification->default_sms_body ) ? $notification->default_sms_body : '';
				$sms              = MoUtility::is_blank( $textar_tag ) ? $default_sms_body : $textar_tag;
				$recipient_value  = MoUtility::sanitize_check( $recipient_tag, $_POST );

				if ( ! empty( $recipient_value ) ) {
					$recipient_value = preg_replace( '/[^+\-0-9; ]/', '', $recipient_value );
				}

				$sanitized_notification_name = sanitize_key( $notification_name );
				$notification->set_is_enabled( isset( $_POST[ $sanitized_notification_name ] ) );
				$notification->set_recipient( $recipient_value );
				$notification->set_admin_recipient( $admin_recipient_value );
				$notification->set_sms_body( $sms );
			}
			mowc_update_fmsn_option( 'notification_settings_option', $this->notification_settings );
			mowc_update_fmsn_option( 'moform_notif_admin_recipient', $admin_recipient_value );
		}

		/**
		 * Unhook all the emails that we will be sending sms notifications for.
		 */
		private function unhook() {
			// Reserved for future use if needed.
		}


		/** Set Addon Key */
		public function set_addon_key() {
			$this->add_on_key = 'form_sms_notification_addon';
		}

		/** Set AddOn Desc */
		public function set_add_on_desc() {
			$this->add_on_desc = mowc_(
				'Allows your site to send custom SMS notifications to your customers.'
				. 'Click on the settings button to the right to see the list of notifications that go out.'
			);
		}

		/** Set an AddOnName */
		public function set_add_on_name() {
			$this->addon_name = mowc_( 'Forms SMS Notification' );
		}

		/** Set an Addon Docs link */
		public function set_add_on_docs() {
		}

		/** Set an Addon Video link */
		public function set_add_on_video() {
		}

		/** Set Settings Page URL */
		public function set_settings_url() {
			$this->settings_url = add_query_arg( array( 'addon' => 'form_notif' ), isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : null );
		}
	}
}
