<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class Ecafe_Theme_Builder {

	public static $instance = null;
	protected $singular_template;

	const Ecafe_Type      = ECAFE_POST;
	const Ecafe_Shortcode = 'ecafe-builder';

	public $taxonomies_list = array();
	public static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'wp', array( $this, 'ec_load_templates' ) );
		add_action( 'init', array( $this, 'ec_template_builder_post_type' ), 0 );
		add_action( 'admin_menu', array( $this, 'ec_change_menu_post_type' ), 9 );

		add_action( 'manage_' . self::Ecafe_Type . '_posts_columns', array( __CLASS__, 'ec_admin_columns_headers' ) );
		add_action( 'manage_' . self::Ecafe_Type . '_posts_custom_column', array( $this, 'ec_admin_columns_text' ), 10, 2 );

		add_action( 'wp_ajax_ecafe_get_prev_list', array( $this, 'ec_get_prev_list_callback' ) );
		add_action( 'add_meta_boxes', array( $this, 'ec_builder_condition_meta' ) );
		add_action( 'save_post', array( $this, 'ec_builder_condition_save_meta' ) );

		add_filter( 'template_include', array( $this, 'ecafe_single_template_overright' ), 1000 );
		add_action( 'ecafe_content_render', array( $this, 'ec_singular_archives_content_render' ), 1000 );

		if ( is_admin() ) {
			add_action( 'manage_' . self::Ecafe_Type . '_posts_columns', array( $this, 'ec_admin_columns_shortcode' ), 15 );
			add_action( 'manage_' . self::Ecafe_Type . '_posts_custom_column', array( $this, 'ec_admin_columns_shortcode_content' ), 15, 2 );
		}

		add_shortcode( self::Ecafe_Shortcode, array( $this, 'ec_create_shortcode' ) );
	}

	public function ec_template_builder_post_type() {
		$labels = array(
			'name'                  => _x( 'Theme Builder', 'Post Type General Name', 'essential-classy-addons-for-elementor' ),
			'singular_name'         => _x( 'Theme Builder', 'Post Type Singular Name', 'essential-classy-addons-for-elementor' ),
			'menu_name'             => _x( 'Theme Builder', 'Admin Menu text', 'essential-classy-addons-for-elementor' ),
			'name_admin_bar'        => _x( 'Theme Builder', 'Add New on Toolbar', 'essential-classy-addons-for-elementor' ),
			'archives'              => __( 'Theme Builder Archives', 'essential-classy-addons-for-elementor' ),
			'attributes'            => __( 'Theme Builder Attributes', 'essential-classy-addons-for-elementor' ),
			'parent_item_colon'     => __( 'Parent Theme Builder:', 'essential-classy-addons-for-elementor' ),
			'all_items'             => __( 'All Theme Builder', 'essential-classy-addons-for-elementor' ),
			'add_new_item'          => __( 'Add New Theme Builder', 'essential-classy-addons-for-elementor' ),
			'add_new'               => __( 'Add New', 'essential-classy-addons-for-elementor' ),
			'new_item'              => __( 'New Theme Builder', 'essential-classy-addons-for-elementor' ),
			'edit_item'             => __( 'Edit Theme Builder', 'essential-classy-addons-for-elementor' ),
			'update_item'           => __( 'Update Theme Builder', 'essential-classy-addons-for-elementor' ),
			'view_item'             => __( 'View Theme Builder', 'essential-classy-addons-for-elementor' ),
			'view_items'            => __( 'View Theme Builder', 'essential-classy-addons-for-elementor' ),
			'search_items'          => __( 'Search Theme Builder', 'essential-classy-addons-for-elementor' ),
			'not_found'             => __( 'Not found', 'essential-classy-addons-for-elementor' ),
			'not_found_in_trash'    => __( 'Not found in Trash', 'essential-classy-addons-for-elementor' ),
			'featured_image'        => __( 'Featured Image', 'essential-classy-addons-for-elementor' ),
			'set_featured_image'    => __( 'Set featured image', 'essential-classy-addons-for-elementor' ),
			'remove_featured_image' => __( 'Remove featured image', 'essential-classy-addons-for-elementor' ),
			'use_featured_image'    => __( 'Use as featured image', 'essential-classy-addons-for-elementor' ),
			'insert_into_item'      => __( 'Insert into Theme Builder', 'essential-classy-addons-for-elementor' ),
			'uploaded_to_this_item' => __( 'Uploaded to this Theme Builder', 'essential-classy-addons-for-elementor' ),
			'items_list'            => __( 'Theme Builder list', 'essential-classy-addons-for-elementor' ),
			'items_list_navigation' => __( 'Theme Builder list navigation', 'essential-classy-addons-for-elementor' ),
			'filter_items_list'     => __( 'Filter Theme Builder list', 'essential-classy-addons-for-elementor' ),
		);
		$args   = array(
			'label'               => __( 'Theme Builder', 'essential-classy-addons-for-elementor' ),
			'description'         => __( 'Description', 'essential-classy-addons-for-elementor' ),
			'labels'              => $labels,
			'supports'            => array( 'title', 'editor', 'revisions', 'elementor' ),
			'taxonomies'          => array(),
			'public'              => true,
			'show_ui'             => true,
			'show_in_menu'        => false,
			'show_in_admin_bar'   => false,
			'show_in_nav_menus'   => false,
			'can_export'          => true,
			'has_archive'         => false,
			'hierarchical'        => false,
			'exclude_from_search' => true,
			'capability_type'     => 'post',
			'rewrite'             => false,
			'query_var'           => false,
			'map_meta_cap'        => true,
			'show_in_rest'        => true,
		);
		register_post_type( self::Ecafe_Type, $args );
	}

	public function ec_change_menu_post_type() {
		add_submenu_page(
			'ecafe_welcome',
			__( 'Theme Builder', 'essential-classy-addons-for-elementor' ),
			__( 'Theme Builder', 'essential-classy-addons-for-elementor' ),
			'manage_options',
			'edit.php?post_type=' . sanitize_text_field( self::Ecafe_Type ),
			false
		);
	}

	public static function ec_admin_columns_headers( $posts_columns ) {
		$offset = 2;

		$posts_columns = array_slice( $posts_columns, 0, $offset, true ) + array(
			'type' => __( 'Type', 'essential-classy-addons-for-elementor' ),
		) + array_slice( $posts_columns, $offset, null, true );

		return $posts_columns;
	}

	public function ec_admin_columns_text( $column_name, $post_id ) {

		if ( 'type' === $column_name ) {
			$type = get_post_meta( $post_id, 'ecafe_build_template_type', true );
			if ( ! empty( $type ) ) {
				echo esc_html( ucfirst( $type ) );
			}
		}
	}

	public function ec_builder_condition_meta() {
		add_meta_box(
			'ecafe-template-settings',
			__( 'Template Settings', 'essential-classy-addons-for-elementor' ),
			array( $this, 'ec_builder_condition_fields' ),
			self::Ecafe_Type,
			'normal',
			'default'
		);
	}

	public function ec_get_public_post_types() {
		$post_type_args = array(
			'show_in_nav_menus' => true,
		);

		$post_type_args = wp_parse_args( $post_type_args );

		$ecpost_types = get_post_types( $post_type_args, 'objects' );

		$post_types = array();

		foreach ( $ecpost_types as $post_type => $object ) {
			if ( $post_type != 'e-landing-page' ) {
				$post_types[ $post_type ] = $object->label;
			}
		}

		return $post_types;
	}

	public function ec_get_posts_list( $post_type = 'post' ) {
		$arg = array(
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'post_type'      => $post_type,
		);

		$posts      = get_posts( $arg );
		$post_array = array();
		if ( ! empty( $posts ) ) {
			foreach ( $posts as $post ) {
				$post_array[ $post->ID ] = $post->post_title;
			}
		}

		return $post_array;
	}

	function ec_get_prev_list_callback() {
		if ( ! isset( $_POST['ecafe_nonce'] ) ) {
			return;
		}
		$ecafe_nonce = isset( $_POST['ecafe_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ecafe_nonce'] ) ) : '';

		// Verify nonce
		if ( ! wp_verify_nonce( $ecafe_nonce, 'ecafe-temp-nonce' ) ) {
			return;
		}

		// Check user capability
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Check permissions
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		$data          = array();
		$template_type = ( isset( $_POST['template_type'] ) && ! empty( $_POST['template_type'] ) ) ? sanitize_text_field( wp_unslash( $_POST['template_type'] ) ) : 'singular';

		if ( $template_type == 'singular' ) {
			$post_type = ( isset( $_POST['template_data'] ) && ! empty( $_POST['template_data'] ) ) ? sanitize_text_field( wp_unslash( $_POST['template_data'] ) ) : 'post';
			$data      = $this->ec_get_posts_list( $post_type );
		} elseif ( $template_type == 'archives' ) {
			$taxonomy = ( isset( $_POST['template_data'] ) && ! empty( $_POST['template_data'] ) ) ? sanitize_text_field( wp_unslash( $_POST['template_data'] ) ) : 'category';
			$taxonomy = explode( ',', $taxonomy );
			$data     = $this->ec_get_taxonomy_list( $taxonomy );
		}

		$output = '';
		if ( ! empty( $data ) ) {
			foreach ( $data as $key => $val ) {
				$output .= '<option value="' . esc_attr( $key ) . '">' . esc_html( $val ) . '</option>';
			}
		}
		wp_send_json_success( $output );
	}

	public function ec_get_public_taxonomy_list() {
		$post_types    = $this->ec_get_public_post_types();
		$taxonomy_list = array();
		foreach ( $post_types as $post_type => $post_label ) {

			if ( ! get_post_type_archive_link( $post_type ) ) {
				continue;
			}

			$taxonomies      = get_object_taxonomies( $post_type, 'objects' );
			$taxonomies_list = wp_filter_object_list(
				$taxonomies,
				array(
					'public'            => true,
					'show_in_nav_menus' => true,
				)
			);
			foreach ( $taxonomies_list as $slug => $object ) {
				$taxonomy_list[ $object->name ] = $object->label;
			}
		}

		return $taxonomy_list;
	}

	public function ec_get_taxonomy_list( $taxonomy ) {
		$terms = get_terms(
			array(
				'taxonomy'   => $taxonomy,
				'hide_empty' => false,
			)
		);

		$term_list = array();
		if ( ! empty( $terms ) ) {
			foreach ( $terms as $term ) {
				$term_list[ $term->term_id ] = $term->name;
			}
		}
		return $term_list;
	}

	public function ec_builder_condition_fields( $post ) {
		// Retrieve existing value from the database
		$template_type    = get_post_meta( $post->ID, 'ecafe_build_template_type', true );
		$template_display = get_post_meta( $post->ID, 'ecafe_build_template_display', true );
		$display_singular = get_post_meta( $post->ID, 'ecafe_build_display_singular', true );
		$display_archives = get_post_meta( $post->ID, 'ecafe_build_display_archives', true );

		$display_prev   = get_post_meta( $post->ID, 'ecafe_build_display_prev', true );
		$options        = array(
			''         => __( 'None', 'essential-classy-addons-for-elementor' ),
			'header'   => __( 'Header', 'essential-classy-addons-for-elementor' ),
			'footer'   => __( 'Footer', 'essential-classy-addons-for-elementor' ),
			'singular' => __( 'Singular', 'essential-classy-addons-for-elementor' ),
			'archives' => __( 'Archives', 'essential-classy-addons-for-elementor' ),
			'page404'  => __( '404 Page', 'essential-classy-addons-for-elementor' ),
		);
		$get_post_types = $this->ec_get_public_post_types();
		$get_taxonomies = $this->ec_get_public_taxonomy_list();

		$get_prev = array();
		if ( $template_type == 'singular' ) {
			$get_prev = $this->ec_get_posts_list( $display_singular );
		} elseif ( $template_type == 'archives' ) {
			$get_prev = $this->ec_get_taxonomy_list( $display_archives );
		}

		wp_nonce_field( 'ec_template_builder_nonce', 'ec_template_builder_nonce' );
		?>
		<div class="ecafe-build-field-wrap">
			<div class="ecafe-field-col">
				<label for="ecafe-build-temp-type"><?php echo esc_html__( 'Template Type :', 'essential-classy-addons-for-elementor' ); ?></label>
				<select id="ecafe-build-temp-type" name="ecafe_build_template_type">
					<?php foreach ( $options as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $template_type, $value ); ?>><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>
			<div class="ecafe-field-col">
				<label for="ecafe-build-temp-display"><?php echo esc_html__( 'Display :', 'essential-classy-addons-for-elementor' ); ?></label>
				<select id="ecafe-build-temp-display" name="ecafe_build_template_display">
					<option value="entire" <?php selected( $template_display, 'entire' ); ?>><?php esc_html_e( 'Entire Website', 'essential-classy-addons-for-elementor' ); ?></option>
				</select>
			</div>
			
			<div class="ecafe-field-col">
				<label for="ecafe-build-display-singular"><?php echo esc_html__( 'Display :', 'essential-classy-addons-for-elementor' ); ?></label>
				<select id="ecafe-build-display-singular" name="ecafe_build_display_singular">
					<?php foreach ( $get_post_types as $post_type => $label ) : ?>
						<option value="<?php echo esc_attr( $post_type ); ?>" <?php selected( $display_singular, $post_type ); ?>><?php echo esc_html__( 'All ', 'essential-classy-addons-for-elementor' ) . esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>
			
			<div class="ecafe-field-col">
				<label for="ecafe-build-display-archives"><?php echo esc_html__( 'Display :', 'essential-classy-addons-for-elementor' ); ?></label>
				<select id="ecafe-build-display-archives" name="ecafe_build_display_archives[]" multiple>
					<?php
					foreach ( $get_taxonomies as $key => $label ) :
						$selected = in_array( $key, (array) $display_archives ) ? 'selected' : '';
						?>
						<option value="<?php echo esc_attr( $key ); ?>" <?php echo esc_attr( $selected ); ?>><?php echo esc_html__( 'All ', 'essential-classy-addons-for-elementor' ) . esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="ecafe-field-col">
				<label for="ecafe-build-display-prev"><?php echo esc_html__( 'Preview :', 'essential-classy-addons-for-elementor' ); ?></label>
				<select id="ecafe-build-display-prev" name="ecafe_build_display_prev">
					<?php foreach ( $get_prev as $post_type => $label ) : ?>
						<option value="<?php echo esc_attr( $post_type ); ?>" <?php selected( $display_prev, $post_type ); ?>><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>
		</div>
		<?php
	}

	public function ec_builder_condition_save_meta( $post_id ) {
		// Check if nonce is set
		if ( ! isset( $_POST['ec_template_builder_nonce'] ) ) {
			return;
		}
		$ecafe_nonce = isset( $_POST['ec_template_builder_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ec_template_builder_nonce'] ) ) : '';

		// Verify nonce
		if ( ! wp_verify_nonce( $ecafe_nonce, 'ec_template_builder_nonce' ) ) {
			return;
		}
		// Check if autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Check permissions
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
		// Save Theme Builder field data
		if ( isset( $_POST['ecafe_build_template_type'] ) ) {
			update_post_meta( $post_id, 'ecafe_build_template_type', sanitize_text_field( wp_unslash( $_POST['ecafe_build_template_type'] ) ) );
		}
		if ( isset( $_POST['ecafe_build_template_display'] ) ) {
			update_post_meta( $post_id, 'ecafe_build_template_display', sanitize_text_field( wp_unslash( $_POST['ecafe_build_template_display'] ) ) );
		}
		if ( isset( $_POST['ecafe_build_display_singular'] ) ) {
			update_post_meta( $post_id, 'ecafe_build_display_singular', sanitize_text_field( wp_unslash( $_POST['ecafe_build_display_singular'] ) ) );
		}
		if ( isset( $_POST['ecafe_build_display_archives'] ) && ! empty( $_POST['ecafe_build_display_archives'] ) ) {
			$display_archives = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['ecafe_build_display_archives'] ) );
			update_post_meta( $post_id, 'ecafe_build_display_archives', $display_archives );
		}
		if ( isset( $_POST['ecafe_build_display_prev'] ) && ! empty( $_POST['ecafe_build_display_prev'] ) ) {
			update_post_meta( $post_id, 'ecafe_build_display_prev', sanitize_text_field( wp_unslash( $_POST['ecafe_build_display_prev'] ) ) );
		}
	}

	/* Overright Header/Footer Template */
	public function ec_load_templates() {
		$curr_temp = basename( get_page_template_slug() );

		if ( $curr_temp == 'elementor_canvas' ) {
			return;
		}

		new Ecafe_Theme_Template();
	}

	/* get Conditional Content*/
	public function ec_render_builder_data_location( $location ) {
		$temp = Ecafe_Condition_Rules::get_instance()->ec_get_location_type( $location );
		if ( $location == 'header' || $location = 'footer' ) {
			$load_template = $temp;
		} else {
			$_key          = key( $temp );
			$load_template = $temp[ $_key ];
		}
		return Ec_Template_Builder_Content::get_instance()->ec_get_render_content( $load_template );
	}

	public function ecafe_single_template_overright( $template ) {
		if ( is_singular( array_keys( $this->ec_get_public_post_types() ) ) || is_404() ) {

			$location = 'singular';
			if ( is_404() ) {
				$location = 'page404';
			}
		} elseif ( function_exists( 'is_shop' ) && \is_shop() ) {
			$location = 'archives';
		} elseif ( is_archive() || is_tax() || is_home() || is_search() ) {
			$location = 'archives';
		}

		if ( ! empty( $location ) ) {
			$location_documents = Ecafe_Condition_Rules::get_instance()->ec_get_location_type( $location );

			if ( empty( $location_documents ) ) {
				return $template;
			}

			if ( 'singular' === $location || 'archives' === $location || 'page404' === $location ) {

				$first_key      = key( $location_documents );
				$theme_document = $location_documents[ $first_key ];

				$templateType = get_post_meta( $theme_document, '_wp_page_template', true );

				$this->singular_template = $theme_document;

				if ( $theme_document ) {
					switch ( $templateType ) {
						case 'elementor_canvas':
							$template = ECAFE_CLASSES_URL . 'builders/singular-canvas.php';
							break;
						case 'elementor_header_footer':
							$template = ECAFE_CLASSES_URL . 'builders/singular-fullwidth.php';
							break;
						default:
							$template = ECAFE_CLASSES_URL . 'builders/singular-fullwidth.php';
							break;
					}
				}
			}
		}

		return $template;
	}

	public function ec_singular_archives_content_render( $post ) {
		$templates = $this->singular_template;
		if ( ! empty( $templates ) ) {
			$allowed_tags           = wp_kses_allowed_html( 'post' );
			$allowed_tags['script'] = array(
				'type'  => true,
				'src'   => true,
				'defer' => true,
			);
			$allowed_tags['style']  = array(
				'type'  => true,
				'media' => true,
			);
			echo Ec_Template_Builder_Content::get_instance()->ec_get_render_content( $templates );
		} else {
			the_content();
		}
	}

	public function ec_admin_columns_shortcode( $columns ) {
		$columns['ecafe-shortcode'] = __( 'Shortcode', 'essential-classy-addons-for-elementor' );

		return $columns;
	}

	public function ec_admin_columns_shortcode_content( $column, $post_id ) {
		if ( 'ecafe-shortcode' === $column ) {
			// translator %s = shortcode, %d = post_id
			$shortcode = esc_attr( sprintf( '[%s id="%d"]', self::Ecafe_Shortcode, $post_id ) );
			printf( '<input type="text" class="ecafe-shortcode-input" onfocus="this.select()" value="%s" readonly style="font-size: 12px;"/>', esc_attr( $shortcode ) );
		}
	}

	public function ec_create_shortcode( $option = array() ) {
		if ( empty( $option['id'] ) ) {
			return '';
		}

		ob_start();
			echo Ec_Template_Builder_Content::get_instance()->ec_get_render_content( $option['id'] );
		return ob_get_clean();
	}
}

Ecafe_Theme_Builder::instance();
