<?php
/**
 * Admin functionality.
 *
 * @package documentor
 */

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

/**
 * Admin Class
 */
class Documentor_Admin {
	/**
	 * Construct
	 */
	public function __construct() {
		$this->include_dependencies();
		$this->init_actions();
		$this->init_classes();
	}

	/**
	 * Include dependencies.
	 */
	public function include_dependencies() {
		require_once documentor()->plugin_path . 'includes/class-settings-api.php';
		require_once documentor()->plugin_path . 'includes/admin/class-settings.php';
		require_once documentor()->plugin_path . 'includes/admin/class-docs-list-table.php';
	}

	/**
	 * Initialize action hooks
	 *
	 * @return void
	 */
	public function init_actions() {
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );

		add_action( 'admin_menu', array( $this, 'admin_menu' ) );
		add_filter( 'parent_file', array( $this, 'menu_highlight' ) );

		add_filter( 'display_post_states', array( $this, 'display_post_states' ), 10, 2 );

		add_filter( 'admin_footer_text', array( $this, 'admin_footer_text' ), 1 );

		// Creates a new page when a Doc Hub is created
		add_action('created_docs_hub', [$this, 'auto_create_hub_page'], 10, 2);
		// Auto-Update the Page title/slug if the Hub is renamed
		add_action('edited_docs_hub', [$this, 'auto_update_hub_page'], 10, 2);
		// Auto-Trash the Page if the Hub is deleted
		add_action('pre_delete_term', [$this, 'auto_trash_hub_page'], 10, 2);

		// Force-hide the Parent Hub dropdown while creationg a Hub
		add_action('admin_head', [$this, 'hide_hub_parent_dropdown']);

