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

use Prodigy\Includes\Content\Prodigy_Request_Maker;
use Prodigy\Includes\Frontend\Cart_Error_Handler;
use Prodigy\Includes\Helpers\Prodigy_Logger;
use Prodigy\includes\models\Prodigy_Order;
use Prodigy\Includes\Prodigy_Cache;
use Prodigy\Includes\Prodigy_Cart;
use Prodigy\Includes\Prodigy_User;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Prodigy cart shortcode class
 *
 * @version    2.7.0
 * @package    Prodigy
 * @subpackage Prodigy/includes
 */
class Prodigy_Short_Code_Cart {

	/**
	 * Shortcode name
	 *
	 * @var string
	 */
	const NAME = 'prodigy_cart_widget';

	/**
	 * @var Prodigy_Cache
	 */
	public Prodigy_Cache $cache;

	/** @var Prodigy_User */
	public Prodigy_User $user;

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

	/**
	 * String to bool mapper
	 *
	 * @var array
	 */
	public array $cart_dropdown_mapper = array(
		'false' => false,
		'true'  => true,
	);

	/**
	 * Set hooks
	 *
	 * @throws \Exception
	 */
	public function __construct() {
		$this->cache = new Prodigy_Cache();
		$this->user  = new Prodigy_User();
		$this->cart  = new Prodigy_Cart(
			Prodigy_Request_Maker::get_instance(),
			new Prodigy_Order(),
			new Cart_Error_Handler()
		);
		add_action( 'wp_ajax_prodigy-get-checkout-url', array( $this, 'prodigy_generate_checkout_url' ) );
		add_action( 'wp_ajax_nopriv_prodigy-get-checkout-url', array( $this, 'prodigy_generate_checkout_url' ) );

		add_shortcode( self::NAME, array( $this, 'output' ) );
	}


	/**
	 * @throws \Exception
	 */
	public function prodigy_generate_checkout_url(): void {
		$cart_cookie = Prodigy_User::get_user_session();
		if ( ! empty( $cart_cookie ) ) {
			$prodigy_user = htmlspecialchars( $cart_cookie, ENT_QUOTES );
		}

		$order_token = ( new Prodigy_Order() )->get_order_token( $prodigy_user ?? '' );

		$external_checkout_id = Prodigy_User::get_external_checkout_id();
		if ( $external_checkout_id !== null && ! empty( $order_token ) ) {
			if ( PRODIGY_DEBUG_MODE ) {
				Prodigy_Logger::add_record(
					Prodigy_Logger::TYPE_INFO,
					'Starting external checkout flow',
					'prodigy-cart-shortcode',
					wp_json_encode(
						array(
							'external_checkout_id' => $external_checkout_id,
							'order_token'          => $order_token,
						)
					)
				);
			}
			$response = Prodigy_Request_Maker::get_instance()->do_external_checkout_request(
				$order_token,
				$external_checkout_id
			);
			if ( ! empty( $response['error'] ) ) {
				if ( PRODIGY_DEBUG_MODE ) {
					Prodigy_Logger::add_record(
						Prodigy_Logger::TYPE_ERROR,
						'External checkout flow failed',
						'prodigy-cart-shortcode',
						wp_json_encode(
							array(
								'external_checkout_id' => $external_checkout_id,
								'order_token'          => $order_token,
								'response_code'        => $response['code'] ?? null,
								'error'                => is_string( $response['error'] ?? null ) ? $response['error'] : 'non-string error',
							)
						)
					);
				}
				$error = $response['error'];

				$message = __( 'Unable to start external checkout. Please try again.', 'prodigy-commerce' );
				if ( is_string( $error ) ) {
					$message = $error;
				} elseif ( is_object( $error ) && method_exists( $error, 'get_error_message' ) ) {
					$message = $error->get_error_message();
				}

				wp_send_json_error(
					array(
						'message' => $message,
					),
					(int) ( $response['code'] ?? \WP_Http::INTERNAL_SERVER_ERROR )
				);
			}

			$checkout_url = $response['checkout_url'] ?? null;
			if ( ! is_string( $checkout_url ) || $checkout_url === '' ) {
				if ( PRODIGY_DEBUG_MODE ) {
					Prodigy_Logger::add_record(
						Prodigy_Logger::TYPE_ERROR,
						'External checkout flow missing checkout_url',
						'prodigy-cart-shortcode',
						wp_json_encode(
							array(
								'external_checkout_id' => $external_checkout_id,
								'order_token'          => $order_token,
								'response_code'        => $response['code'] ?? null,
							)
						)
					);
				}
				wp_send_json_error(
					array(
						'message' => __( 'Unable to start external checkout. Please try again.', 'prodigy-commerce' ),
					),
					(int) ( $response['code'] ?? \WP_Http::INTERNAL_SERVER_ERROR )
				);
			}

			wp_send_json_success(
				array(
					'checkout_url' => $checkout_url,
				)
			);
		} else {
			$order                   = Prodigy_Order::get_order_number( $order_token );
			$options['checkout_url'] = Prodigy_Cart::get_checkout_url( $order, $order_token );
			wp_send_json_success( $options );
		}
	}

	/**
	 * @param array $atts
	 *
	 * @return array
	 */
	public function set_widget_parameters( $atts ): array {
		$params = array();
		if ( isset( $atts['dropdown'] ) ) {
			$params['dropdown'] = $this->cart_dropdown_mapper[ $atts['dropdown'] ];
		}
		return $params;
	}

	/**
	 * @param array $atts
	 *
	 * @return void
	 */
	public function render_view( array $atts ): void {
		ob_start();
		do_action( 'prodigy_shortcode_template_cart', $atts );
		wp_reset_postdata();
	}

	/**
	 * @param $atts
	 *
	 * @return false|string
	 */
	public function output( $atts ) {
		$attr = $this->set_widget_parameters( $atts );
		$this->render_view( $attr );

		return ob_get_clean();
	}
}
