<?php
/**
 * FoodOrd Card Block Class
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Card_Block
 */
class Foodord_Card_Block {
	/**
	 * Constructor: register block.
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register_block' ) );
	}

	/**
	 * Register dynamic block.
	 */
	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		// Register scripts and styles.
		wp_register_script(
			'foodord-card-block-editor',
			FOODORD_URL . 'admin/js/blocks/foodord-card-block.js',
			array( 'wp-blocks', 'wp-element', 'wp-i18n' ),
			FOODORD_VERSION,
			true
		);

		wp_register_style(
			'foodord-card',
			FOODORD_URL . 'public/css/foodord-card.css',
			array(),
			FOODORD_VERSION
		);

		// Register block with minimal config for widget compatibility.
		register_block_type(
			'foodord/card',
			array(
				'render_callback' => array( $this, 'render' ),
				'editor_script'   => 'foodord-card-block-editor',
				'style'           => 'foodord-card',
			)
		);
	}

	/**
	 * Render block.
	 *
	 * @return string
	 */
	public function render(): string {
		// Signal that this page contains the Foodord Card block.
		$GLOBALS['foodord_has_card_block'] = true;
		// Signal that home banner should be shown (for dynamic rendering detection).
		$GLOBALS['foodord_banner_should_show'] = true;

		// Enqueue frontend styles.
		if ( function_exists( 'foodord_enqueue_frontend_styles' ) ) {
			foodord_enqueue_frontend_styles();
		}

		// Enqueue frontend JS only if not in admin.
		if ( ! is_admin() ) {
			wp_enqueue_script(
				'foodord-card',
				FOODORD_URL . 'public/js/foodord-card.js',
				array( 'jquery' ),
				FOODORD_VERSION,
				true
			);

			wp_localize_script(
				'foodord-card',
				'foodordCardI18n',
				array(
					'checkout'         => __( 'Checkout', 'foodord' ),
					'orderAndPay'      => __( 'Order and Pay', 'foodord' ),
					'viewCart'         => __( 'View Cart', 'foodord' ),
					'emptyCartText'    => __( 'Your cart is empty', 'foodord' ),
					'emptyCartSubtext' => __( 'Add items to get started', 'foodord' ),
					'itemsInCart'      => __( 'Items in cart', 'foodord' ),
					/* translators: %s: Product name */
					'editItem'         => __( 'Edit %s', 'foodord' ),
					'addToCart'        => __( 'Add to cart', 'foodord' ),
					'updateItem'       => __( 'Update item', 'foodord' ),
					'subtotal'         => __( 'Subtotal', 'foodord' ),
					'total'            => __( 'Total', 'foodord' ),
					'deliveryFee'      => __( 'Delivery Fee', 'foodord' ),
					'clearCartConfirmMessage' => __(
						'Are you sure you want to clear all items from your cart?',
						'foodord'
					),
					'cancel'           => __( 'Cancel', 'foodord' ),
					'clearCart'        => __( 'Clear Cart', 'foodord' ),
					'free'             => __( 'Free', 'foodord' ),
					/* translators: %1$s: remaining amount. */
					'minOrderNotice'   => __( 'Add %1$s more to reach the minimum order.', 'foodord' ),
					'upsellsEnabled'   => 'yes' === get_option( 'foodord_enable_modal_upsells', 'no' ),
				)
			);

			// Pass minimum order amount data to JavaScript.
			$this->localize_minimum_order_params();

			// Add inline script to update clear button state after load.
			wp_add_inline_script(
				'foodord-card',
				'
				jQuery(document).ready(function() {
					setTimeout(function() {
						if (typeof window.FoodordCard !== "undefined" && window.FoodordCard.updateClearButton) {
							window.FoodordCard.updateClearButton();
						}
					}, 300);
				});
				'
			);

			if ( class_exists( 'Foodord_Business_Hours' ) ) {
				Foodord_Business_Hours::enqueue_toast_script();
			}
		}

		// Render HTML directly.
		ob_start();
		$is_checkout = function_exists( 'is_checkout' ) && is_checkout();
		?>
		<div class="wr-card" data-context="<?php echo $is_checkout ? 'checkout' : 'default'; ?>" role="complementary" aria-label="<?php esc_attr_e( 'Cart sidebar', 'foodord' ); ?>">
			<div class="wr-card__header">
				<h2 class="wr-card__title"><?php esc_html_e( 'Your order', 'foodord' ); ?></h2>
				<?php
				$cart_has_items = function_exists( 'WC' ) && WC()->cart && WC()->cart->get_cart_contents_count() > 0;
				$cart_count     = function_exists( 'WC' ) && WC()->cart ? (int) WC()->cart->get_cart_contents_count() : 0;
				$disabled       = $cart_has_items ? '' : ' disabled';
				$btn_text       = $is_checkout ? __( 'Order and Pay', 'foodord' ) : __( 'Checkout', 'foodord' );
				$checkout_url   = function_exists( 'wc_get_checkout_url' ) ? wc_get_checkout_url() : '/checkout';
				?>
				<button class="wr-card__clear-btn" type="button" title="<?php esc_attr_e( 'Clear cart', 'foodord' ); ?>" aria-label="<?php esc_attr_e( 'Clear all items from cart', 'foodord' ); ?>"<?php echo esc_attr( $disabled ); ?>>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<polyline points="3 6 5 6 21 6" />
						<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
						<line x1="10" y1="11" x2="10" y2="17" />
						<line x1="14" y1="11" x2="14" y2="17" />
					</svg>
				</button>
			</div>
		<div class="wr-card__body">
			<div class="wr-card__empty">
				<svg class="wr-card__empty-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
				<div class="wr-card__empty-text"><?php esc_html_e( 'Your cart is empty', 'foodord' ); ?></div>
				<div class="wr-card__empty-subtext"><?php esc_html_e( 'Add items to get started', 'foodord' ); ?></div>
			</div>
		</div>
			<div class="wr-card__footer">
				<button class="wr-card__cta" type="button" disabled aria-disabled="true" data-checkout-url="<?php echo esc_attr( $checkout_url ); ?>" data-is-checkout="<?php echo $is_checkout ? 'true' : 'false'; ?>" data-action="<?php echo $is_checkout ? 'order' : 'checkout'; ?>">
					<span class="wr-card__cta-left">
						<span class="wr-card__cta-count" aria-live="polite" aria-label="<?php echo esc_attr__( 'Items in cart', 'foodord' ); ?>"><?php echo (int) $cart_count; ?></span>
						<span class="wr-card__cta-label"><?php echo esc_html( $btn_text ); ?></span>
					</span>
					<span class="wr-card__cta-total"><?php echo function_exists( 'wc_price' ) ? wp_kses_post( wc_price( 0 ) ) : '0'; ?></span>
				</button>
			</div>
		</div>
		<?php
		$html = (string) ob_get_clean();

		if ( function_exists( 'foodord_wrap_card_markup' ) ) {
			return foodord_wrap_card_markup( $html );
		}

		return $html;
	}

	/**
	 * Localize minimum order parameters for JavaScript
	 */
	private function localize_minimum_order_params() {
		$minimum_amount = 0;
		$is_table_ordering = foodord_is_table_ordering_request();

		if ( ! function_exists( 'WC' ) ) {
			return;
		}

		$wc = WC();
		if ( ! $wc || ! isset( $wc->session ) || ! $wc->session ) {
			return;
		}

		if ( ! $is_table_ordering && class_exists( 'Foodord_Checkout_Validator' ) && class_exists( 'Foodord_Location_Service' ) ) {
			$order_type = (string) $wc->session->get( 'foodord_order_type', 'delivery' );
			$order_mode = function_exists( 'foodord_get_order_mode' ) ? foodord_get_order_mode() : (string) $wc->session->get( 'foodord_order_mode', $order_type );

			if ( 'pickup' !== $order_type && 'pickup' !== $order_mode ) {
				$session_location = Foodord_Location_Service::get_session();
				if ( $session_location['allowed'] && isset( $session_location['minimum'] ) ) {
					$minimum_amount = max( 0.0, (float) $session_location['minimum'] );
				} else {
					$city   = '';
					$postal = '';

					if ( isset( $wc->customer ) && $wc->customer ) {
						$city   = (string) $wc->customer->get_shipping_city();
						$postal = (string) $wc->customer->get_shipping_postcode();

						if ( '' === $city || '' === $postal ) {
							$billing_city   = (string) $wc->customer->get_billing_city();
							$billing_postal = (string) $wc->customer->get_billing_postcode();

							if ( '' === $city && '' !== $billing_city ) {
								$city = $billing_city;
							}

							if ( '' === $postal && '' !== $billing_postal ) {
								$postal = $billing_postal;
							}
						}
					}

					if ( '' === $city ) {
						$session_city = (string) $wc->session->get( Foodord_Location_Service::SESSION_CITY_KEY );
						if ( '' !== $session_city ) {
							$city = $session_city;
						}
					}

					if ( '' === $postal ) {
						$session_postal = (string) $wc->session->get( Foodord_Location_Service::SESSION_POSTAL_KEY );
						if ( '' !== $session_postal ) {
							$postal = $session_postal;
						}
					}

					if ( '' !== $city ) {
						$matched = Foodord_Location_Service::find_location( $city, $postal );
						if ( is_array( $matched ) && isset( $matched['minimum'] ) && is_numeric( $matched['minimum'] ) ) {
							$minimum_amount = max( 0.0, (float) $matched['minimum'] );
						}
					}
				}
			}
		}

		wp_localize_script(
			'foodord-card',
			'foodord_block_checkout_params',
			array(
				'minimum_order_amount' => $minimum_amount,
			'currency_symbol'      => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '',
		)
	);
	}
}
