<?php
/**
 * The main class blocks settings page.
 *
 * @package Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/admin/blocks-settings
 */

if ( ! defined( 'ABSPATH' ) ) {
	die;
} // Cannot access pages directly.

/**
 * Smart Post Show Pro blocks API Page.
 */
class Builder_Api {

	/**
	 * Smart Post Show Pro single instance of the class
	 *
	 * @var null The instance of the class.
	 * @since 2.0
	 *
	 * @return void
	 */
	protected static $instance = null;

	/**
	 * Main Builder Api Instance
	 *
	 * @since 2.0
	 * @static
	 *
	 * @return self help instance
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Single pre made data and insert builder post.
	 *
	 * @param string $type The type of template to create.
	 * @param string $body ( Optional ) The content of the post.
	 * @return int The ID of the newly created post.
	 */
	public static function set_post_content( $type, $body = '' ) {
		$post_id = wp_insert_post(
			array(
				'post_title'   => ucfirst( $type ) . ' Template',
				'post_content' => $body,
				'post_type'    => 'sp_smart_builder',
				'post_status'  => 'draft',
			)
		);

		update_post_meta( $post_id, '__spc_builder_type', $type );
		$settings = get_option( 'sp_builder_conditions', array() );

		switch ( $type ) {
			case 'single_page':
				update_post_meta( $post_id, '__spc_builder_type', 'single_page' );
				$settings['single_page'][ $post_id ] = array( 'include/single_page/post' );
				break;
			case 'home_page':
				update_post_meta( $post_id, '__spc_builder_type', 'home_page' );
				$settings['home_page'][ $post_id ] = array( 'include/home_page' );
				break;
			case 'blog_page':
				update_post_meta( $post_id, '__spc_builder_type', 'blog_page' );
				$settings['blog_page'][ $post_id ] = array( 'include/blog_page' );
				break;
			case 'authors':
			case 'post_tag':
			case 'date':
			case 'search':
			case 'archive':
			case 'category':
				update_post_meta( $post_id, '__spc_builder_type', 'archive' );
				$extra                           = 'archive' !== $type ? '/' . $type : '';
				$settings['archive'][ $post_id ] = array( 'include/archive' . $extra );
				break;
			case 'header':
				update_post_meta( $post_id, '__spc_builder_type', 'header' );
				$settings['header'][ $post_id ] = array( 'include/header/entire_site' );
				break;
			case 'footer':
				update_post_meta( $post_id, '__spc_builder_type', 'footer' );
				$settings['footer'][ $post_id ] = array( 'include/footer/entire_site' );
				break;
			case '404':
				update_post_meta( $post_id, '__spc_builder_type', '404' );
				$settings['404'][ $post_id ] = array( 'include/404' );
				break;
			default:
				break;
		}

		update_option( 'sp_builder_conditions', $settings );
		return $post_id;
	}

