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

use Prodigy\Includes\Content\Prodigy_Request_Maker;
use Prodigy\Includes\Helpers\Prodigy_Cookies;
use Prodigy\Includes\Helpers\Prodigy_Url_Helper;
use Prodigy\includes\models\Prodigy_Order;
use Prodigy\Includes\Prodigy;
use Prodigy\Includes\Prodigy_Callback_Api_Listener;
use Prodigy\Includes\Prodigy_Cart;
use Prodigy\Includes\Prodigy_User;

require_once wp_normalize_path( ABSPATH ) . 'wp-load.php';
require_once ABSPATH . 'wp-includes/pluggable.php';
defined( 'ABSPATH' ) || exit;

/**
 * Class Prodigy_Page
 *
 * @package Prodigy\Includes\Frontend\Pages
 */
class Prodigy_Page {
	public const PRODIGY_CART_PAGE           = 'prodigy_cart_page_id';
	public const PRODIGY_SHOP_PAGE           = 'prodigy_shop_page_id';
	public const PRODIGY_THANK_PAGE          = 'prodigy_thank_page_id';
	public const PRODIGY_PAGE_STATUS_PUBLISH = 'publish';

	public const PAGE_TYPE_THANK = 'thank';
	public const PAGE_TYPE_CART  = 'cart';
	public const PAGE_TYPE_SHOP  = 'shop';


	/** @var Prodigy_Order $order_model */
	protected Prodigy_Order $order_model;

	/** @var string|null */
	protected ?string $user_session;

	/** @var string */
	protected $order_token;

	/** @var string */
	protected string $page_uri;

	/** @var Prodigy_Request_Maker  */
	protected Prodigy_Request_Maker $request_maker;

	/** @var Prodigy_Cart  */
	protected Prodigy_Cart $cart;

	/** @var Prodigy_Callback_Api_Listener  */
	protected Prodigy_Callback_Api_Listener $callback_api_listener;

	/**
	 * @var array|string[]
	 */
	public array $pages_list = array(
		'Thank you' => self::PAGE_TYPE_THANK,
		'Cart'      => self::PAGE_TYPE_CART,
		'Shop'      => self::PAGE_TYPE_SHOP,
	);


	/**
	 * @param Prodigy_Order                 $order_model
	 * @param Prodigy_Request_Maker         $request_maker
	 * @param Prodigy_Cart                  $cart
	 * @param Prodigy_Callback_Api_Listener $callback_api_listener
	 *
	 * @throws \Exception
	 */
	public function __construct(
		Prodigy_Order $order_model,
		Prodigy_Request_Maker $request_maker,
		Prodigy_Cart $cart,
		Prodigy_Callback_Api_Listener $callback_api_listener
	) {
		$this->callback_api_listener = $callback_api_listener;
		$this->cart                  = $cart;
		$this->order_model           = $order_model;
		$this->request_maker         = $request_maker;
		$this->user_session          = Prodigy_User::get_user_session();
		$this->order_token           = ! empty( $this->user_session ) ? $order_model->get_order_token( $this->user_session ) : null;
		$this->page_uri              = Prodigy_Url_Helper::prodigy_get_request_uri();

		add_action( 'wp_head', array( $this, 'myplugin_ajaxurl' ) );
		add_filter( 'wp_nav_menu_objects', array( $this, 'prodigy_brands_menu' ) );

		$this->set_redirect_dispatcher();
	}

	/**
	 * @throws \Exception
	 */
	public function set_redirect_dispatcher() {
		if ( substr_count(
			Prodigy_Url_Helper::prodigy_parse_request_uri(),
			'api-listener'
		) ) {
			$this->callback_api_listener->dispatch_url();
		}
	}

