<?php
/**
 * Utility functions for WooCommerce SMS Notifications
 *
 * @package miniorange-sms-order-notification-otp-verification/notifications/wcsmsnotification/helper
 */

namespace WCSMSOTP\Notifications\WcSMSNotification\Helper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use WCSMSOTP\Helper\MoUtility;
use WC_Order;

/**
 * This class is used to define some plugin wide utility
 * functions. The functions described here are all static
 * in nature so that it's accessible without an instance.
 */
if ( ! class_exists( 'MoWcAddOnUtility' ) ) {
	/**
	 * MoWcAddOnUtility class
	 */
	class MoWcAddOnUtility {


		/**
		 * Get the Phone of the first Admin user. This is used as
		 * the recipient of the admin SMS notifications if no
		 * phone number is saved for the notification.
		 *
		 * @return string
		 */
		public static function get_admin_phone_number() {
			$recipient_value       = '';
			$notification_settings = mowc_get_mowc_option( 'notification_settings' );
			if ( ! empty( $notification_settings ) && is_object( $notification_settings ) ) {
				$sms_settings = $notification_settings->get_wc_admin_order_status_notif(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- $notification_settings is an object.
				if ( is_object( $sms_settings ) && isset( $sms_settings->recipient ) ) {
					$recipient_value = maybe_unserialize( $sms_settings->recipient );
					if ( false === $recipient_value ) {
						$recipient_value = '';
					} elseif ( is_array( $recipient_value ) ) {
						$recipient_value = implode( ';', array_map( 'sanitize_text_field', $recipient_value ) );
					} else {
						$recipient_value = sanitize_text_field( $recipient_value );
					}
				}
			}
			return $recipient_value;
		}

		/**
		 * Get the billing phone number of Customer. If the billing number is not set
		 * with the order, pick the number from registered phone number.
		 *
		 * @param WC_Order $order   - Order details, WooCommerce Order Object.
		 * @return string
		 */
		public static function get_customer_number_from_order( $order ) {
			if ( empty( $order ) || ! is_a( $order, 'WC_Order' ) ) {
				return '';
			}
			$phone = $order->get_billing_phone();
			if ( ! empty( $phone ) ) {
				return sanitize_text_field( $phone );
			}
			$user_id = $order->get_user_id();
			if ( ! empty( $user_id ) ) {
				$phone = get_user_meta( $user_id, 'billing_phone', true );
				return ! empty( $phone ) ? sanitize_text_field( $phone ) : '';
			}
			return '';
		}


		/**
		 * Checks if the customer is registered or not and shows a message on the page
		 * to the user so that they can register or login themselves to use the plugin.
		 */
		public static function is_addon_activated() {
			MoUtility::is_addon_activated();
		}
	}

}
