<?php
namespace Prodigy\Includes\Frontend\Mappers;

use Prodigy\Includes\Content\Prodigy_Order_Parser;
use Prodigy\Includes\Models\Prodigy_Products;
use Prodigy\Includes\Prodigy;
use Prodigy\Includes\Prodigy_Elementor_Template_Loader;

/**
 * Prodigy cart page data mapper
 *
 * @version    2.7.0
 * @package    Prodigy
 * @subpackage Prodigy/includes
 */
class Prodigy_Cart_Data_Mapper extends Prodigy_Main_Data_Mapper {
	const DEFAULT_ADD_TO_CART_MESSAGE = 'has been added to your cart.';

	/**
	 * @param array $options
	 *
	 * @return array
	 */
	public function get_default_parameters( array $options ): array {
		$cart_products = array();
		$cart_total    = 0.0;

		if ( isset( $this->order_token ) ) {
			$order_data         = $this->request_maker->do_order_request( $this->order_token );
			$order              = new Prodigy_Order_Parser( $order_data );
			$cart_items         = $order->get_line_items();
			$is_product_deleted = $order->is_order_item_deleted();
		}

		if ( ! empty( $cart_items ) ) {
			foreach ( $cart_items as $item ) {
				$remote_product_id = $item['attributes']['variant-id'];
				$line_item_id      = $item['id'] ?? $remote_product_id;
				$quantity          = $item['attributes']['quantity'];
				$actual_price      = $item['attributes']['price'];
				$item_total        = $item['attributes']['total'];
				$image_url         = $item['attributes']['image-url'];
				$name              = $item['attributes']['name'];

				$local_parent_product_info = Prodigy_Products::get_product_meta_by_remote_id( Prodigy::PRODIGY_REMOTE_PRODUCT_ID, (int) $item['attributes']['product-id'] );
				$local_parent_product_id   = $local_parent_product_info->post_id;
				$option_variants           = $item['attributes']['options'];

				$cart_products[ $line_item_id ]                            = $item;
				$cart_products[ $line_item_id ]['remote_product_id']       = $remote_product_id;
				$cart_products[ $line_item_id ]['count_items']             = $quantity;
				$cart_products[ $line_item_id ]['actual_price']            = $actual_price;
				$cart_products[ $line_item_id ]['total_price']             = $item_total;
				$cart_products[ $line_item_id ]['image_url']               = $image_url;
				$cart_products[ $line_item_id ]['name']                    = $name;
				$cart_products[ $line_item_id ]['local_parent_product_id'] = $local_parent_product_id;
				$cart_products[ $line_item_id ]['option_variants']         = $option_variants;
				$cart_products[ $line_item_id ]['logo_options']            = $this->apply_mlc_extra_charges_to_logos(
					$item['attributes']['logos'] ?? array(),
					(int) ( $item['attributes']['product-id'] ?? 0 )
				);

				$cart_total += $this->resolve_line_item_total( $item['attributes'] ?? array() );
			}
		}

		$customizer_general_options = get_option( 'prodigy_general_options' );

		return array(
			'heading_text'                 => $options['cart_style_heading_text'] ?? 'Shopping Cart',
			'empty_cart_text'              => $options['cart_style_empty_text'] ?? 'No products added yet',
			'cart_products'                => $cart_products ?? array(),
			'gallery_thumb'                => false,
			'is_dropdown'                  => $options['dropdown'] ?? true,
			'is_deleted_product'           => $is_product_deleted ?? false,
			'cart_widget_option'           => $customizer_general_options['prodigy_enable_cart_widget'] ?? false,
			'count_classname'              => $options['count_classname'] ?? 'prodigy-navbar-cart__count',
			'attr_shortcode'               => $options,
			'cart_icon_type'               => $options['cart_icon_type'] ?? '',
			'cart_content_icon_hide_empty' => $options['cart_content_icon_hide_empty'] ?? '',
			'container_class'              => $options['container_class'] ?? '',
			'add_to_cart_text'             => $options['cart_content_gen_add_cart_message_text'] ?? self::DEFAULT_ADD_TO_CART_MESSAGE,
			'is_elementor_header'          => Prodigy_Elementor_Template_Loader::is_include_header_template(),
			'cart_total'                   => $cart_total,
		);
	}

	/**
	 * Resolve line item total using total first, then price * quantity.
	 */
	private function resolve_line_item_total( array $attributes ): float {
		$total = $this->to_float_amount( $attributes['total'] ?? null );
		if ( $total > 0 ) {
			return $total;
		}

		$price    = $this->to_float_amount( $attributes['price'] ?? null );
		$quantity = isset( $attributes['quantity'] ) && is_numeric( $attributes['quantity'] )
			? (float) $attributes['quantity']
			: 0.0;

		return $price * $quantity;
	}

	/**
	 * Normalize numeric amount values from API payloads.
	 *
	 * @param mixed $value
	 *
	 * @return float
	 */
	private function to_float_amount( $value ): float {
		if ( is_numeric( $value ) ) {
			return (float) $value;
		}

		if ( ! is_string( $value ) ) {
			return 0.0;
		}

		$normalized = preg_replace( '/[^0-9.\-]/', '', str_replace( ',', '.', $value ) );

		return is_numeric( $normalized ) ? (float) $normalized : 0.0;
	}
}
