<?php
/**
 * Register Custom Portfolio with Taxonomies
 * 
 * @package Responsive Portfolio Image Gallery 1.3 - 10 July, 2025
 * @link https://www.realwebcare.com/
 */

if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

if (!class_exists('RPGAL_Custom_Post')) {
	class RPGAL_Custom_Post
	{

		// Hold the single instance of the class.
		private static $instance;
		private $rpgal_options;

		// Constructor is private to enforce the Singleton pattern.
		private function __construct()
		{
			// Portfolio Global Values			
			$this->rpgal_options = get_option('rpgal_global_options', []);

			add_action('init', [$this, 'register_rcp_image_gallery'], 0);

			// Hook into the 'after_setup_theme' action
			add_action('after_setup_theme', [$this, 'rpgal_theme_support']);

			add_action('init', [$this, 'rpgal_taxonomies'], 0);

			/* Creating Filters With Custom Taxonomy */
			add_action('restrict_manage_posts', [$this, 'rpgal_filter_list']);

			// add_filter('parse_query', [$this, 'rpgal_perform_filtering']);
			add_action('pre_get_posts', [$this, 'rpgal_pre_get_posts']);
		}

		/**
		 * Public static method to retrieve the singleton instance.
		 *
		 * @return RPGAL_Custom_Post The singleton instance.
		 */
		public static function get_instances()
		{
			if (self::$instance) {
				return self::$instance;
			}

			self::$instance = new self();

			return self::$instance;
		}

		/**
		 * Registers the custom post type for portfolios.
		 * @return void
		 */
		public function register_rcp_image_gallery()
		{
			$rpgal_labels = apply_filters('rpgal_labels', array(
				'name' => _x('Portfolios', 'Post Type General Name', 'responsive-portfolio-image-gallery'),
				'singular_name' => _x('Portfolio', 'Post Type Singular Name', 'responsive-portfolio-image-gallery'),
				'menu_name' => __('RPGAL Portfolio', 'responsive-portfolio-image-gallery'),
				'parent_item_colon' => __('Parent Portfolio:', 'responsive-portfolio-image-gallery'),
				'all_items' => __('All Portfolios', 'responsive-portfolio-image-gallery'),
				'view_item' => __('View Portfolio', 'responsive-portfolio-image-gallery'),
				'add_new_item' => __('Add New Portfolio', 'responsive-portfolio-image-gallery'),
				'add_new' => __('New Portfolio', 'responsive-portfolio-image-gallery'),
				'edit_item' => __('Edit Portfolio', 'responsive-portfolio-image-gallery'),
				'update_item' => __('Update Portfolio', 'responsive-portfolio-image-gallery'),
				'search_items' => __('Search Portfolio', 'responsive-portfolio-image-gallery'),
				'not_found' => __('No Portfolio Found', 'responsive-portfolio-image-gallery'),
				'not_found_in_trash' => __('No Portfolio in Trash', 'responsive-portfolio-image-gallery'),
			));
			$rewrite = array(
				'slug' => 'portfolio',
				'with_front' => false,
				'pages' => true,
				'feeds' => true,
			);
			$rpgal_args = array(
				'label' => __('Portfolio', 'responsive-portfolio-image-gallery'),
				'description' => __('Lightweight portfolio gallery grid plugin', 'responsive-portfolio-image-gallery'),
				'labels' => $rpgal_labels,
				'supports' => apply_filters('rpgal_supports', array('title', 'editor', 'thumbnail', 'author', 'comments')),
				'taxonomies' => array('rpgal-category'),
				'hierarchical' => false,
				'public' => true,
				'show_ui' => true,
				'show_in_menu' => true,
				'show_in_admin_bar' => true,
				'menu_position' => null,
				'menu_icon' => 'dashicons-format-image',
				'can_export' => true,
				'has_archive' => true,
				'exclude_from_search' => false,
				'publicly_queryable' => true,
				'rewrite' => $rewrite,
				'query_var' => true,
				'capability_type' => 'page',
			);
			register_post_type('rpgal', apply_filters('rpgal_post_type_args', $rpgal_args));
			flush_rewrite_rules(); // Ensure rewrite rules are updated
		}

		/**
		 * Register Theme Features (feature image for portfolio)
		 * @return void
		 */
		public function rpgal_theme_support()
		{
			// Add theme support for Featured Images
			add_theme_support('post-thumbnails', array('rpgal'));
		}

		public function rpgal_taxonomies()
		{
			$labels = array(
				'name' => _x('Portfolio Categories', 'Taxonomy General Name', 'responsive-portfolio-image-gallery'),
				'singular_name' => _x('Portfolio Category', 'Taxonomy Singular Name', 'responsive-portfolio-image-gallery'),
				'menu_name' => __('Portfolio Category', 'responsive-portfolio-image-gallery'),
				'all_items' => __('All Categories', 'responsive-portfolio-image-gallery'),
				'parent_item' => __('Parent Category', 'responsive-portfolio-image-gallery'),
				'parent_item_colon' => __('Parent Category:', 'responsive-portfolio-image-gallery'),
				'new_item_name' => __('New Category Name', 'responsive-portfolio-image-gallery'),
				'add_new_item' => __('Add New Category', 'responsive-portfolio-image-gallery'),
				'edit_item' => __('Edit Category', 'responsive-portfolio-image-gallery'),
				'update_item' => __('Update Category', 'responsive-portfolio-image-gallery'),
				'separate_items_with_commas' => __('Separate categories with commas', 'responsive-portfolio-image-gallery'),
				'search_items' => __('Search categories', 'responsive-portfolio-image-gallery'),
				'add_or_remove_items' => __('Add or remove Categories', 'responsive-portfolio-image-gallery'),
				'choose_from_most_used' => __('Choose from the most used categories', 'responsive-portfolio-image-gallery'),
				'not_found' => __('Not Found', 'responsive-portfolio-image-gallery'),
			);
			$rewrite = array(
				'slug' => 'portfolio-category',
				'with_front' => true,
				'hierarchical' => false,
			);
			$args = array(
				'labels' => $labels,
				'hierarchical' => true,
				'has_archive' => true,
				'public' => true,
				'show_ui' => true,
				'show_admin_column' => true,
				'show_in_nav_menus' => false,
				'show_tagcloud' => false,
				'rewrite' => $rewrite,
				'query_var' => true,
			);
			register_taxonomy('rpgal-category', array('rpgal'), $args);
		}

		/**
		 * Displays a dropdown filter for portfolio categories in the admin area.
		 * @return void
		 */
		public function rpgal_filter_list()
		{
			global $typenow;
			$post_type = 'rpgal';
			$taxonomy = 'rpgal-category';
			if ($typenow == $post_type) {
				// Add nonce field to the admin filter form
				wp_nonce_field('rpgal_filter_list_action', 'rpgal_filter_list_nonce');

				// Verify nonce before processing GET data
				if (!isset($_GET['rpgal_filter_list_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['rpgal_filter_list_nonce'])), 'rpgal_filter_list_action')) {
					$selected = '';
				} else {
					$selected = isset($_GET[$taxonomy]) ? sanitize_text_field(wp_unslash($_GET[$taxonomy])) : '';
				}

				// $selected = isset($_GET[$taxonomy]) ? sanitize_text_field(wp_unslash($_GET[$taxonomy])) : '';
				$info_taxonomy = get_taxonomy($taxonomy);
				wp_dropdown_categories(array(
					// translators: %s is the portfolio category name
					'show_option_all' => sprintf(esc_html__('All %s', 'responsive-portfolio-image-gallery'), $info_taxonomy->label),
					'taxonomy' => $taxonomy,
					'name' => $taxonomy,
					'orderby' => 'name',
					'selected' => $selected,
					'hierarchical' => false,
					'depth' => 3,
					'show_count' => false,
					'hide_empty' => true,
				));
			}
			;
		}

		/**
		 * Modifies the main query for portfolio post type, category, and tag archives.
		 *
		 * @param WP_Query $query The current query object.
		 */
		public function rpgal_pre_get_posts($query)
		{
			if (!is_admin() && $query->is_main_query()) {
				// Handle rpgal post type archive, category, and tag archives
				if (is_post_type_archive('rpgal') || is_tax('rpgal-category') || is_tag()) {
					$query->set('post_type', 'rpgal');
					$query->set('posts_per_page', get_option('posts_per_page', 10));
				}
			} elseif (is_admin() && $query->is_main_query()) {
				// Handle admin category filtering
				global $pagenow;
				$post_type = 'rpgal';
				$taxonomy = 'rpgal-category';
				if ($pagenow === 'edit.php' && isset($query->query_vars['post_type']) && $query->query_vars['post_type'] === $post_type && isset($query->query_vars[$taxonomy]) && is_numeric($query->query_vars[$taxonomy]) && $query->query_vars[$taxonomy] != 0) {
					$term = get_term_by('id', $query->query_vars[$taxonomy], $taxonomy);
					if ($term) {
						$query->query_vars[$taxonomy] = $term->slug;
					}
				}
			}
		}
	}
}

RPGAL_Custom_Post::get_instances();
