<?php

namespace FinchCart\Admin\Edith\includes\ShortcodeBuilder;

use function FinchCart\Admin\Edith\includes\edith_kses_allowed_svg;

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

/**
 * Shortcode Builder Options Class
 */
class ShortCodeBuilderPostTypeOptions {

	/**
	 * SVG icons for the builder
	 *
	 * @var array
	 */
	public $svg_icons = array(
		'shortcode'  => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>',
		'left_arrow' => '<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" viewBox="0 0 24 24" fill="none" stroke="#495057" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>',
	);

	/**
	 * The unique id of each shortcode builder.
	 *
	 * @var string
	 */
	public $unique = '';

	/**
	 * The shortcode builder parameters array.
	 *
	 * @var array
	 */
	public $args = array(
		'menu_type'   => 'menu', // or submenu.
		'parent_slug' => 'options-general.php', // for submenu only.
		'defaults'    => array(),
		'options'     => array(),
	);

	/**
	 * Class Constructor
	 *
	 * @param atring $key The unique id of each shortcode builder.
	 * @param array  $params The shortcode builder parameters array.
	 */
	public function __construct( $key, $params ) {
		$this->unique = $key;
		$this->args   = apply_filters( "edith_{$this->unique}_args", wp_parse_args( $params['args'], $this->args ), $this );

		add_action( 'admin_init', array( $this, 'register_shortcode_post_type' ) );
		add_action( 'admin_init', array( $this, 'remove_side_meta' ) );
		add_filter( 'admin_body_class', array( $this, 'add_admin_body_classes' ) );
		add_filter( 'screen_options_show_screen', array( $this, 'remove_screen_options' ), 10, 2 );
		add_action( 'admin_head', array( $this, 'admin_admin_footer_items' ) );
		add_action( 'edit_form_after_title', array( $this, 'edit_shortcode_header' ) );
		add_filter( "get_user_option_screen_layout_{$this->args['post_type']}", array( $this, 'edit_shortcodes_page_column' ) );
		add_filter( 'post_updated_messages', array( $this, 'shortcodes_post_updated_messages' ) );
	}

	/**
	 * ShortCode Builder Instance
	 *
	 * @param atring $key The unique id of each shortcode builder.
	 * @param array  $params The shortcode builder parameters array.
	 * @return mixed
	 */
	public static function instance( $key, $params ) {
		return new self( $key, $params );
	}

	/**
	 * CSS classes for the body tag in the admin.
	 *
	 * @param string $classes Space-separated list of CSS classes.
	 * @return string
	 */
	public function add_admin_body_classes( $classes ) {
		$args     = $this->args;
		$wpscreen = get_current_screen();

		if ( isset( $wpscreen->post_type ) && 'post' === $wpscreen->base && $args['post_type'] === $wpscreen->post_type ) {
			$classes .= ' edith_shortcode_edit_page';
		}

		return $classes;
	}

	/**
	 * Register post type for the shortcode builder.
	 *
	 * @return void
	 */
	public function register_shortcode_post_type() {

		$args = $this->args;

		if ( isset( $args['post_type'] ) ) {
			$shortcode_args = array(
				'label'              => esc_html( $args['post_type_label'] ? $args['post_type_label'] : $args['menu_title'] ),
				'supports'           => array( 'title' ),
				'hierarchical'       => false,
				'public'             => false,
				'show_ui'            => true,
				'show_in_menu'       => ( 'menu' === $args['menu_type'] ? $args['menu_slug'] : $args['parent_slug'] ),
				'publicly_queryable' => false, // disable single post view.
				'capability_type'    => 'page',
				'show_in_rest'       => true,
			);

			register_post_type( $args['post_type'], $shortcode_args );
		}
	}

	/**
	 * Remove Custom Post Type Publish Metabox
	 *
	 * @return void
	 */
	public function remove_side_meta() {
		$args = $this->args;
		remove_meta_box( 'submitdiv', $args['post_type'], 'side' );
	}

	/**
	 * Remove Screen Options
	 *
	 * @param bool   $show_screen Whether to show Screen Options tab.
	 * @param object $screen Current WP_Screen instance.
	 * @return boolean
	 */
	public function remove_screen_options( $show_screen, $screen ) {
		$args = $this->args;

		if ( isset( $screen->post_type ) && 'post' === $screen->base && $args['post_type'] === $screen->post_type ) {
			$show_screen = false;
		}
		return $show_screen;
	}

	/**
	 * Remove admin footer items
	 */
	public function admin_admin_footer_items() {
		$args   = $this->args;
		$screen = get_current_screen();

		if ( isset( $screen->post_type ) && 'post' === $screen->base && $args['post_type'] === $screen->post_type ) {
			remove_filter( 'update_footer', 'core_update_footer' );
			add_filter( 'admin_footer_text', '__return_false' );
		}
	}

