<?php
/**
 * WooCommerce Handler
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Handlers\WooCommerce
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Handlers\WooCommerce;

use MOWCPS\Common\Models\Supplier_Model;
use MOWCPS\Common\Utils\Model_Utils;

if ( ! defined( 'ABSPATH' ) ) {
	die;
}

/**
 * Class WooCommerce_Handler
 *
 * Handles WooCommerce related functionality implementation
 */
class WooCommerce_Handler {


	/**
	 * Display product deletion notice based on transient data
	 *
	 * @return void
	 */
	public static function display_product_deletion_notice() {
		$notice_data = get_transient( 'mowcps_product_deletion_notice' );

		if ( $notice_data && is_admin() ) {
			$type    = $notice_data['type'] ?? 'info';
			$message = $notice_data['message'] ?? '';

			if ( ! empty( $message ) ) {
				$notice_class = 'notice';
				if ( $type === 'success' ) {
					$notice_class .= ' notice-success';
				} elseif ( $type === 'error' ) {
					$notice_class .= ' notice-error';
				} else {
					$notice_class .= ' notice-info';
				}
				$notice_class .= ' is-dismissible';

				?>
				<div class="<?php echo esc_attr( $notice_class ); ?>">
					<p><?php echo esc_html( $message ); ?></p>
					<button type="button" class="notice-dismiss">
						<span class="screen-reader-text">Dismiss this notice.</span>
					</button>
				</div>
				<?php

				// Delete the transient after displaying it once
				delete_transient( 'mowcps_product_deletion_notice' );
			}
		}
	}

	/**
	 * Handle WooCommerce product top bar delete button with React
	 *
	 * @return void
	 */
	public static function render_bulk_delete_products_button() {
		self::enqueue_modal_assets();
		?>
		<div class="alignleft actions custom">
			<button type="button" name="mo_wcps_custom_" class="button mo-wcps-delete-button" onclick="openDeleteProductsModal()">
				<span style="margin-right: 6px;">🗑️</span>
				<?php echo esc_attr_e( 'Delete miniOrange Synced Products', 'products-sync-for-woocommerce' ); ?>
			</button>
		</div>
		<script>
			// Immediate fallback function - will be replaced when vanilla JS loads
			window.openDeleteProductsModal = function() {
				// Check if vanilla JS version is available
				if (window.MOWCPSDeleteModal && window.MOWCPSDeleteModal.open) {
					window.MOWCPSDeleteModal.open();
				} else {
					alert('Delete products functionality is loading. Please try again in a moment.');
				}
			};
		</script>
		<?php
	}

	/**
	 * Enqueue delete products React assets
	 *
	 * @return void
	 */
	private static function enqueue_modal_assets() {
		wp_enqueue_style(
			'mowcps-delete-products-css',
			plugin_dir_url( dirname( __DIR__, 3 ) ) . 'views/public/css/delete-modal.css',
			array(),
			'1.0.0'
		);

		wp_enqueue_script(
			'mowcps-delete-products',
			plugin_dir_url( dirname( __DIR__, 3 ) ) . 'views/public/js/delete-modal.js',
			array(),
			'1.0.0',
			false
		);

		wp_localize_script(
			'mowcps-delete-products',
			'MOWCPSData',
			array(
				'pluginUrl' => plugin_dir_url( MOWCPS_PLUGIN_DIR . 'index.php' ),
				'restNonce' => wp_create_nonce( 'wp_rest' ),
				'restUrl'   => rest_url( 'mowcps/v1' ),
			)
		);
	}

	/**
	 * Get WooCommerce countries
	 *
	 * Retrieves all available countries from WooCommerce and formats them
	 * as an array with 'label' and 'value' keys for use in dropdowns.
	 *
	 * @return array Array of countries with 'label' and 'value' keys. Returns empty array if WooCommerce is not available or on error.
	 */
	public static function get_countries() {
		try {
			// Check if WooCommerce is available.
			if ( ! class_exists( 'WooCommerce' ) ) {
				return array();
			}

			$countries      = new \WC_Countries();
			$countries_list = $countries->get_countries();

			if ( empty( $countries_list ) || ! is_array( $countries_list ) ) {
				return array();
			}

			$countries_array = array();
			foreach ( $countries_list as $code => $name ) {
				$countries_array[] = array(
					'label' => $name,
					'value' => $code,
				);
			}

			return $countries_array;

		} catch ( \Exception $e ) {
			return array();
		}
	}

	/**
	 * Get WooCommerce states for a country
	 *
	 * Retrieves all available states/provinces for a given country code
	 * and formats them as an array with 'label' and 'value' keys for use in dropdowns.
	 *
	 * @param string $country_code Country code (e.g., 'US', 'CA', 'GB').
	 * @return array Array of states with 'label' and 'value' keys. Returns empty array if WooCommerce is not available, country code is invalid, or no states exist for the country.
	 */
	public static function get_states( $country_code ) {
		try {
			// Check if WooCommerce is available.
			if ( ! class_exists( 'WooCommerce' ) ) {
				return array();
			}

			// Validate country code parameter.
			if ( empty( $country_code ) || ! is_string( $country_code ) ) {
				return array();
			}

			$countries   = new \WC_Countries();
			$states_list = $countries->get_states( $country_code );

			// Return empty array if no states exist for this country.
			if ( empty( $states_list ) || ! is_array( $states_list ) ) {
				return array();
			}

			$states_array = array();
			foreach ( $states_list as $code => $name ) {
				$states_array[] = array(
					'label' => $name,
					'value' => $code,
				);
			}

			return $states_array;

		} catch ( \Exception $e ) {
			return array();
		}
	}
}
