<?php
/**
 * Main class
 *
 * @author Jegstudio
 * @since 1.0.0
 * @package gutenverse-themes-builder
 */

namespace Gutenverse_Themes_Builder;

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

use Gutenverse_Themes_Builder\Database\Database;

/**
 * Class Builder Page
 *
 * @package gutenverse-themes-builder
 */
class Builder_Page {
	/**
	 * Type
	 *
	 * @var string
	 */
	const TYPE = 'gutenverse-theme-builder';

	/**
	 * Init constructor.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Init hooks.
	 */
	private function init_hooks() {
		add_action( 'admin_menu', array( $this, 'register_builder_menu' ) );
		add_action( 'gutenverse_include_dashboard', array( $this, 'load_builder_scripts' ) );
		add_action( 'save_post_wp_template', array( $this, 'on_save_template' ), 10, 3 );
	}

	/**
	 * On Save Template
	 *
	 * @param string $post_id .
	 * @param object $post .
	 * @param object $update .
	 * @return void
	 */
	public function on_save_template( $post_id, $post, $update ) {
		$theme_id   = get_option( 'gtb_active_theme_id' );
		$info_db    = Database::instance()->theme_info;
		$theme_data = $info_db->get_theme_data( $theme_id );
		$data       = $theme_data[0];
		$other      = maybe_unserialize( $data['other'] );
		if ( isset( $other['usedTemplateMode'] ) && ! empty( $other['usedTemplateMode'] ) && 'none' !== $other['usedTemplateMode'] ) {
			$parts              = explode( '-', $post->post_name );
			$post_template_type = $parts[0];
			if ( $post_template_type !== $other['usedTemplateMode'] ) {
				return;
			}
			// Remove the first element (index 0) and reindex
			array_shift( $parts );

			// Merge remaining elements with '-'
			$type = implode( '-', $parts );

			$core_template_slug = array(
				'404',
				'archive',
				'author',
				'category',
				'home',
				'index',
				'search',
				'single',
				'singular',
				'tag',
				'front-page',
				'date',
				'page',
			);

			if ( in_array( $type, $core_template_slug, true ) ) {
				$existing_template = get_page_by_path( $type, OBJECT, 'wp_template' );
				if ( $existing_template ) {
					wp_update_post(
						array(
							'ID'           => $existing_template->ID,
							'post_content' => $post->post_content,
							'tax_input'    => array(
								'wp_theme' => array( get_stylesheet() ),
							),
						)
					);
				} else {
					wp_insert_post(
						array(
							'post_title'   => ucwords( str_replace( '-', ' ', $type ) ),
							'post_name'    => $type,
							'post_type'    => 'wp_template',
							'post_status'  => 'publish',
							'post_content' => $post->post_content,
							'tax_input'    => array(
								'wp_theme' => array( get_stylesheet() ),
							),
						)
					);
				}
			}
		}
	}

