<?php

namespace Prodigy\Includes\Content;

use Prodigy\includes\helpers\Prodigy_Includes_Helper;

/**
 * Class responsible for parsing a list of products from a given response.
 * It processes product information and resolves relationships such as logos
 * and logo locations for a better-formed product list.
 */
class Prodigy_Products_List_Parser extends Prodigy_Main_Content {

	/**
	 * @var array
	 */
	private array $products_list_response;

	/**
	 * @var array
	 */
	private array $included_by_type;

	/**
	 * @param array $products_list_response
	 */
	public function __construct( array $products_list_response ) {
		parent::__construct();
		$this->products_list_response = $products_list_response;
		$this->included_by_type       = Prodigy_Includes_Helper::prepare_included_by_type( $products_list_response['included'] ?? array() );
	}

	/**
	 * @return array
	 */
	public function get_products(): array {
		$products = $this->products_list_response['data'] ?? array();

		foreach ( $products as &$product ) {
			$required_logos = array();

			$logo_option_ids = array_map(
				function ( $data_item ) {
					return $data_item['id'];
				},
				$product['relationships']['logo-options']['data'] ?? array()
			);
			foreach ( $logo_option_ids as $logo_option_id ) {
				$logo_option = $this->included_by_type['logo-options'][ $logo_option_id ] ?? null;
				$location_id = $logo_option['attributes']['logo-location-id'] ?? null;
				$logo_id     = $logo_option['attributes']['logo-id'] ?? null;
				if ( isset( $location_id ) && isset( $logo_id ) && ! isset( $required_logos[ $location_id ] ) ) {
					$location = $this->included_by_type['logo-locations'][ $location_id ] ?? null;
					$logo     = $this->included_by_type['logos'][ $logo_id ] ?? null;
					if ( $location === null || $logo === null ) {
						continue;
					}
					$required_logos[ $location_id ] = array(
						'logo-location' => $location['attributes'],
						'logo'          => $logo['attributes'],
					);
				}
			}
			$product['attributes']['required_logos'] = $required_logos;
		}

		return $products;
	}
}