	/**
	 * @param array $menu_items
	 *
	 * @return array
	 */
	public function prodigy_brands_menu( array $menu_items ): array {
		$brand_slug = Prodigy_Url_Helper::get_brand_slug();
		if ( empty( $brand_slug ) ) {
			return $menu_items;
		}

		foreach ( $menu_items as $item ) {
			$taxonomy = Prodigy_Url_Helper::get_taxonomy_from_url( $item->url );
			if (
				$taxonomy === Prodigy::get_prodigy_category_slug() ||
				$taxonomy === Prodigy::get_prodigy_tag_slug()
			) {

				$item->url = add_query_arg(
					array(
						'brand' => $brand_slug,
					),
					$item->url
				);
			}
		}

		return $menu_items;
	}

	/**
	 * @param array $page_ids
	 *
	 * @return void
	 */
	public function prodigy_pages_update_options( array $page_ids ): void {
		foreach ( $this->pages_list as $key => $page ) {
			if ( isset( $page_ids[ $key ] ) ) {
				update_option( 'prodigy_' . $page . '_page_id', $page_ids[ $key ] );
			}
		}
	}

	/**
	 * @param string $page_name
	 *
	 * @return object|\WP_Post|null
	 */
	public function get_page_by_name( string $page_name ) {
		$prodigy_page_id = get_option( 'prodigy_' . $page_name . '_page_id' );

		return get_post( $prodigy_page_id );
	}

	/**
	 * @param array $prodigy_pages
	 * @return array
	 */
	public function create_pages( array $prodigy_pages ): array {
		$content_short_cart = false;
		$page_ids           = array();
		foreach ( $prodigy_pages as $page_data ) {
			$prodigy_page = $this->get_page_by_name( $page_data['name'] );
			if ( ! empty( $prodigy_page ) && in_array( $page_data['name'], array( self::PAGE_TYPE_CART, self::PAGE_TYPE_THANK ), true ) ) {
				$is_content = strpos( $prodigy_page->post_content, $page_data['content'] );
				if ( ! $is_content ) {
					$content_short_cart = true;
				}
			}

			if ( empty( $prodigy_page ) ) {
				$post_data = array(
					'post_content' => $page_data['content'] ?? '',
					'post_title'   => $page_data['title'] ?? '',
					'post_name'    => $page_data['name'] ?? '',
					'post_type'    => 'page',
					'post_status'  => self::PRODIGY_PAGE_STATUS_PUBLISH,
				);

				$post = wp_insert_post( $post_data, true );
				if ( is_wp_error( $post ) ) {
					echo esc_html( $post->get_error_message() );
				}
				$page_ids[ $post_data['post_title'] ] = $post;
			} elseif (
				isset( $prodigy_page->post_status ) &&
				$prodigy_page->post_status !== self::PRODIGY_PAGE_STATUS_PUBLISH
			) {
				$post_data = array(
					'ID'          => $prodigy_page->ID ?? '',
					'post_status' => self::PRODIGY_PAGE_STATUS_PUBLISH,
				);

				$post = wp_update_post( $post_data, true );
				if ( is_wp_error( $post ) ) {
					echo esc_html( $post->get_error_message() );
				}
			}

			if ( $content_short_cart && in_array( $page_data['name'], array( self::PAGE_TYPE_CART, self::PAGE_TYPE_THANK ), true ) ) {
				$post_data = array(
					'ID'           => $prodigy_page->ID ?? '',
					'post_content' => $page_data['content'] ?? '',
				);

				$post = wp_update_post( $post_data, true );
				if ( is_wp_error( $post ) ) {
					echo esc_html( $post->get_error_message() );
				}
			}

			if ( isset( $prodigy_page->post_title, $prodigy_page->ID ) ) {
				$page_ids[ $prodigy_page->post_title ] = $prodigy_page->ID;
			}
		}

		return $page_ids;
	}

	/**
	 *  Set ajaxurl path
	 */
	public function myplugin_ajaxurl() {
		echo '<script type="text/javascript">
           var ajaxurl = "' . esc_url( admin_url( 'admin-ajax.php' ) ) . '";
         </script>';
	}
}