	/**
	 * CPT Change Default Layout to 1 column
	 *
	 * @param init $result Number of columns.
	 * @return init
	 */
	public function edit_shortcodes_page_column( $result ) {
		$result = 1;
		return $result;
	}

	/**
	 * ShortCode CPT post update messages
	 *
	 * @param array $messages Post updated messages. For defaults see $messages declarations above.
	 * @return array
	 */
	public function shortcodes_post_updated_messages( $messages ) {
		$args            = $this->args;
		$post_type       = $args['post_type'];
		$post_type_label = ( isset( $args['post_type_label'] ) ? $args['post_type_label'] : $post_type );

		$messages[ $post_type ][1] = esc_html( $post_type_label ) . esc_html__( ' updated.', 'finch-cart-product-recommendations' );
		$messages[ $post_type ][6] = esc_html( $post_type_label ) . esc_html__( ' published.', 'finch-cart-product-recommendations' );

		return $messages;
	}

	/**
	 * Edit shortcode CPT custom header
	 *
	 * @param object $post Post object.
	 * @return mixed
	 */
	public function edit_shortcode_header( $post ) {
		$args             = $this->args;
		$post_id          = (int) $post->ID;
		$post_type        = $post->post_type;
		$post_type_object = get_post_type_object( $post_type );
		$can_publish      = current_user_can( $post_type_object->cap->publish_posts );

		if ( get_post_type( $post ) === $args['post_type'] ) {

			if ( 'menu' === $args['menu_type'] ) {
				$back_btn_url = add_query_arg( array( 'page' => $args['menu_slug'] ), admin_url( 'admin.php' ) );
			} elseif ( 'submenu' === $args['menu_type'] ) {
				$back_btn_url = add_query_arg( array( 'page' => $args['menu_slug'] ), admin_url( $args['parent_slug'] ) );
			}
			?>
				
				<div class="edith-shortcode-back-button">
					<a class="button" href="<?php echo esc_url( $back_btn_url ); ?>">
						<?php echo wp_kses( $this->svg_icons['left_arrow'], edith_kses_allowed_svg() ); ?>
					</a>
				</div>
				<div class="edith-shortcode-post-action-buttons">
					<div class="submitbox" id="submitpost">
						<div id="publishing-action">
							<span class="spinner"></span>
							<?php
							if ( ! in_array( $post->post_status, array( 'publish', 'future', 'private' ), true ) || 0 === $post_id ) {
								if ( $can_publish ) :
									if ( ! empty( $post->post_date_gmt ) && time() < strtotime( $post->post_date_gmt . ' +0000' ) ) :
										?>
										<input name="original_publish" type="hidden" id="original_publish" value="<?php echo esc_attr_x( 'Schedule', 'post action/button label', 'finch-cart-product-recommendations' ); ?>" />
										<?php submit_button( esc_html_x( 'Schedule', 'post action/button label', 'finch-cart-product-recommendations' ), 'primary large', 'publish', false ); ?>
										<?php
									else :
										?>
										<input name="original_publish" type="hidden" id="original_publish" value="<?php esc_attr_e( 'Publish', 'finch-cart-product-recommendations' ); ?>" />
										<?php submit_button( esc_html__( 'Publish', 'finch-cart-product-recommendations' ), 'primary large', 'publish', false ); ?>
										<?php
									endif;
								else :
									?>
									<input name="original_publish" type="hidden" id="original_publish" value="<?php esc_attr_e( 'Submit for Review', 'finch-cart-product-recommendations' ); ?>" />
									<?php submit_button( esc_html__( 'Submit for Review', 'finch-cart-product-recommendations' ), 'primary large', 'publish', false ); ?>
									<?php
								endif;
							} else {
								?>
								<button class="button edith-shortcode-popup-trigger" data-id="<?php echo esc_attr( $post_id ); ?>" data-nonce="<?php echo esc_attr( wp_create_nonce( 'edith_shortcode_popup_nonce_' . esc_attr( $post_id ) ) ); ?>">
									<?php echo wp_kses( $this->svg_icons['shortcode'], edith_kses_allowed_svg() ); ?>
									<?php echo esc_html__( 'ShortCode', 'finch-cart-product-recommendations' ); ?>
								</button>
								<input name="original_publish" type="hidden" id="original_publish" value="<?php esc_attr_e( 'Update', 'finch-cart-product-recommendations' ); ?>" />
								<?php submit_button( esc_html__( 'Update', 'finch-cart-product-recommendations' ), 'primary large', 'save', false, array( 'id' => 'publish' ) ); ?>
								<?php
							}
							?>
						</div>
					</div>
				</div>
			<?php
		}
	}
}
