<?php
/**
 * Thank-you (order received) page recommendations.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Pages;

use PRECO\Includes\Frontend\Core\PageRecommendationsBase;

defined( 'ABSPATH' ) || exit;

/**
 * Thank-you (order received) page recommendations.
 */
class OrderPageRecommendations extends PageRecommendationsBase {

	/**
	 * Page key in option structure.
	 *
	 * @return string
	 */
	protected function page_key() {
		return 'thank-you';
	}

	/**
	 * Is the current request the relevant page?
	 *
	 * @return bool
	 */
	protected function is_active_page() {
		return function_exists( 'is_order_received_page' ) && \is_order_received_page();
	}

	/**
	 * Map of location key => hook definition.
	 *
	 * @return array
	 */
	protected function locations() {
		return array(
			'after-order-details' => array(
				'hook'          => 'woocommerce_order_details_after_order_table',
				'priority'      => 10,
				'accepted_args' => 1,
			),
		);
	}

	/**
	 * Build context for rule evaluation.
	 *
	 * @param string $location_key Location key.
	 * @param array  $hook_args Hook args.
	 * @return array
	 */
	protected function build_context( $location_key, $hook_args ) {
		$order    = null;
		$order_id = 0;
		if ( ! empty( $hook_args ) ) {
			$maybe_order = $hook_args[0];
			if ( is_numeric( $maybe_order ) ) {
				$order_id = absint( $maybe_order );
				$order    = function_exists( 'wc_get_order' ) ? \wc_get_order( $order_id ) : null;
			} elseif ( is_object( $maybe_order ) && method_exists( $maybe_order, 'get_id' ) ) {
				$order    = $maybe_order;
				$order_id = absint( $order->get_id() );
			}
		}

		$exclude_ids = array();
		if ( $order && method_exists( $order, 'get_items' ) ) {
			foreach ( $order->get_items() as $item ) {
				if ( $item && method_exists( $item, 'get_product_id' ) ) {
					$exclude_ids[] = absint( $item->get_product_id() );
				}
			}
		}

		return array(
			'page'         => $this->page_key(),
			'location_key' => (string) $location_key,
			'order_id'     => $order_id,
			'exclude_ids'  => array_values( array_unique( array_filter( $exclude_ids ) ) ),
		);
	}
}
