<?php
namespace SabaiApps\Directories\Component\WordPressContent\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Model\Bundle;

class FullSiteEditorHelper {

	public function registerTemplates( Application $application ) {
		if ( ! $application->getPlatform()->isFullSiteEditorEnabled() ) {
			return;
		}

		register_block_template(
			'directories-pro/drts-directory-template',
			array(
				'title'       => 'Directories: Directory',
				'description' => __( 'Template for the main page of your directory.', 'directories-pro' ),
				'content'     => $this->_getTemplateContent( 'directory.php' ),
				'plugin'      => 'directories-pro',
				'post_types'  => array( 'page' ),
			)
		);
		register_block_template(
			'directories-pro/drts-post-template',
			array(
				'title'       => 'Directories: Post',
				'description' => __( 'Default template used to display a single post in your directory.', 'directories-pro' ),
				'content'     => $this->_getTemplateContent( 'post.php' ),
				'plugin'      => 'directories-pro',
			)
		);
		register_block_template(
			'directories-pro/drts-term-template',
			array(
				'title'       => 'Directories: Term',
				'description' => __( 'Default template used to display a single taxonomy along with its associated posts.', 'directories-pro' ),
				'content'     => $this->_getTemplateContent( 'term.php' ),
				'plugin'      => 'directories-pro',
			)
		);
	}

	protected function _getTemplateName( Bundle $bundle ) {
		switch ( $bundle->entitytype_name ) {
			case 'post':
				return 'single-' . $bundle->name;
			case 'term':
				return 'taxonomy-' . $bundle->name;
			case 'user':
				return 'user-' . $bundle->name;
			default:
				return false;
		}
	}

	protected function _getTemplateContent( $template, array $args = array() ) {
		extract( $args, EXTR_SKIP );
		ob_start();
		include strpos( $template, '/' ) === 0 ? $template : dirname( __DIR__ ) . '/templates/' . $template;
		return ob_get_clean();
	}

	public function isTemplateEnabled( Application $application, $bundleType ) {
		$info = $application->Entity_BundleTypeInfo( $bundleType );
		if ( empty( $info['public'] ) ) {
			return false;
		}

		if ( isset( $info['wp_template'] ) ) {
			return $info['wp_template'];
		}

		switch ( $info['entity_type'] ) {
			case 'post':
				return 'single.php';
			case 'term':
				return 'taxonomy.php';
			case 'user':
				return 'user.php';
			default:
				return false;
		}
	}

	public function isTemplateRegistered( Application $application, $bundle ) {
		return ( $bundle = $application->Entity_Bundle( $bundle ) )
			&& ( $template_name = $this->_getTemplateName( $bundle ) )
			&& $this->isTemplateEnabled( $application, $bundle->type )
			&& WP_Block_Templates_Registry::get_instance()->is_registered( 'directories-pro//' . $template_name );
	}
}