		// Intercept Hub creation to prevent slug conflicts with existing posts/pages
		add_filter('pre_insert_term', [$this, 'prevent_duplicate_hub_slug'], 10, 2);
		// Admin Notices for Doc Hub Template.
		add_action('admin_notices', [$this, 'missing_hub_template_notice']);
	}

	/**
	 * Initialize classes.
	 */
	public function init_classes() {
		new Documentor_Settings();
		new Documentor_Docs_List_Table();
	}

	/**
	 * Load admin scripts and styles
	 *
	 * @param string $hook - hook name.
	 */
	public function admin_scripts( $hook ) {
		// Check if we are currently looking at the Categories or Hubs taxonomy screen
		$current_taxonomy = isset($_GET['taxonomy']) ? sanitize_text_field(wp_unslash($_GET['taxonomy'])) : '';
		$is_taxonomy_page = (in_array($hook, ['edit-tags.php', 'term.php']) && in_array($current_taxonomy, ['docs_category', 'docs_hub']));

		if('toplevel_page_documentor' !== $hook && !$is_taxonomy_page){
			wp_enqueue_style( 'documentor-admin-setting', documentor()->plugin_url . 'assets/admin/css/settings_style.css', array(), '1.0.0' );
			return;
		}

		wp_enqueue_script( 'vuejs', documentor()->plugin_url . 'assets/vendor/vue/vue.min.js', array(), '2.5.13', true );
		wp_enqueue_script( 'sweetalert', documentor()->plugin_url . 'assets/vendor/sweetalert/js/sweetalert.min.js', array( 'jquery' ), '1.1.3', true );
		wp_enqueue_script( 'documentor-admin', documentor()->plugin_url . 'assets/admin/js/script.min.js', array( 'jquery', 'jquery-ui-sortable', 'wp-util' ), '1.0.0', true );
		wp_enqueue_script('documentor-admin-custom', documentor()->plugin_url . 'assets/admin/js/admin.js', array('jquery'), '1.0.0', true);

		wp_localize_script(
			'documentor-admin',
			'documentor_admin_vars',
			array(
				'nonce'	=> wp_create_nonce( 'documentor-admin-nonce' ),
				'editurl'  => home_url( '/?pagelayer-live=1&p=' ),
				'viewurl'  => home_url( '/?p=' ),
				'__'	   => array(
					'enter_doc_title'		   => __( 'Enter doc title', 'documentor' ),
					'enter_section_title'	   => __( 'Enter section title', 'documentor' ),
					// translators: %s - copy.
					'clone_default_title'	   => __( '%s Copy', 'documentor' ),
					'remove_doc_title'		  => __( 'Are you sure?', 'documentor' ),
					'remove_doc_text'		   => __( 'Are you sure to delete the entire documentation? Sections and articles inside this doc will be deleted too!', 'documentor' ),
					'remove_doc_button_yes'	 => __( 'Yes, delete it!', 'documentor' ),
					'remove_section_title'	  => __( 'Are you sure?', 'documentor' ),
					'remove_section_text'	   => __( 'Are you sure to delete the entire section? Articles inside this section will be deleted too!', 'documentor' ),
					'remove_section_button_yes' => __( 'Yes, delete it!', 'documentor' ),
					'remove_article_title'	  => __( 'Are you sure?', 'documentor' ),
					'remove_article_text'	   => __( 'Are you sure to delete the article?', 'documentor' ),
					'remove_article_button_yes' => __( 'Yes, delete it!', 'documentor' ),
					'post_deleted_text'		 => __( 'This post has been deleted', 'documentor' ),
					'export_doc_text'		   => __( 'This process may take a while depending on your documentation size.', 'documentor' ),
					// translators: %s - export.
					'export_doc_title'		  => __( 'Export %s?', 'documentor' ),
					'export_doc_button_yes'	 => __( 'Export!', 'documentor' ),
					'exporting_doc_title'	   => __( 'Exporting...', 'documentor' ),
					'exporting_doc_text'		=> __( 'Starting', 'documentor' ),
					'exported_doc_title'		=> __( 'Successfully Exported', 'documentor' ),
					'exported_doc_download'	 => __( 'Download ZIP', 'documentor' ),
					'exported_doc_cancel'	   => __( 'Close', 'documentor' ),
				),
			)
		);

		wp_enqueue_style( 'sweetalert', documentor()->plugin_url . 'assets/vendor/sweetalert/css/sweetalert.css', array(), '1.1.3' );

		wp_enqueue_style( 'documentor-admin', documentor()->plugin_url . 'assets/admin/css/style.min.css', array(), '1.0.0' );
		
		wp_enqueue_style('documentor-admin-custom', documentor()->plugin_url . 'assets/admin/css/admin.css', array(), '1.0.0');
		wp_style_add_data( 'documentor-admin', 'rtl', 'replace' );
		wp_style_add_data( 'documentor-admin', 'suffix', '.min' );
	}

	/**
	 * Get the admin menu position
	 *
	 * @return int the position of the menu
	 */
	public function get_menu_position() {
		return apply_filters( 'documentor_menu_position', 48 );
	}

	/**
	 * Add menu items
	 *
	 * @return void
	 */
	public function admin_menu() {
		add_menu_page(
			__( 'Documentor', 'documentor' ),
			__( 'Documentor', 'documentor' ),
			'publish_posts',
			'documentor',
			array( $this, 'page_index' ),
			'dashicons-media-document',
			$this->get_menu_position()
		);
		add_submenu_page(
			'documentor',
			__( 'Documentations', 'documentor' ),
			__( 'Documentations', 'documentor' ),
			'publish_posts',
			'documentor',
			array( $this, 'page_index' )
		);
		add_submenu_page(
			'documentor',
			__( 'Categories', 'documentor' ),
			__( 'Categories', 'documentor' ),
			'publish_posts',
			'edit-tags.php?taxonomy=docs_category&post_type=docs'
		);
		add_submenu_page(
			'documentor', 
			__('Document Hub', 'documentor'), 
			__('Document Hub', 'documentor'),
			'publish_posts',
			'edit-tags.php?taxonomy=docs_hub&post_type=docs'
		);
	}

	/**
	 * Highlight the proper top level menu
	 *
	 * @link http://wordpress.org/support/topic/moving-taxonomy-ui-to-another-main-menu?replies=5#post-2432769
	 *
	 * @global obj $current_screen
	 * @param string $parent_file - parent file.
	 *
	 * @return string
	 */
	public function menu_highlight( $parent_file ) {
		global $current_screen;

		if ( 'docs' === $current_screen->post_type ) {
			$parent_file = 'documentor';
		}

		return $parent_file;
	}

	/**
	 * Add a post display state for special Documents in the page list table.
	 *
	 * @param array   $post_states An array of post display states.
	 * @param WP_Post $post		The current post object.
	 * @return array $post_states  An array of post display states.
	 */
	public function display_post_states( $post_states, $post ) {
		$documents_page_id = documentor()->get_option( 'docs_page_id', 'documentor_settings' );
		$linked_hub = get_post_meta($post->ID, '_documentor_linked_hub_id', true);

		if ( 'page' === $post->post_type && $documents_page_id && intval( $documents_page_id ) === $post->ID ) {
			$post_states[] = esc_html__('Documentor', 'documentor');
		} else if(!empty($linked_hub)){
			// Doc hub pages need to have post name
			$post_states[] = esc_html__('Documentor', 'documentor');
		}

		return $post_states;
	}

	/**
	 * UI Page handler
	 *
	 * @return void
	 */
	public function page_index() {
		include dirname( __FILE__ ) . '/template-vue.php';
	}

	/**
	 * Change the admin footer text on docs admin pages
	 *
	 * @param string $footer_text - footer text.
	 *
	 * @return string
	 */
	public function admin_footer_text( $footer_text ) {
		$current_screen = get_current_screen();
		$pages		  = array( 'toplevel_page_documentor', 'edit-docs' );

		// Check to make sure we're on a docs admin page.
		if ( isset( $current_screen->id ) && apply_filters( 'documentor_display_admin_footer_text', in_array( $current_screen->id, $pages, true ) ) ) {
			$footer_text .= ' ' . __( 'Thank you for using <strong>Documentor</strong>.', 'documentor' );

			// translators: %s - docs page url.
			$footer_text .= ' ' . sprintf( __( 'Use the <a href="%s">classic UI</a>.', 'documentor' ), admin_url( 'edit.php?post_type=docs' ) );
		}

		return $footer_text;
	}

	public function auto_create_hub_page($term_id, $tt_id){
		$term = get_term($term_id, 'docs_hub');

		// Prepare the page data
		$page_data = [
			'post_title' => $term->name,
			'post_name' => $term->slug,
			'post_status' => 'publish',
			'post_type' => 'page',
			'post_author' => get_current_user_id(),
		];

		// Insert the page into WordPress
		$page_id = wp_insert_post($page_data);

		if(!is_wp_error($page_id) && $page_id > 0){
			// Save the Page ID to the Hub, and the Hub ID to the Page
			update_term_meta($term_id, 'documentor_hub_page_id', $page_id);
			// adding '_' keeps it hidden
			update_post_meta($page_id, '_documentor_linked_hub_id', $term_id);
		}
	}

	public function auto_update_hub_page($term_id, $tt_id){
		$page_id = get_term_meta($term_id, 'documentor_hub_page_id', true);
		if($page_id){
			$term = get_term($term_id, 'docs_hub');
			wp_update_post([
				'ID' => $page_id,
				'post_title' => $term->name,
				'post_name' => $term->slug // Updates the URL if the hub name changes
			]);
		}
	}

	public function auto_trash_hub_page($term_id, $taxonomy){
		if($taxonomy === 'docs_hub'){
			$page_id = get_term_meta($term_id, 'documentor_hub_page_id', true);
			if($page_id){
				wp_trash_post($page_id); // Safely moves the linked page to the trash
			}
		}
	}

	public function hide_hub_parent_dropdown(){
		echo '<style>
			select#newdocs_hub_parent,
			label[for="newdocs_hub_parent"]{
				display: none !important;
			}
		</style>';
	}

	public function prevent_duplicate_hub_slug($term_name, $taxonomy){
		if('docs_hub' !== $taxonomy){
			return $term_name;
		}

		$entered_slug = false;

		$slug = !empty($_POST['slug']) ? sanitize_title(wp_unslash($_POST['slug'])) : '';
		
		if(!empty($slug)){
			// The user manually typed a slug
			$entered_slug = true;
		} else{
			// The user left it blank so WP will generate it from the Hub Name
			$slug = sanitize_title(wp_unslash($term_name));
		}

		$existing_term = get_term_by('slug', $slug, 'docs_hub');

		// If a conflict is found, abort and show the smart error message
		if(!empty($existing_term)){
			if($entered_slug){
				return new WP_Error(
					'duplicate_slug',
					sprintf(__('The slug <strong>"%s"</strong> is already in use. Please use different slug.', 'documentor'), $slug)
				);
			} else{
				return new WP_Error(
					'duplicate_slug',
					sprintf(__('The Hub name <strong>"%s"</strong> generates a slug that is already in use. Please manually enter a unique slug.', 'documentor'), $term_name)
				);
			}
		}
		return $term_name;
	}

	public function missing_hub_template_notice(){
		if(!current_user_can('manage_options')){
			return;
		}

		$is_documentor_page = false;
		$screen = function_exists('get_current_screen') ? get_current_screen() : null;

		// If the screen object doesn't exist, or if the current post type isn't 'docs', abort completely!
		if($screen && $screen->post_type === 'docs'){ 
			$is_documentor_page = true;
		} elseif(isset($_GET['page']) && strpos( $_GET['page'], 'documentor') !== false){
			$is_documentor_page = true;
		}

		if(!$is_documentor_page){
			return;
		}

		global $wpdb;
		
		$hub_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->term_taxonomy} WHERE taxonomy = 'docs_hub'");

		// If the DB returns 0 (or null), abort. 
		if(empty($hub_count) || intval($hub_count) === 0){
			return;
		}

		// Check for the PageLayer Template
		$template_exists = get_posts([
			'post_type' => 'pagelayer-template',
			'type' => 'archive',
			'title' => 'Docs Hub', // Search by the slug
			'post_status' => 'any',
			'numberposts' => 1,
			'fields' => 'ids',
		]);

		// Display the Notice
		if(empty($template_exists)){
			?>
			<div class="notice notice-warning">
				<p>
					<strong><?php esc_html_e( 'Documentor Action Required:', 'documentor' ); ?></strong> 
					<?php esc_html_e( 'Doc Hub template for it is missing. Please import the "Docs Hub" to display Hubs correctly.', 'documentor' ); ?>
				</p>
			</div>
			<?php
		}
	}
}

return new Documentor_Admin();
