<?php

namespace Objectiv\Plugins\Checkout\Admin\Pages\Premium;

use Objectiv\Plugins\Checkout\Admin\Pages\PageAbstract;
use Objectiv\Plugins\Checkout\Managers\SettingsManager;

/**
 * Side Cart Admin Page
 *
 * @link checkoutwc.com
 * @since 5.0.0
 * @package Objectiv\Plugins\Checkout\Admin\Pages
 */
class SideCart extends PageAbstract {
	public function __construct() {
		parent::__construct( __( 'Side Cart', 'checkout-wc' ), 'cfw_manage_side_cart', 'side-cart' );
	}

	public function output() {
		?>
		<div id="cfw-admin-pages-side-cart"></div>
		<?php
	}

	public function maybe_set_script_data() {
		if ( ! $this->is_current_page() ) {
			return;
		}

		$icon_options = [];

		foreach ( glob( CFW_PATH . '/assets/images/cart-icons/*.svg' ) as $icon_filename ) {
			$icon_options[ basename( $icon_filename ) ] = file_get_contents( $icon_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		}

		$this->set_script_data(
			[
				'settings' => [
					'enable_side_cart'                     => SettingsManager::instance()->get_setting( 'enable_side_cart' ) === 'yes',
					'side_cart_icon'                       => SettingsManager::instance()->get_setting( 'side_cart_icon' ),
					'side_cart_custom_icon_attachment_id'  => SettingsManager::instance()->get_setting( 'side_cart_custom_icon_attachment_id' ),
					'side_cart_icon_color'                 => SettingsManager::instance()->get_setting( 'side_cart_icon_color' ),
					'side_cart_icon_width'                 => SettingsManager::instance()->get_setting( 'side_cart_icon_width' ),
					'enable_floating_cart_button'          => SettingsManager::instance()->get_setting( 'enable_floating_cart_button' ) === 'yes',
					'floating_cart_button_right_position'  => SettingsManager::instance()->get_setting( 'floating_cart_button_right_position' ),
					'floating_cart_button_bottom_position' => SettingsManager::instance()->get_setting( 'floating_cart_button_bottom_position' ),
					'hide_floating_cart_button_empty_cart' => SettingsManager::instance()->get_setting( 'hide_floating_cart_button_empty_cart' ) === 'yes',
					'shake_floating_cart_button'           => SettingsManager::instance()->get_setting( 'shake_floating_cart_button' ) === 'yes',
					'enable_ajax_add_to_cart'              => SettingsManager::instance()->get_setting( 'enable_ajax_add_to_cart' ) === 'yes',
					'enable_side_cart_payment_buttons'     => SettingsManager::instance()->get_setting( 'enable_side_cart_payment_buttons' ) === 'yes',
					'enable_order_bumps_on_side_cart'      => SettingsManager::instance()->get_setting( 'enable_order_bumps_on_side_cart' ) === 'yes',
					'enable_side_cart_suggested_products'  => SettingsManager::instance()->get_setting( 'enable_side_cart_suggested_products' ) === 'yes',
					'side_cart_suggested_products_heading' => SettingsManager::instance()->get_setting( 'side_cart_suggested_products_heading' ),
					'enable_side_cart_suggested_products_random_fallback' => SettingsManager::instance()->get_setting( 'enable_side_cart_suggested_products_random_fallback' ) === 'yes',
					'side_cart_suggested_products_link_to_product' => SettingsManager::instance()->get_setting( 'side_cart_suggested_products_link_to_product' ) === 'yes',
					'allow_side_cart_item_variation_changes' => SettingsManager::instance()->get_setting( 'allow_side_cart_item_variation_changes' ) === 'yes',
					'show_side_cart_item_discount'         => SettingsManager::instance()->get_setting( 'show_side_cart_item_discount' ) === 'yes',
					'enable_promo_codes_on_side_cart'      => SettingsManager::instance()->get_setting( 'enable_promo_codes_on_side_cart' ) === 'yes',
					'enable_side_cart_totals'              => SettingsManager::instance()->get_setting( 'enable_side_cart_totals' ) === 'yes',
					'enable_side_cart_continue_shopping_button' => SettingsManager::instance()->get_setting( 'enable_side_cart_continue_shopping_button' ) === 'yes',
					'enable_free_shipping_progress_bar'    => SettingsManager::instance()->get_setting( 'enable_free_shipping_progress_bar' ) === 'yes',
					'side_cart_free_shipping_threshold'    => SettingsManager::instance()->get_setting( 'side_cart_free_shipping_threshold' ),
					'side_cart_amount_remaining_message'   => SettingsManager::instance()->get_setting( 'side_cart_amount_remaining_message' ),
					'side_cart_free_shipping_message'      => SettingsManager::instance()->get_setting( 'side_cart_free_shipping_message' ),
					'side_cart_free_shipping_tiers'        => $this->get_normalized_tiers(),
					'side_cart_free_shipping_excluded_shipping_classes' => array_map( 'strval', (array) SettingsManager::instance()->get_setting( 'side_cart_free_shipping_excluded_shipping_classes' ) ),
					'side_cart_free_shipping_progress_indicator_color' => SettingsManager::instance()->get_setting( 'side_cart_free_shipping_progress_indicator_color' ),
					'side_cart_free_shipping_progress_bg_color' => SettingsManager::instance()->get_setting( 'side_cart_free_shipping_progress_bg_color' ),
					'enable_free_shipping_progress_bar_at_checkout' => SettingsManager::instance()->get_setting( 'enable_free_shipping_progress_bar_at_checkout' ) === 'yes',
					'side_cart_empty_image_attachment_id'  => SettingsManager::instance()->get_setting( 'side_cart_empty_image_attachment_id' ),
				],
				'params'   => [
					'icon_options'            => $icon_options,
					'default_free_shipping_progress_bar_color' => cfw_get_active_template()->get_default_setting( 'button_color' ),
					'custom_icon_preview_url' => wp_get_attachment_url( SettingsManager::instance()->get_setting( 'side_cart_custom_icon_attachment_id' ) ),
					'empty_image_preview_url' => wp_get_attachment_url( SettingsManager::instance()->get_setting( 'side_cart_empty_image_attachment_id' ) ),
					'shipping_classes'        => $this->get_shipping_class_options(),
					'max_free_shipping_tiers' => 3,
					'free_shipping_methods'   => $this->get_free_shipping_methods(),
					'shipping_settings_url'   => admin_url( 'admin.php?page=wc-settings&tab=shipping' ),
					'currency_symbol'         => html_entity_decode( get_woocommerce_currency_symbol() ),
				],
				'plan'     => $this->get_plan_data(),
			]
		);
	}

	/**
	 * Normalize the stored free shipping tiers into a stable shape for the admin form.
	 *
	 * @return array
	 */
	private function get_normalized_tiers(): array {
		$tiers = SettingsManager::instance()->get_setting( 'side_cart_free_shipping_tiers' );

		if ( empty( $tiers ) || ! is_array( $tiers ) ) {
			return [];
		}

		$normalized = [];

		foreach ( $tiers as $index => $tier ) {
			if ( ! is_array( $tier ) ) {
				continue;
			}

			$normalized[] = [
				'id'                => isset( $tier['id'] ) ? (string) $tier['id'] : 'tier-' . $index,
				'threshold'         => isset( $tier['threshold'] ) ? (string) $tier['threshold'] : '',
				'reward_type'       => isset( $tier['reward_type'] ) ? (string) $tier['reward_type'] : 'free_shipping',
				'label'             => isset( $tier['label'] ) ? (string) $tier['label'] : '',
				'unlocked_message'  => isset( $tier['unlocked_message'] ) ? (string) $tier['unlocked_message'] : '',
				'remaining_message' => isset( $tier['remaining_message'] ) ? (string) $tier['remaining_message'] : '',
				'color'             => isset( $tier['color'] ) ? (string) $tier['color'] : '',
				'gift_product'      => ( isset( $tier['gift_product'] ) && is_array( $tier['gift_product'] ) ) ? array_values( $tier['gift_product'] ) : [],
			];
		}

		return $normalized;
	}

	/**
	 * Build the WooCommerce shipping class options for the exclusion multiselect.
	 *
	 * @return array
	 */
	private function get_shipping_class_options(): array {
		$options = [];

		if ( ! function_exists( 'WC' ) || ! WC()->shipping() ) {
			return $options;
		}

		foreach ( WC()->shipping()->get_shipping_classes() as $shipping_class ) {
			$options[] = [
				'value' => (string) $shipping_class->term_id,
				'label' => $shipping_class->name,
			];
		}

		return $options;
	}

	/**
	 * Collect the store's enabled WooCommerce Free Shipping methods so the admin form can warn
	 * when a "free shipping" reward tier has no real method behind it (or a mismatched threshold).
	 *
	 * The rewards bar only reflects progress toward free shipping — it never creates it — so the
	 * actual delivery depends on a Free Shipping method existing in a shipping zone. We surface the
	 * min_amount + requires of each so the client can compare against the tier threshold.
	 *
	 * @return array List of [ 'zone' => string, 'requires' => string, 'min_amount' => float ].
	 */
	private function get_free_shipping_methods(): array {
		$methods = [];

		if ( ! class_exists( '\WC_Shipping_Zones' ) || ! class_exists( '\WC_Shipping_Zone' ) ) {
			return $methods;
		}

		$zones = \WC_Shipping_Zones::get_zones( 'admin' );

		// get_zones() omits the "Rest of the World" zone (id 0); include it explicitly.
		$rest_of_world = new \WC_Shipping_Zone( 0 );
		$zones[]       = [
			'zone_name'        => $rest_of_world->get_zone_name(),
			'shipping_methods' => $rest_of_world->get_shipping_methods( false, 'admin' ),
		];

		foreach ( $zones as $zone ) {
			$zone_name    = isset( $zone['zone_name'] ) ? (string) $zone['zone_name'] : '';
			$zone_methods = ( isset( $zone['shipping_methods'] ) && is_array( $zone['shipping_methods'] ) ) ? $zone['shipping_methods'] : [];

			foreach ( $zone_methods as $method ) {
				if ( ! is_object( $method ) || 'free_shipping' !== $method->id ) {
					continue;
				}

				// A disabled method can't deliver free shipping, so it doesn't count.
				if ( isset( $method->enabled ) && 'yes' !== $method->enabled ) {
					continue;
				}

				$methods[] = [
					'zone'       => $zone_name,
					'requires'   => isset( $method->requires ) ? (string) $method->requires : '',
					'min_amount' => isset( $method->min_amount ) ? (float) $method->min_amount : 0.0,
				];
			}
		}

		return $methods;
	}
}
