<?php
/**
 * RedFox Tabs Custom Post Type Class
 *
 * Handles the registration and management of the RedFox Tabs custom post type.
 *
 * @package RedFoxWP\RedFoxTabManager
 * @since 1.0.0
 */

namespace RedFoxWP\RedFoxTabManager;

use RedFoxWP\RedFoxTabManager\Abstracts\Abstract_Singleton;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class Tabs_CPT
 *
 * Manages the RedFox Tabs custom post type.
 *
 * @since 1.0.0
 */
class Tabs_CPT extends Abstract_Singleton {

	/**
	 * Custom post type name.
	 *
	 * @since 1.0.0
	 * @access public
	 * @static
	 *
	 * @var string
	 */
	const CPT_NAME = 'redfoxwp_tab';

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 * @access protected
	 *
	 * @return void
	 */
	protected function __construct() {
		add_action( 'init', array( $this, 'register_post_type' ) );
		add_action( 'current_screen', array( $this, 'hide_cpt_list_page' ) );
		add_action( 'admin_init', array( $this, 'handle_duplicate_tab' ) );
	}

	/**
	 * Register the RedFox Tabs custom post type.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public function register_post_type() {
		$labels = array(
			'name'                  => _x( 'RedFox Tabs', 'Post type general name', 'redfox-tab-manager' ),
			'singular_name'         => _x( 'RedFox Tab', 'Post type singular name', 'redfox-tab-manager' ),
			'menu_name'             => _x( 'RedFox Tabs', 'Admin Menu text', 'redfox-tab-manager' ),
			'name_admin_bar'        => _x( 'RedFox Tab', 'Add New on Toolbar', 'redfox-tab-manager' ),
			'add_new'               => __( 'Add New', 'redfox-tab-manager' ),
			'add_new_item'          => __( 'Add New RedFox Tab', 'redfox-tab-manager' ),
			'new_item'              => __( 'New RedFox Tab', 'redfox-tab-manager' ),
			'edit_item'             => __( 'Edit RedFox Tab', 'redfox-tab-manager' ),
			'view_item'             => __( 'View RedFox Tab', 'redfox-tab-manager' ),
			'all_items'             => __( 'All RedFox Tabs', 'redfox-tab-manager' ),
			'search_items'          => __( 'Search RedFox Tabs', 'redfox-tab-manager' ),
			'parent_item_colon'     => __( 'Parent RedFox Tabs:', 'redfox-tab-manager' ),
			'not_found'             => __( 'No RedFox tabs found.', 'redfox-tab-manager' ),
			'not_found_in_trash'    => __( 'No RedFox tabs found in Trash.', 'redfox-tab-manager' ),
			'featured_image'        => _x( 'RedFox Tab Cover Image', 'Overrides the "Featured Image" phrase for this post type. Added in 4.3', 'redfox-tab-manager' ),
			'set_featured_image'    => _x( 'Set cover image', 'Overrides the "Set featured image" phrase for this post type. Added in 4.3', 'redfox-tab-manager' ),
			'remove_featured_image' => _x( 'Remove cover image', 'Overrides the "Remove featured image" phrase for this post type. Added in 4.3', 'redfox-tab-manager' ),
			'use_featured_image'    => _x( 'Use as cover image', 'Overrides the "Use as featured image" phrase for this post type. Added in 4.3', 'redfox-tab-manager' ),
			'archives'              => _x( 'RedFox Tab archives', 'The post type archive label used in nav menus. Default "Post Archives". Added in 4.4', 'redfox-tab-manager' ),
			'insert_into_item'      => _x( 'Insert into RedFox tab', 'Overrides the "Insert into post"/"Insert into page" phrase (used when inserting media into a post). Added in 4.4', 'redfox-tab-manager' ),
			'uploaded_to_this_item' => _x( 'Uploaded to this RedFox tab', 'Overrides the "Uploaded to this post"/"Uploaded to this page" phrase (used when viewing media attached to a post). Added in 4.4', 'redfox-tab-manager' ),
			'filter_items_list'     => _x( 'Filter RedFox tabs list', 'Screen reader text for the filter links heading on the post type listing screen. Default "Filter posts list"/"Filter pages list". Added in 4.4', 'redfox-tab-manager' ),
			'items_list_navigation' => _x( 'RedFox Tabs list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default "Posts list navigation"/"Pages list navigation". Added in 4.4', 'redfox-tab-manager' ),
			'items_list'            => _x( 'RedFox Tabs list', 'Screen reader text for the items list heading on the post type listing screen. Default "Posts list"/"Pages list". Added in 4.4', 'redfox-tab-manager' ),
		);

		$args = array(
			'labels'             => $labels,
			'public'             => false,
			'publicly_queryable' => false,
			'show_ui'            => true,
			'show_in_admin_bar'  => true,
			'show_in_menu'       => false,
			'query_var'          => false,
			'rewrite'            => false,
			'capability_type'    => 'post',
			'has_archive'        => false,
			'hierarchical'       => false,
			'menu_position'      => 56,
			'show_in_rest'       => true,
			'supports'           => array( 'title', 'editor' ),
		);

		register_post_type( self::CPT_NAME, $args );
	}

	/**
	 * Hide the CPT list page in admin.
	 *
	 * Redirects users away from the post list page while keeping
	 * individual post creation and editing pages accessible.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public function hide_cpt_list_page() {
		$current_screen = get_current_screen();

		// Check if we're on the post list page for our CPT.
		if ( $current_screen && 'edit-' . self::CPT_NAME === $current_screen->id ) {
			// Redirect to the Tab Manager admin page.
			wp_safe_redirect( admin_url( 'admin.php?page=redfox-tab-manager' ) );
			exit;
		}
	}

	/**
	 * Handle tab duplication when duplicate parameter is present.
	 *
	 * @since 1.0.1
	 * @access public
	 *
	 * @return void
	 */
	public function handle_duplicate_tab() {
		// Verify nonce for security first.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'redfox_tab_manager_duplicate_tab' ) ) {
			return;
		}

