<?php
/**
 * Helper functions for WooCommerce New Customer SMS Notification
 *
 * @package miniorange-sms-order-notification-otp-verification/notifications/wcsmsnotification/helper/notifications
 */

namespace WCSMSOTP\Notifications\WcSMSNotification\Helper\Notifications;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use WCSMSOTP\Notifications\WcSMSNotification\Helper\MoWcAddOnMessages;
use WCSMSOTP\Helper\MoUtility;
use WCSMSOTP\Objects\SMSNotification;
use WCSMSOTP\Notifications\WcSMSNotification\Helper\WooCommerceNotificationsList;

/**
 * This class is used to handle all the settings and function related
 * to the WooCommerce New Customer SMS Notification. It initializes the
 * notification related settings and implements the functionality for
 * sending the SMS to the user.
 */
if ( ! class_exists( 'WooCommerceCutomerNoteNotification' ) ) {
	/**
	 * WooCommerceCutomerNoteNotification class
	 */
	class WooCommerceNewCustomerNotification extends SMSNotification {

		/** Global Variable
		 *
		 * @var instance - initiates the instance of the file.
		 */
		public static $instance;

		/**
		 * Woocommerce premium tags.
		 *
		 * @var array
		 */
		public $premium_tags;

		/** Declare Default variables */
		protected function __construct() {
			parent::__construct();
			$this->title             = 'New Account';
			$this->page              = 'wc_new_customer_notif';
			$this->is_enabled        = false;
			$this->tool_tip_header   = 'NEW_CUSTOMER_NOTIF_HEADER';
			$this->tool_tip_body     = 'NEW_CUSTOMER_NOTIF_BODY';
			$this->recipient         = 'customer';
			$this->sms_body          = mowc_get_mowc_option( 'woocommerce_registration_generate_password', '' ) === 'yes'
									? MoWcAddOnMessages::showMessage( MoWcAddOnMessages::NEW_CUSTOMER_SMS_WITH_PASS )
									: MoWcAddOnMessages::showMessage( MoWcAddOnMessages::NEW_CUSTOMER_SMS );
			$this->default_sms_body  = mowc_get_mowc_option( 'woocommerce_registration_generate_password', '' ) === 'yes'
									? MoWcAddOnMessages::showMessage( MoWcAddOnMessages::NEW_CUSTOMER_SMS_WITH_PASS )
									: MoWcAddOnMessages::showMessage( MoWcAddOnMessages::NEW_CUSTOMER_SMS );
			$this->premium_tags      = '{user-email},{registration-date},{accountpage-url}';
			$this->available_tags    = '{site-name},{username}';
			$this->page_header       = mowc_( 'NEW ACCOUNT NOTIFICATION SETTINGS' );
			$this->page_description  = mowc_( 'SMS notifications sent to the user after New Account creation.' );
			$this->notification_type = mowc_( 'Customer' );
			self::$instance          = $this;
		}

		/**
		 * Checks if there exists an existing instance of the class.
		 * If not then creates an instance and returns it.
		 */
		public static function getInstance() {
			return null === self::$instance ? new self() : self::$instance;
		}

		/**
		 * Initialize all the variables required to modify the sms template
		 * and send the SMS to the user. Checks if the SMS notification
		 * has been enabled and send SMS to the user. Do not send SMS
		 * if phone number of the customer doesn't exist.
		 *
		 * @param  array $args all the arguments required to send SMS.
		 */
		public function send_sms( array $args ) {
			if ( ! $this->is_enabled ) {
				return;
			}
			if ( ! isset( $args['customer_id'] ) ) {
				return;
			}
			$customer_id = absint( $args['customer_id'] );
			if ( empty( $customer_id ) ) {
				return;
			}
			$this->set_notif_in_session( $this->page );
			$customer_data = isset( $args['new_customer_data'] ) ? $args['new_customer_data'] : array();
			$site_name     = get_bloginfo( 'name' );
			$userdetails   = get_userdata( $customer_id );
			if ( ! $userdetails || ! isset( $userdetails->user_login ) ) {
				return;
			}
			$username     = $userdetails->user_login;
			$phone_number = get_user_meta( $customer_id, 'billing_phone', true );
			$posted_phone_no = '';
			if ( ! empty( $_POST ) && is_array( $_POST ) ) {
				$nonce_valid = false;
				if ( isset( $_POST['woocommerce-register-nonce'] ) ) {
					$nonce_valid = wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce-register-nonce'] ) ), 'woocommerce-register' );
				}
				if ( ! $nonce_valid && isset( $_POST['woocommerce-process-checkout-nonce'] ) ) {
					$nonce_valid = wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ), 'woocommerce-process_checkout' );
				}
				if ( $nonce_valid ) {
					$post_data       = wp_unslash( $_POST ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized via MoUtility::sanitize_check below.
					$posted_phone_no = MoUtility::sanitize_check( 'billing_phone', $post_data );
				}
			}
			$phone_number = MoUtility::is_blank( $phone_number ) && $posted_phone_no ? $posted_phone_no : $phone_number;
			$accountpage     = esc_url( wc_get_page_permalink( 'myaccount' ) ); // phpcs:ignore -- Default function of Woocommerce.

			/* Adding extra tags */
			$user_email        = isset( $userdetails->user_email ) ? $userdetails->user_email : '';
			$registration_date = isset( $userdetails->user_registered ) ? $userdetails->user_registered : '';
			$reg_date          = ! empty( $registration_date ) && is_string( $registration_date ) ? substr( $registration_date, 0, 10 ) : '';

			$replaced_string = array(
				'site-name'         => sanitize_text_field( $site_name ),
				'username'          => sanitize_text_field( $username ),
				'accountpage-url'   => esc_url_raw( $accountpage ),
				'user-email'        => sanitize_email( $user_email ),
				'registration-date' => sanitize_text_field( $reg_date ),
			);
			$replaced_string = apply_filters( 'mowc_new_customer_notif_string_replace', $replaced_string );
			$sms_body        = MoUtility::replace_string( $replaced_string, $this->sms_body );

			if ( MoUtility::is_blank( $phone_number ) ) {
				return;
			}
			$phone_number = trim( $phone_number );
			if ( MoUtility::validate_phone_number( $phone_number ) ) {
				MoUtility::send_phone_notif( $phone_number, $sms_body );
			}
		}
	}

}
