<?php
/**
 * PolyLang Strings Class
 *
 * This is the constant class which lists all the texts
 * that need to be supported for the polylang plugin.
 * PolyLang plugin supports multilingual texts.
 *
 * @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\Objects\BaseMessages;
use WCSMSOTP\Traits\Instance;
use ReflectionClass;
use ReflectionException;

/**
 * PolyLang Strings Class
 *
 * This is the constant class which lists all the texts
 * that need to be supported for the polylang plugin.
 * PolyLang plugin supports multilingual texts.
 */
if ( ! class_exists( 'PolyLangStrings' ) ) {
	/**
	 * PolyLang Strings Class
	 *
	 * This is the constant class which lists all the texts
	 * that need to be supported for the polylang plugin.
	 * PolyLang plugin supports multilingual texts.
	 */
	class PolyLangStrings {

		use Instance;

		/**
		 * Constructor.
		 *
		 * Initializes the PolyLang strings constant with all translatable strings.
		 * The constant is only defined once to prevent redefinition errors.
		 *
		 * @return void
		 */
		private function __construct() {
			if ( defined( 'MOV_WC_POLY_STRINGS' ) ) {
				return;
			}

			$strings = array();

			// Collect strings from BaseMessages class.
			if ( class_exists( 'BaseMessages' ) ) {
				try {
					$reflect_base   = new \ReflectionClass( BaseMessages::class );
					$base_constants = $reflect_base->getConstants();
					if ( is_array( $base_constants ) ) {
						foreach ( $base_constants as $key => $value ) {
							if ( is_string( $value ) && ! empty( $value ) ) {
								$strings[ $value ] = '';
							}
						}
					}
				} catch ( \ReflectionException $e ) {
					// Reflection failed, continue anyway.
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Exception is intentionally ignored.
				}
			}

			// Collect strings from MoMessages class if it exists.
			if ( class_exists( 'MoMessages' ) && method_exists( 'MoMessages', 'showMessage' ) ) {
				try {
					$reflect_mo   = new \ReflectionClass( MoMessages::class );
					$mo_constants = $reflect_mo->getConstants();
					if ( is_array( $mo_constants ) ) {
						foreach ( $mo_constants as $key => $value ) {
							if ( is_string( $value ) && ! empty( $value ) ) {
								$strings[ $value ] = '';
							}
						}
					}
				} catch ( \ReflectionException $e ) {
					// Reflection failed, continue anyway.
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Exception is intentionally ignored.
				}
			}

			// Define constant only if strings array is not empty.
			if ( ! empty( $strings ) && function_exists( 'maybe_serialize' ) ) {
				define( 'MOV_WC_POLY_STRINGS', maybe_serialize( $strings ) );
			}
		}
	}
}
