<?php

/**
 * usage: 
 * add_filter('dragblock_register_post_type', 'your_post_type_function')
 * your_post_type_function($post_types) => $post_types.push([slug, icon]) 
 * if icon is missing, the post type will not show in the admin menu
 */
add_action('init', 'dragblock_post_type_register_all');
function dragblock_post_type_register_all()
{
	$post_types = apply_filters('dragblock_register_post_type', []);
	foreach ($post_types as $post_type) {
		if (empty($post_type['slug'])) {
			continue;
		}
		$slug = $post_type['slug'];
		$icon = $post_type['icon'] ?? '';		
		
		dragblock_post_type_register_one($slug, $icon);
	}
}

/**
 * update the post query for the post type archive
 */
add_action('pre_get_posts', 'dragblock_post_type_get_archive');
function dragblock_post_type_get_archive($query)
{
	if (is_admin()) {
		return;
	}
	if (!$query->is_main_query()) {
		return;
	}
	$post_types = apply_filters('dragblock_register_post_type', []);
	foreach ($post_types as $post_type) {
		$slug = $post_type['slug'];
		if (!is_post_type_archive($slug)) {
			continue;
		}

		if (isset($_GET['cat'])) {
			$query->set('tax_query', array(
				array(
					'taxonomy' => $slug . '-category',
					'field'    => 'slug',
					'terms'    => sanitize_text_field($_GET['cat']),
				),
			));
		}
		if (isset($_GET['tag'])) {
			$query->set('tax_query', array(
				array(
					'taxonomy' => $slug . '-tag',
					'field'    => 'slug',
					'terms'    => sanitize_text_field($_GET['tag']),
				),
			));
		}
		break;
	}
}

function dragblock_post_type_register_one($slug, $icon = '')
{
	// register post type
	$slug_permalink = $slug . 's';
	$hidden = empty($icon);
	$single = dragblock_slug_to_title($slug);
	$plural = $single . 's';

	$cat_slug = $slug . '-category';
	$tag_slug = $slug . '-tag';

	////////////////////////////////
	// Register Custom Post Type
	$labels = array(
		'name'                  => $plural,
		'singular_name'         => $single,
		'menu_name'             => $plural,
		'name_admin_bar'        => $single,
		'archives'              => $single . ' Archives',
		'attributes'            => $single . ' Attributes',
		'parent_item_colon'     => 'Parent  ' . $single . ':',
		'all_items'             => 'All ' . $plural,
		'add_new_item'          => 'Add New ' . $single,
		'add_new'               => 'Add New',
		'new_item'              => 'New ' . $single,
		'edit_item'             => 'Edit ',
		'update_item'           => 'Update ' . $single,
		'view_item'             => 'View ' . $single,
		'view_items'            => 'View ' . $plural,
		'search_items'          => 'Search ' . $single,
		'not_found'             => 'Not found',
		'not_found_in_trash'    => 'Not found in Trash',
		'featured_image'        => 'Featured Image',
		'set_featured_image'    => 'Set featured image',
		'remove_featured_image' => 'Remove featured image',
		'use_featured_image'    => 'Use as featured image',
		'insert_into_item'      => $single . 'Insert into ' . $single,
		'uploaded_to_this_item' => $single . 'Uploaded to this ' . $single,
		'items_list'            => $plural . ' list',
		'items_list_navigation' => $plural . ' list navigation',
		'filter_items_list'     => 'Filter ' . $plural . ' list',
	);
	$args = array(
		'label'                 => $single,
		'description'           => 'Custom post type for ' . $plural,
		'labels'                => $labels,
		'supports'              => array('title', 'editor', 'thumbnail', 'custom-fields'),
		'taxonomies'            => array($cat_slug, $tag_slug),
		'hierarchical'          => false,
		'public'                => true,
		'publicly_queryable'    => true,
		'show_in_rest'          => true,
		'has_archive'           => true,
		'show_ui'               => !$hidden,
		'show_in_menu'          => !$hidden,
		'menu_position'         => 5,
		'show_in_admin_bar'     => true,
		'show_in_nav_menus'     => true,
		'can_export'            => true,
		'exclude_from_search'   => false,
		'capability_type'       => 'post',
		'rewrite'               => array('slug' => $slug_permalink),
		'menu_icon'				=> $icon
	);
	register_post_type($slug, $args);


	////////////////////////////////////////////////////////////////
	// register default taxonomy parameters
	// Register Category Taxonomy (Similar to Category)
	$labels = array(
		'name'              => $single . ' Categories',
		'singular_name'     => $single . ' Category',
		'search_items'      => 'Search ' . $single . ' Categories',
		'all_items'         => 'All ' . $single . ' Categories',
		'parent_item'       => 'Parent ' . $single . ' Category',
		'parent_item_colon' => 'Parent ' . $single . ' Category:',
		'edit_item'         => 'Edit ' . $single . ' Category',
		'update_item'       => 'Update ' . $single . ' Category',
		'add_new_item'      => 'Add New ' . $single . ' Category',
		'new_item_name'     => 'New ' . $single . ' Category Name',
		'menu_name'         => $single . ' Categories',
	);
	$args = array(
		'hierarchical'      => true,
		'public'            => true,
		'publicly_queryable' => true,
		'show_in_rest' 		=> true,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => array('slug' => $cat_slug),
	);
	register_taxonomy($cat_slug, array($slug), $args);

	// Register ' . $single . ' Tag Taxonomy (Similar to Tag)
	$labels = array(
		'name'                       => $single . ' Tags',
		'singular_name'              => $single . ' Tag',
		'search_items'               => 'Search ' . $single . ' Tags',
		'popular_items'              => 'Popular ' . $single . ' Tags',
		'all_items'                  => 'All ' . $single . ' Tags',
		'edit_item'                  => 'Edit ' . $single . ' Tag',
		'update_item'                => 'Update ' . $single . ' Tag',
		'add_new_item'               => 'Add New ' . $single . ' Tag',
		'new_item_name'              => 'New ' . $single . ' Tag Name',
		'separate_items_with_commas' => 'Separate ' . $single . ' tags with commas',
		'add_or_remove_items'        => 'Add or remove ' . $single . ' tags',
		'choose_from_most_used'      => 'Choose from the most used ' . $single . ' tags',
		'not_found'                  => 'No ' . $single . ' tags found.',
		'menu_name'                  => $single . ' Tags',
	);
	$args = array(
		'hierarchical'          => false,
		'labels'                => $labels,
		'show_ui'               => true,
		'show_admin_column'     => true,
		'update_count_callback' => '_update_post_term_count',
		'query_var'             => true,
		'rewrite'               => array('slug' => $tag_slug),
	);
	register_taxonomy($tag_slug, array($slug), $args);

	////////////////////////////////
	// redirect taxonomy to default archive template
	$separator = '/' . $cat_slug . '/';
	if (strpos($_SERVER['REQUEST_URI'], $separator) !== false) {
		$parts = explode($separator, $_SERVER['REQUEST_URI']);
		$category_part = trim($parts[1], '/');

		// Preserve the query string if it exists
		$query_string = isset($_SERVER['QUERY_STRING']) ? '&' . $_SERVER['QUERY_STRING'] : '';
		wp_redirect(home_url('/' . $slug_permalink . '?cat=' . $category_part . $query_string), 301);
		exit;
	}
}