	/**
	 * Get current template id.
	 *
	 * @param string $type Check for return you want single id or all template list ids.
	 * @return integer
	 */
	public static function get_builder_template_id( $type = 'id' ) {

		$template_post_ids = get_posts(
			array(
				'post_type'      => 'sp_smart_builder',
				'posts_per_page' => 9999,
				'fields'         => 'ids',
				'post_status'    => 'any',
				'orderby'        => 'ID',
				'order'          => 'DESC',
			)
		);

		$page_id           = '';
		$template_details  = array();
		$load_archive_page = true;

		$all_conditions = get_option( 'sp_builder_conditions', array() );

		$current_post_id = get_the_ID();

		foreach ( $template_post_ids as $id ) {

			$post_type = get_post_meta( $id, '__spc_builder_type', true );

			$template_details[] = array(
				'title'     => get_the_title( $id ),
				'type'      => $post_type,
				'id'        => $id,
				'temStatus' => 'publish' === get_post_status( $id ) ? true : false,
			);

			if ( 'publish' !== get_post_status( $id ) ) {
				continue;
			}

			// ==============================
			// HEADER / FOOTER
			// ==============================
			if ( 'header' === $type || 'footer' === $type ) {
				if ( $type === $post_type ) {

					if ( ! empty( $all_conditions[ $type ][ $id ] ) ) {

						$queried_id  = get_queried_object_id();
						$term        = get_queried_object();
						$current_cat = (int) ( $term->term_id ?? '' );

						foreach ( $all_conditions[ $type ][ $id ] as $rule ) {

							$parts     = explode( '/', $rule );
							$action    = $parts[0] ?? '';
							$target    = $parts[1] ?? '';
							$value     = (int) ( $parts[2] ?? '' );
							$post_type = get_post_type( $value );

							if ( $post_type === $target && ! empty( $value ) && ! is_archive() ) {
								if ( 'exclude' === $action ) {
									if ( $post_type === $target && (int) $value !== (int) $current_post_id ) {
										$page_id = $id;
										break;
									}
								} elseif ( $post_type === $target && (int) $value === (int) $current_post_id ) {
									$page_id = $id;
									break;
								}
							}

							if ( 'exclude' === $action ) {
								if ( (int) $value !== (int) $queried_id ) {
									$page_id = $id;
								}
							} elseif ( (int) $value === (int) $queried_id ) {
								$page_id = $id;
							}

							// Specific category ID match .
							if ( isset( $term->taxonomy ) && $term->taxonomy === $target && $value > 0 ) {

								if ( 'exclude' === $action ) {
									if ( $current_cat !== $value ) {
										$page_id = $id;
										break;
									}
								} elseif ( $current_cat === $value ) {
									$page_id = $id;
									break;
								}
							}

							if ( isset( $term->taxonomy ) && "child_of_$term->taxonomy" === $target ) {

								$parent_id = (int) $term->parent;

								if ( 'exclude' === $action ) {
									if ( $parent_id !== (int) $value ) {
										$page_id = $id;
										break;
									}
								} elseif ( $parent_id === (int) $value ) {
									$page_id = $id;
									break;
								}
							}

							if ( isset( $term->taxonomy ) && "any_child_of_$term->taxonomy" === $target && $value > 0 ) {

								$current_cat = (int) get_queried_object_id();

								if ( 'exclude' === $action ) {
									if ( term_is_ancestor_of( $value, $current_cat, $term->taxonomy ) ) {

										$page_id = $id;
										break;
									}
								} elseif ( ! term_is_ancestor_of( $value, $current_cat, $term->taxonomy ) ) {

									$page_id = $id;
									break;
								}
							}

							if ( isset( $term->taxonomy ) && $term->taxonomy === $target && empty( $value ) ) {
								$page_id = $id;
							}
						}
					} else {
						$page_id = $id;
					}
				}
				continue;
			}

			// ==============================
			// FRONT PAGE
			// ==============================
			if ( 'home_page' === $post_type && is_front_page() ) {
				$page_id = $id;
			}

			// ==============================
			// BLOG PAGE
			// ==============================
			if ( 'blog_page' === $post_type && is_home() ) {
				$page_id = $id;
				break;
			}

			// ==============================
			// SINGLE PAGE
			// ==============================
			if ( 'single_page' === $post_type && is_singular() && ! is_front_page() ) {

				if ( ! empty( $all_conditions['single_page'][ $id ] ) ) {

					foreach ( $all_conditions['single_page'][ $id ] as $rule ) {

						$parts  = explode( '/', $rule );
						$action = $parts[0] ?? '';
						$target = $parts[1] ?? '';
						$value  = (int) ( $parts[2] ?? '' );

						$post_type = get_post_type( $value );

						if ( 'exclude' === $action ) {
							if ( $post_type === $target && (int) $value !== (int) $current_post_id ) {
								$page_id = $id;
								break;
							}
						} elseif ( $post_type === $target && (int) $value === (int) $current_post_id ) {
							$page_id = $id;
							break;
						} elseif ( $post_type === $target && empty( $value ) ) {
							$page_id = $id;
							break;
						}
					}
				} else {
					$page_id = $id;
				}
			}

			if ( 'archive' === $post_type && is_archive() ) {

				$author_id   = get_queried_object_id();
				$term        = get_queried_object();
				$current_cat = (int) $term->term_id;

				if ( ! empty( $all_conditions['archive'][ $id ] ) ) {

					foreach ( $all_conditions['archive'][ $id ] as $rule ) {

						$parts  = explode( '/', $rule );
						$action = $parts[0] ?? '';
						$target = $parts[1] ?? '';
						$value  = (int) ( $parts[2] ?? '' );

						if ( 'author' === $target ) {
							if ( 'exclude' === $action ) {
								if ( (int) $value !== (int) $author_id ) {
									$page_id = $id;
								}
							} elseif ( (int) $value === (int) $author_id ) {
								$page_id = $id;
							}
						}

						// Specific category ID match .
						if ( $term->taxonomy === $target && $value > 0 ) {

							if ( 'exclude' === $action ) {
								if ( $current_cat !== $value ) {
									$page_id = $id;
									break;
								}
							} elseif ( $current_cat === $value ) {
								$page_id = $id;
								break;
							}
						}

						if ( "child_of_$term->taxonomy" === $target ) {

							$parent_id = (int) $term->parent;

							if ( 'exclude' === $action ) {
								if ( $parent_id !== (int) $value ) {
									$page_id = $id;
									break;
								}
							} elseif ( $parent_id === (int) $value ) {
								$page_id = $id;
								break;
							}
						}

						if ( "any_child_of_$term->taxonomy" === $target && $value > 0 ) {

							$current_cat = (int) get_queried_object_id();

							if ( 'exclude' === $action ) {
								if ( term_is_ancestor_of( $value, $current_cat, $term->taxonomy ) ) {

									$page_id = $id;
									break;
								}
							} elseif ( ! term_is_ancestor_of( $value, $current_cat, $term->taxonomy ) ) {

								$page_id = $id;
								break;
							}
						}

						if ( $term->taxonomy === $target && empty( $value ) ) {
								$page_id = $id;
						}
					}
				} else {
					$page_id = $id;
				}
			}

			// ==============================
			// CATEGORY
			// ==============================
			if ( 'category' === $post_type && is_category() ) {

				if ( ! empty( $all_conditions['category'][ $id ] ) ) {

					$term        = get_queried_object();
					$current_cat = (int) $term->term_id;

					$include_match = false;
					$exclude_match = false;

					foreach ( $all_conditions['category'][ $id ] as $rule ) {

						$parts  = explode( '/', $rule );
						$action = $parts[0] ?? '';
						$target = $parts[1] ?? '';
						$value  = (int) ( $parts[2] ?? 0 );

						// Specific category ID match .
						if ( $term->taxonomy === $target && $value > 0 ) {

							if ( 'exclude' === $action ) {
								if ( $current_cat !== $value ) {
									$page_id = $id;
									break;
								}
							} elseif ( $current_cat === $value ) {
								$page_id = $id;
								break;
							}
						}

						if ( "child_of_$term->taxonomy" === $target ) {

							$parent_id = (int) $term->parent;

							if ( 'exclude' === $action ) {
								if ( $parent_id !== (int) $value ) {
									$page_id = $id;
									break;
								}
							} elseif ( $parent_id === (int) $value ) {
								$page_id = $id;
								break;
							}
						}

						if ( "any_child_of_$term->taxonomy" === $target && $value > 0 ) {

							$current_cat = (int) get_queried_object_id();

							if ( 'exclude' === $action ) {
								if ( ! term_is_ancestor_of( $value, $current_cat, 'category' ) ) {

									$page_id = $id;
									break;
								}
							} elseif ( term_is_ancestor_of( $value, $current_cat, 'category' ) ) {

								$page_id = $id;
								break;
							}
						}

						if ( $term->taxonomy === $target && empty( $value ) ) {
							$page_id = $id;
						}
					}
				} else {
					$page_id = $id;
				}
			}

			// ==============================
			// TAG
			// ==============================
			if ( 'post_tag' === $post_type && is_tag() ) {

				$tag_id = get_queried_object_id();

				if ( ! empty( $all_conditions['post_tag'][ $id ] ) ) {

					foreach ( $all_conditions['post_tag'][ $id ] as $rule ) {

						$parts  = explode( '/', $rule );
						$action = $parts[0] ?? '';
						$value  = $parts[2] ?? '';

						if ( 'exclude' === $action ) {
							if ( (int) $value !== (int) $tag_id ) {
								$page_id = $id;
							}
						} elseif ( (int) $value === (int) $tag_id ) {
							$page_id = $id;
						}
					}
				} else {
					$page_id = $id;
				}
			}

			// ==============================
			// AUTHOR
			// ==============================
			if ( 'authors' === $post_type && is_author() ) {

				$author_id = get_queried_object_id();

				if ( ! empty( $all_conditions['authors'][ $id ] ) ) {

					foreach ( $all_conditions['authors'][ $id ] as $rule ) {

						$parts  = explode( '/', $rule );
						$action = $parts[0] ?? '';
						$value  = (int) ( $parts[2] ?? '' );

						if ( 'exclude' === $action ) {
							if ( (int) $value !== (int) $author_id ) {
								$page_id = $id;
							}
						} elseif ( (int) $value === (int) $author_id ) {
							$page_id = $id;
						}
					}
				} else {
					$page_id = $id;
				}
			}

			// ==============================
			// 404 Page
			// ==============================
			if ( '404' === $post_type && is_404() ) {
				$page_id = $id;
			}
		}

		return 'all' === $type ? $template_details : $page_id;
	}
}
