<?php
/**
 * Essential Grid page template handling.
 *
 * @package   Essential_Grid
 * @author    ThemePunch <info@themepunch.com>
 * @link      https://www.essential-grid.com/
 * @copyright 2025 ThemePunch
 * @since: 3.1.9.3
 */

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

/**
 * Handle custom page templates for Essential Grid.
 */
class Essential_Grid_Page_Template {

	/**
	 * Default blank template path (relative to the plugin root folder).
	 *
	 * @var string
	 */
	const TMPL = 'public/views/esg-blank-page-template.php';

	/**
	 * Singleton instance.
	 *
	 * @var Essential_Grid_Page_Template
	 */
	protected static $instance = null;

	/**
	 * Array of templates that this plugin tracks.
	 *
	 * @var array  Array of templates that this plugin tracks
	 */
	protected $templates = array();

	/**
	 * Get or create the singleton instance.
	 *
	 * @return Essential_Grid_Page_Template
	 */
	public static function get_instance() {
		if ( is_null( static::$instance ) ) {
			static::$instance = new Essential_Grid_Page_Template();
		}

		return static::$instance;
	}

	/**
	 * Set up defaults and hooks.
	 */
	protected function __construct() {
		$this->templates = array( self::TMPL => 'Essential Grid Blank Template' );
		$this->add_hooks();
	}

	/**
	 * Register hooks for page templates.
	 */
	protected function add_hooks() {
		// Add a filter to the template include to return "blank template" path.
		add_filter( 'template_include', array( $this, 'get_template_path' ) );

		// "Meta box" actions.
		add_action( 'essgrid_add_plugin_meta_box', array( $this, 'add_meta_box' ) );
		add_action( 'essgrid_custom_meta_box_save_after', array( $this, 'save_post' ), 10, 2 );
	}

	/**
	 * Add "blank template" meta box.
	 *
	 * @return void
	 */
	public function add_meta_box() {
		add_meta_box(
			'eg-blank-template-metabox',
			esc_attr__( 'Essential Grid', 'essential-grid' ),
			array( $this, 'display_meta_box' ),
			array(),
			'side',
			'default',
		);
	}

	/**
	 * Display "blank template" meta box.
	 *
	 * @param WP_Post $post Current post.
	 * @return void
	 */
	public static function display_meta_box( $post ) {
		$page_bg = get_post_meta( $post->ID, 'tp_eg_page_bg_color', true );
		$blank   = '1' === get_post_meta( $post->ID, 'tp_eg_blank_page', true );
		require_once ESG_PLUGIN_ADMIN_PATH . 'views/elements/grid-meta-box-blank-tmpl.php';
	}

	/**
	 * Checks if the template is assigned to the page
	 *
	 * @param string $template The template path WordPress resolved.
	 *
	 * @return string
	 */
	public function get_template_path( $template ) {
		global $post;

		if ( is_search() || ! isset( $post->ID ) ) {
			return $template;
		}
		if ( '1' !== get_post_meta( $post->ID, 'tp_eg_blank_page', true ) ) {
			return $template;
		}

		return ESG_PLUGIN_PATH . self::TMPL;
	}

	/**
	 * Create a page pre-populated with the first imported grid block.
	 *
	 * @param array $grids Imported grids to render.
	 *
	 * @return int
	 */
	public function create_grid_page( $grids ) {
		$new_page_id = 0;

		if ( ! is_array( $grids ) || empty( $grids ) ) {
			return $new_page_id;
		}

		$content = '';
		$page_id = get_option( 'tp_eg_import_page_id', 1 );

		foreach ( $grids as $grid ) {
			$content .= '<!-- wp:themepunch/essgrid -->' . "\n";
			$content .= '<div class="wp-block-themepunch-essgrid essgrid" data-gridtitle="' . esc_attr( $grid['name'] ) . '">';
			$content .= '[ess_grid alias="' . $grid['handle'] . '"][/ess_grid]';
			$content .= '</div>' . "\n";
			$content .= '<!-- /wp:themepunch/essgrid -->' . "\n";

			// TODO: check if any template(s) add more than one grid on page.
			// Currently add only main grid.
			break;
		}

		if ( '' !== $content ) {
			$new_page_id = wp_insert_post(
				array(
					'post_title'   => wp_strip_all_tags( 'Essential Grid Page ' . $page_id ),
					'post_content' => $content,
					'post_type'    => 'page',
					'post_status'  => 'draft',
					'meta_input'   => array(
						'tp_eg_blank_page'    => '1',
						'tp_eg_page_bg_color' => '',
					),
				)
			);

			if ( is_wp_error( $new_page_id ) ) {
				$new_page_id = 0;
			}

			update_option( 'tp_eg_import_page_id', ++$page_id );
		}

		return $new_page_id;
	}

	/**
	 * Persist page template meta when saving Essential Grid settings.
	 *
	 * @param array $metas   Submitted meta values.
	 * @param int   $post_id Current post ID.
	 */
	public function save_post( $metas, $post_id ) {
		$page_bg   = $metas['tp_eg_page_bg_color'] ?? '';
		$use_blank = $metas['tp_eg_blank_page'] ?? 0;

		update_post_meta( $post_id, 'tp_eg_page_bg_color', $page_bg );
		update_post_meta( $post_id, 'tp_eg_blank_page', $use_blank );
	}
}