	/**
	 * Register Builder Menu.
	 */
	public function register_builder_menu() {
		// Main Menu.
		add_menu_page(
			esc_html__( 'Themes Builder', 'gutenverse-themes-builder' ),
			esc_html__( 'Themes Builder', 'gutenverse-themes-builder' ),
			'manage_options',
			self::TYPE,
			array( $this, 'theme_builder_page' ),
			GUTENVERSE_THEMES_BUILDER_URL . '/assets/icons/theme-builder-dashboard.svg',
			40
		);
		$theme_mode = gutenverse_themes_builder_get_theme_mode();
		// Sub Menus.
		$path = self::TYPE . '&path=';

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Theme List', 'gutenverse-themes-builder' ),
			esc_html__( 'Theme List', 'gutenverse-themes-builder' ),
			'manage_options',
			self::TYPE,
			array( $this, 'theme_builder_page' ),
			0
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Templates', 'gutenverse-themes-builder' ),
			esc_html__( 'Templates', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-templates',
			array( $this, 'theme_builder_page' ),
			1
		);
		if ( 'gutenverse-only' === $theme_mode ) {
			add_submenu_page(
				self::TYPE,
				esc_html__( 'Pages', 'gutenverse-themes-builder' ),
				esc_html__( 'Pages', 'gutenverse-themes-builder' ),
				'manage_options',
				$path . 'manage-pages',
				array( $this, 'theme_builder_page' ),
				2
			);
		}

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Patterns', 'gutenverse-themes-builder' ),
			esc_html__( 'Patterns', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-patterns',
			array( $this, 'theme_builder_page' ),
			3
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Global Style', 'gutenverse-themes-builder' ),
			esc_html__( 'Global Style', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-global',
			array( $this, 'theme_builder_page' ),
			4
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Assets', 'gutenverse-themes-builder' ),
			esc_html__( 'Assets', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-assets',
			array( $this, 'theme_builder_page' ),
			4
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Required Plugins', 'gutenverse-themes-builder' ),
			esc_html__( 'Required Plugins', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-plugins',
			array( $this, 'theme_builder_page' ),
			8
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Manage Dashboard', 'gutenverse-themes-builder' ),
			esc_html__( 'Manage Dashboard', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-dashboard',
			array( $this, 'theme_builder_page' ),
			5
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Screenshots', 'gutenverse-themes-builder' ),
			esc_html__( 'Screenshots', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'manage-screenshots',
			array( $this, 'theme_builder_page' ),
			6
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Readme Editor', 'gutenverse-themes-builder' ),
			esc_html__( 'Readme Editor', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'readme-editor',
			array( $this, 'theme_builder_page' ),
			7
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Export Theme', 'gutenverse-themes-builder' ),
			esc_html__( 'Export Theme', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'export-theme',
			array( $this, 'theme_builder_page' ),
			8
		);

		add_submenu_page(
			self::TYPE,
			esc_html__( 'Backup Data', 'gutenverse-themes-builder' ),
			esc_html__( 'Backup Data', 'gutenverse-themes-builder' ),
			'manage_options',
			$path . 'backup-data',
			array( $this, 'theme_builder_page' ),
			99
		);
	}

	/**
	 * Render page.
	 */
	public function theme_builder_page() {
		?>
		<div id="gtb-root"></div>
		<?php
	}

	/**
	 * Load builder scripts
	 */
	public function load_builder_scripts() {
		global $current_screen;

		if ( 'toplevel_page_gutenverse-theme-builder' === $current_screen->id ) {
			$include = ( include GUTENVERSE_THEMES_BUILDER_DIR . '/lib/dependencies/builder.asset.php' ) ['dependencies'];

			wp_enqueue_media();
			wp_enqueue_script(
				'gtb-page',
				GUTENVERSE_THEMES_BUILDER_URL . '/assets/js/builder.js',
				$include,
				GUTENVERSE_THEMES_BUILDER_VERSION,
				true
			);

			wp_localize_script( 'gtb-page', 'GutenverseThemeBuilder', $this->get_config() );

			wp_register_style(
				'gtb-google-font',
				'//fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap',
				array(),
				GUTENVERSE_THEMES_BUILDER_VERSION
			);
			wp_enqueue_style( 'gtb-google-font' );

			wp_enqueue_style(
				'gtb-page-style',
				GUTENVERSE_THEMES_BUILDER_URL . '/assets/css/builder.css',
				null,
				GUTENVERSE_THEMES_BUILDER_VERSION
			);
		}
	}


	/**
	 * Get Theme Slug
	 *
	 * @return string|null
	 */
	public function get_theme_slug() {
		$theme_id = get_option( 'gtb_active_theme_id' );
		$info_db  = Database::instance()->theme_info;
		$data     = $info_db->get_theme_data( $theme_id );

		if ( ! empty( $data ) ) {
			return $data[0]['slug'];
		}

		return null;
	}

	/**
	 * Get Config
	 *
	 * @return array
	 */
	public function get_config() {
		$config                     = array();
		$config['pageSlug']         = self::TYPE;
		$config['editPath']         = admin_url( 'post.php' );
		$config['createPattern']    = admin_url( 'post-new.php?post_type=gutenverse-pattern' );
		$config['themeSlug']        = $this->get_theme_slug();
		$config['themeMode']        = gutenverse_themes_builder_get_theme_mode();
		$config['recomendedPlugin'] = self::get_recomended_plugin_gutenverse();

		return $config;
	}

	/**
	 * Get extra plugin gutenverse
	 *
	 * @return array
	 */
	public static function get_recomended_plugin_gutenverse() {
		$result = wp_remote_get(
			GUTENVERSE_FRAMEWORK_LIBRARY_URL . 'wp-json/gutenverse-server/v3/plugin/ecosystem',
			array(
				'headers' => array(
					'Content-Type' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $result ) ) {
			error_log( 'Gutenverse API Error: ' . $result->get_error_message() );
			return array();
		}

		$response = json_decode( wp_remote_retrieve_body( $result ), true );
		if ( is_array( $response ) ) {
			$data = array_filter(
				$response,
				function ( $el ) {
					return isset( $el['host'] ) && 'wporg' === $el['host'];
				}
			);
			foreach ( $data as $key => $value ) {
				$plugin                  = self::fetch_plugin_detail( $value['slug'] );
				$data[ $key ]            = (array) $data[ $key ];
				$data[ $key ]['version'] = $data[ $key ]['version'] ? $data[ $key ]['version'] : $plugin['version'];
				$data[ $key ]['icon']    = self::get_plugin_image( $plugin );
				$data[ $key ]['label']   = $value['name'];
				$data[ $key ]['value']   = $value['slug'];
				$data[ $key ]['type']    = $value['host'];
				unset( $data[ $key ]['host'] );
				unset( $data[ $key ]['name'] );
				unset( $data[ $key ]['slug'] );
				unset( $data[ $key ]['incoming'] );
				unset( $data[ $key ]['description'] );
				unset( $data[ $key ]['url'] );
			}
			return $data;
		}

		return array();
	}

	/**
	 * Get plugin information
	 *
	 * @param string $plugin_slug Plugin Slug.
	 *
	 * @return array
	 */
	public static function fetch_plugin_detail( $plugin_slug ) {
		require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		$result = plugins_api(
			'plugin_information',
			array(
				'slug'   => $plugin_slug,
				'locale' => 'en_US',
				'fields' => array(
					'icons' => true,
				),
			)
		);

		$description = array(
			'version' => $result->version,
			'name'    => $result->name,
			'icon'    => $result->icons,
		);
		return $description;
	}

	/**
	 * Get Plugin Image.
	 *
	 * @param array $plugin String Plugin.
	 *
	 * @return string
	 */
	public static function get_plugin_image( $plugin ) {
		$plugin = (array) $plugin;

		if ( ! empty( $plugin['icon']['svg'] ) ) {
			$plugin_icon_url = $plugin['icon']['svg'];
		} elseif ( ! empty( $plugin['icon']['2x'] ) ) {
			$plugin_icon_url = $plugin['icon']['2x'];
		} elseif ( ! empty( $plugin['icon']['1x'] ) ) {
			$plugin_icon_url = $plugin['icon']['1x'];
		} else {
			$plugin_icon_url = $plugin['icon']['default'];
		}

		return $plugin_icon_url;
	}
}