		// Check if we're on the new post page with duplicate parameter.
		if ( ! is_admin() || ! isset( $_GET['post_type'] ) || self::CPT_NAME !== $_GET['post_type'] ) {
			return;
		}

		// Check if duplicate parameter exists and is valid.
		if ( ! isset( $_GET['duplicate'] ) || ! is_numeric( $_GET['duplicate'] ) ) {
			return;
		}

		$source_post_id = absint( $_GET['duplicate'] );

		// Verify the source post exists and is of the correct post type.
		$source_post = get_post( $source_post_id );
		if ( ! $source_post || self::CPT_NAME !== $source_post->post_type ) {
			return;
		}

		// Check user capabilities.
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		// Create the duplicate post.
		$duplicate_post_id = $this->duplicate_tab( $source_post );

		if ( $duplicate_post_id ) {
			// Redirect to edit the new duplicate post.
			wp_safe_redirect( admin_url( "post.php?post={$duplicate_post_id}&action=edit" ) );
			exit;
		}
	}

	/**
	 * Duplicate a tab post.
	 *
	 * @since 1.0.1
	 * @access private
	 *
	 * @param \WP_Post $source_post The source post to duplicate.
	 *
	 * @return int|false The new post ID on success, false on failure.
	 */
	private function duplicate_tab( $source_post ) {
		// Prepare the new post data.
		$new_post_data = array(
			'post_title'   => sprintf(
				/* translators: %s: original post title */
				__( '%s (Copy)', 'redfox-tab-manager' ),
				$source_post->post_title
			),
			'post_content' => $source_post->post_content,
			'post_excerpt' => $source_post->post_excerpt,
			'post_status'  => 'draft', // Always create as draft.
			'post_type'    => self::CPT_NAME,
			'post_author'  => get_current_user_id(),
		);

		// Create the new post.
		$new_post_id = wp_insert_post( $new_post_data, true );

		if ( is_wp_error( $new_post_id ) ) {
			return false;
		}

		// Copy all meta data from source post.
		$meta_data = get_post_meta( $source_post->ID );

		if ( is_array( $meta_data ) ) {
			foreach ( $meta_data as $meta_key => $meta_values ) {
				// Skip internal WordPress meta keys that shouldn't be copied.
				if ( '_edit_lock' === $meta_key || '_edit_last' === $meta_key ) {
					continue;
				}

				// Copy each meta value (meta can have multiple values).
				foreach ( $meta_values as $meta_value ) {
					add_post_meta( $new_post_id, $meta_key, maybe_unserialize( $meta_value ) );
				}
			}
		}

		// Copy taxonomies if any are associated with the post type.
		$taxonomies = get_object_taxonomies( self::CPT_NAME );
		if ( ! empty( $taxonomies ) ) {
			foreach ( $taxonomies as $taxonomy ) {
				$terms = wp_get_object_terms( $source_post->ID, $taxonomy, array( 'fields' => 'slugs' ) );
				if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
					wp_set_object_terms( $new_post_id, $terms, $taxonomy );
				}
			}
		}

		return $new_post_id;
	}

	/**
	 * Get the CPT name.
	 *
	 * @since 1.0.0
	 * @access public
	 * @static
	 *
	 * @return string The CPT name.
	 */
	public static function get_cpt_name() {
		return self::CPT_NAME;
	}
}
