<?php
/**
 * Storzen Module — Flash Sale Countdown
 *
 * Reads WooCommerce product sale_date_to to display a live countdown timer.
 * Works on: product cards (shop/archive) + single product page.
 * Supports: Simple and Variable products (uses nearest expiring variation).
 * JS countdown runs client-side; PHP only renders the container + end-time.
 *
 * @package storzen
 * @since   1.1.0
 */

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

if ( ! class_exists( 'Storzen_Module_Flash_Countdown' ) ) {

	class Storzen_Module_Flash_Countdown {

		public function __construct() {
			add_action( 'wp_enqueue_scripts',                        array( $this, 'enqueue_assets' ) );
			// WooCommerce default theme hooks.
			add_action( 'woocommerce_after_shop_loop_item_title',    array( $this, 'render_on_card' ), 8 );
			add_action( 'woocommerce_single_product_summary',        array( $this, 'render_on_single' ), 25 );
			// Storzen-native template hooks.
			add_action( 'storzen_shop_card_after_title',         array( $this, 'render_on_card' ), 10, 1 );
			add_action( 'storzen_product_single_after_price',    array( $this, 'render_on_single' ), 10, 1 );
		}

		// ── Assets ─────────────────────────────────────────────────────

		public function enqueue_assets() {
			if ( is_admin() ) return;

			wp_enqueue_style(
				'storzen-flash-countdown',
				STORZEN_ROOT_URL . 'assets/css/modules/flash-countdown.css',
				array(),
				STORZEN_VERSION
			);

			wp_enqueue_script(
				'storzen-flash-countdown',
				STORZEN_ROOT_URL . 'assets/js/modules/flash-countdown.js',
				array(),
				STORZEN_VERSION,
				true
			);

			wp_localize_script(
				'storzen-flash-countdown',
				'szFlashCountdown',
				array(
					'labels' => array(
						'days'    => __( 'd', 'storzen' ),
						'hours'   => __( 'h', 'storzen' ),
						'mins'    => __( 'm', 'storzen' ),
						'secs'    => __( 's', 'storzen' ),
						'expired' => __( 'Sale has ended', 'storzen' ),
					),
				)
			);
		}

		// ── On Product Card ─────────────────────────────────────────────

		public function render_on_card( $product_arg = null ) {
			if ( class_exists( 'Elementor\Storzen_Archive_Grid' ) ) {
				$ctx = \Elementor\Storzen_Archive_Grid::is_module_active( 'flash_countdown' );
				if ( false === $ctx ) {
					return;
				}
			}
			if ( ! (bool) storzen_module_setting( 'flash_countdown', 'show_on_cards' ) ) return;
			$product = ( $product_arg instanceof WC_Product ) ? $product_arg : ( $GLOBALS['product'] ?? null );
			if ( ! $product instanceof WC_Product ) return;
			$this->render( $product, 'card' );
		}

		// ── On Single Product ───────────────────────────────────────────

		public function render_on_single( $product_arg = null ) {
			if ( ! (bool) storzen_module_setting( 'flash_countdown', 'show_on_single' ) ) return;
			$product = ( $product_arg instanceof WC_Product ) ? $product_arg : ( $GLOBALS['product'] ?? null );
			if ( ! $product instanceof WC_Product ) return;
			$this->render( $product, 'single' );
		}

		// ── Core Render ─────────────────────────────────────────────────

		/**
		 * Render countdown HTML for a product.
		 *
		 * @param WC_Product $product
		 * @param string     $context  'card' | 'single'
		 */
		private function render( WC_Product $product, $context ) {
			if ( ! $product->is_on_sale() ) return;

			$end_timestamp = $this->get_sale_end_timestamp( $product );
			if ( ! $end_timestamp || $end_timestamp <= time() ) return;

			$label = storzen_module_setting( 'flash_countdown', 'label_text' )
				?: __( 'Offer ends in:', 'storzen' );

			?>
			<div
				class="sz-flash-countdown sz-flash-countdown--<?php echo esc_attr( $context ); ?>"
				data-end="<?php echo esc_attr( $end_timestamp ); ?>"
				aria-live="polite"
				aria-label="<?php
					/* translators: %s: sale end date and time */
					echo esc_attr( sprintf( __( 'Sale ends in %s', 'storzen' ), gmdate( 'Y-m-d H:i', $end_timestamp ) ) ); ?>"
			>
				<?php if ( $label ) : ?>
					<span class="sz-flash-label"><?php echo esc_html( $label ); ?></span>
				<?php endif; ?>

				<div class="sz-flash-timer">
					<span class="sz-flash-unit">
						<span class="sz-flash-digit" data-unit="days">--</span>
						<span class="sz-flash-unit-label"><?php esc_html_e( 'd', 'storzen' ); ?></span>
					</span>
					<span class="sz-flash-sep" aria-hidden="true">:</span>
					<span class="sz-flash-unit">
						<span class="sz-flash-digit" data-unit="hours">--</span>
						<span class="sz-flash-unit-label"><?php esc_html_e( 'h', 'storzen' ); ?></span>
					</span>
					<span class="sz-flash-sep" aria-hidden="true">:</span>
					<span class="sz-flash-unit">
						<span class="sz-flash-digit" data-unit="mins">--</span>
						<span class="sz-flash-unit-label"><?php esc_html_e( 'm', 'storzen' ); ?></span>
					</span>
					<span class="sz-flash-sep" aria-hidden="true">:</span>
					<span class="sz-flash-unit">
						<span class="sz-flash-digit" data-unit="secs">--</span>
						<span class="sz-flash-unit-label"><?php esc_html_e( 's', 'storzen' ); ?></span>
					</span>
				</div>
			</div>
			<?php
		}

		/**
		 * Get sale end timestamp.
		 * For variable products, returns the soonest-expiring variation's date.
		 *
		 * @param WC_Product $product
		 * @return int|null  Unix timestamp (UTC) or null
		 */
		private function get_sale_end_timestamp( WC_Product $product ) {
			if ( $product->is_type( 'variable' ) ) {
				$earliest = null;
				foreach ( $product->get_children() as $child_id ) {
					$variation = wc_get_product( $child_id );
					if ( ! $variation || ! $variation->is_on_sale() ) continue;
					$date = $variation->get_date_on_sale_to();
					if ( $date ) {
						$ts = $date->getTimestamp();
						if ( $ts > time() && ( null === $earliest || $ts < $earliest ) ) {
							$earliest = $ts;
						}
					}
				}
				return $earliest;
			}

			$date = $product->get_date_on_sale_to();
			return $date ? $date->getTimestamp() : null;
		}

	} // end class

} // end class_exists
