<?php
// declaring menu, custom post type and taxonomy


///////////////////////////////////
// SETTINGS PAGE

function gg_settings_page() {	
	add_submenu_page('edit.php?post_type=gg_galleries', esc_html__('Collections', 'gg_ml'), esc_html__('Collections', 'gg_ml'), 'publish_posts', 'gg_collections', 'gg_collections');
    add_submenu_page('edit.php?post_type=gg_galleries', 'GG '. esc_html__('Albums Manager', 'gg_ml'), 'GG '. esc_html__('Albums Manager', 'gg_ml'), 'publish_posts', 'gg_album_manager', 'gg_album_manager');
	add_submenu_page('edit.php?post_type=gg_galleries', esc_html__('Settings', 'gg_ml'), esc_html__('Settings', 'gg_ml'), 'manage_options', 'gg_settings', 'gg_settings');	
}
add_action('admin_menu', 'gg_settings_page');


function gg_collections() {
	include_once(GG_DIR . '/collections_manager.php');	
}
function gg_album_manager() {
    include_once(GG_DIR . '/local_images_manag.php');	
}
function gg_settings() {
	include_once(GG_DIR . '/settings/view.php');
}




///////////////////////////////////////
// GALLERY CUSTOM POST TYPE & TAXONOMY

add_action( 'init', 'register_cpt_gg_gallery' );
function register_cpt_gg_gallery() {

    $labels = array( 
        'name' => esc_html__( 'Galleries', 'gg_ml'),
        'singular_name' => esc_html__( 'Gallery', 'gg_ml'),
        'add_new' => esc_html__( 'Add New Gallery', 'gg_ml'),
        'add_new_item' => esc_html__( 'Add New Gallery', 'gg_ml'),
        'edit_item' => esc_html__( 'Edit Gallery', 'gg_ml'),
        'new_item' => esc_html__( 'New Gallery', 'gg_ml'),
        'view_item' => esc_html__( 'View Gallery', 'gg_ml'),
        'search_items' => esc_html__( 'Search Galleries', 'gg_ml'),
        'not_found' => esc_html__( 'No galleries found', 'gg_galleries' ),
        'not_found_in_trash' => esc_html__( 'No galleries found in Trash', 'gg_ml'),
        'parent_item_colon' => esc_html__( 'Parent Gallery:', 'gg_ml'),
        'menu_name' => esc_html__( 'Global Gallery', 'gg_ml'),
    );

    
    $svg_icon = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZD0iTTcuNCw2LjZhMS4wOSwxLjA5LDAsMCwwLC44LS44LjY0LjY0LDAsMCwwLDAtLjYsMSwxLDAsMCwwLTEtLjhINi45QTEuMywxLjMsMCwwLDAsNiw1LjgsMS4yMywxLjIzLDAsMCwwLDcuNCw2LjZaIiBzdHlsZT0iZmlsbDojOWNhMmE3Ii8+PHBhdGggZD0iTTE2LDExLjUsMTMuMi4xVjBIMTNMMi45LDIuNEgyLjh2LjFsLjcsM0wwLDcuOSw1LjYsMTZsNC4yLTIuOSw2LTEuNGguMVptLTExLjEsMkwxLjEsOC4xLDMuNyw2LjNsLjQsMS44YS42My42MywwLDAsMC0uNC4xLDEuMDksMS4wOSwwLDAsMC0uMywxLjMsMSwxLDAsMCwwLDEuMS40bC42LDIuNS0uMi44LjQtLjIuMS4zWm02LjgtNC4xLTEuMy4zLS44LjMtMywuNy0uNi4xTDQuNyw1LjZsLS4yLS43TDQsMy4xbDguMi0xLjksMS45LDcuN1oiIHN0eWxlPSJmaWxsOiM5Y2EyYTciLz48cG9seWdvbiBwb2ludHM9IjEwIDcgOS41IDcuNyA5LjMgNy45IDguNCA5LjIgNy40IDguNyA2LjkgOS4zIDYuMSAxMC40IDYuNyAxMC4zIDEwLjMgOS40IDEwLjYgOS4zIDExLjUgOS4xIDEzLjcgOC42IDEzIDUuNyAxMi4zIDYuNSAxMC45IDUuOCAxMCA3IiBzdHlsZT0iZmlsbDojOWNhMmE3Ii8+PC9zdmc+';
    
    $args = array( 
        'labels' => $labels,
        'hierarchical' => false,
        'supports' => array('title'), 
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 50,
		'menu_icon' => $svg_icon,
        'show_in_nav_menus' => false,
        'publicly_queryable' => false,
        'exclude_from_search' => true,
        'has_archive' => false,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => false,
        'capability_type' => 'post'
    );
    register_post_type('gg_galleries', $args);
	
	//////
	
	$labels = array( 
        'name' => esc_html__( 'Gallery Categories', 'gg_ml'),
        'singular_name' => esc_html__( 'Gallery Category', 'gg_ml' ),
        'search_items' => esc_html__( 'Search Gallery Categories', 'gg_ml' ),
        'popular_items' => NULL,
        'all_items' => esc_html__( 'All Gallery Categories', 'gg_ml' ),
        'parent_item' => esc_html__( 'Parent Gallery Category', 'gg_ml' ),
        'parent_item_colon' => esc_html__( 'Parent Gallery Category:', 'gg_ml' ),
        'edit_item' => esc_html__( 'Edit Gallery Category', 'gg_ml' ),
        'update_item' => esc_html__( 'Update Gallery Category', 'gg_ml' ),
        'add_new_item' => esc_html__( 'Add New Gallery Category', 'gg_ml' ),
        'new_item_name' => esc_html__( 'New Gallery Category', 'gg_ml' ),
        'separate_items_with_commas' => esc_html__( 'Separate item categories with commas', 'gg_ml' ),
        'add_or_remove_items' => esc_html__( 'Add or remove Gallery Categories', 'gg_ml' ),
        'choose_from_most_used' => esc_html__( 'Choose from most used Gallery Categories', 'gg_ml' ),
        'menu_name' => esc_html__( 'Gallery Categories', 'gg_ml' ),
    );

    $args = array( 
        'labels' => $labels,
        'public' => false,
        'show_in_nav_menus' => false,
        'show_ui' => true,
        'show_tagcloud' => false,
        'hierarchical' => true,
        'rewrite' => false,
        'query_var' => true
    );
    register_taxonomy('gg_gall_categories', array('gg_galleries'), $args);
}



// rename the first submenu item from "Media Grid" to "Grid Items"
add_action('admin_menu', function() {
	global $submenu;
	$menu_slug = "edit.php?post_type=gg_galleries";

	// check if submenu exists
	if(isset($submenu[$menu_slug]) && is_array($submenu[$menu_slug])) {

		// loop through submenu items to find the one pointing to the main CPT page
		foreach($submenu[$menu_slug] as $index => $item) {
			// $item[2] is the submenu slug (link)
			if(isset($item[2]) && $item[2] === $menu_slug) {
				$submenu[$menu_slug][$index][0] = esc_html__('Galleries', 'gg_ml');
				return;
			}
		}

		// fallback: if no exact match found, rename the first submenu item
		if(isset($submenu[$menu_slug][0][0])) {
			$submenu[$menu_slug][0][0] = esc_html__('Galleries', 'gg_ml');
		}
	}
}, 9999);




////////////////////////
// COLLECTIONS TAXONOMY

add_action( 'init', 'register_taxonomy_gg_collections' );
function register_taxonomy_gg_collections() {
	
    $labels = array( 
        'name' => esc_html__( 'Collections', 'gg_ml'),
        'singular_name' => esc_html__( 'Collection', 'gg_ml'),
        'search_items' => esc_html__( 'Search Collections', 'gg_ml'),
        'popular_items' => esc_html__( 'Popular Collections', 'gg_ml'),
        'all_items' => esc_html__( 'All Collections', 'gg_ml'),
        'parent_item' => esc_html__( 'Parent Collection', 'gg_ml'),
        'parent_item_colon' => esc_html__( 'Parent Collection:', 'gg_ml'),
        'edit_item' => esc_html__( 'Edit Collection', 'gg_ml'),
        'update_item' => esc_html__( 'Update Collection', 'gg_ml'),
        'add_new_item' => esc_html__( 'Add New Collection', 'gg_ml'),
        'new_item_name' => esc_html__( 'New Collection', 'gg_ml'),
        'separate_items_with_commas' => esc_html__( 'Separate grids with commas', 'gg_ml'),
        'add_or_remove_items' => esc_html__( 'Add or remove Collections', 'gg_ml'),
        'choose_from_most_used' => esc_html__( 'Choose from most used Collections', 'gg_ml'),
        'menu_name' => esc_html__( 'Collections', 'gg_ml'),
    );

    $args = array( 
        'labels' => $labels,
        'public' => false,
        'show_in_nav_menus' => false,
        'show_ui' => false,
        'show_tagcloud' => false,
        'hierarchical' => false,
        'rewrite' => false,
        'query_var' => true
    );

    register_taxonomy('gg_collections', null, $args);
}



//////////////////////////////
// VIEW CUSTOMIZATORS

function gg_updated_messages( $messages ) {
  global $post;

  $messages['gg_galleries'] = array(
    0 => '', // Unused. Messages start at index 1.
    1 => esc_html__('Gallery updated', 'gg_ml'),
    2 => esc_html__('Gallery updated', 'gg_ml'),
    3 => esc_html__('Gallery deleted', 'gg_ml'),
    4 => esc_html__('Gallery updated', 'gg_ml'),
    /* translators: %s: date and time of the revision */
    5 => (isset($_GET['revision'])) ? sprintf( esc_html__('Gallery restored to revision from %s', 'gg_ml'), wp_post_revision_title(absint($_GET['revision']), false ) ) : false,
    6 => esc_html__('Gallery published', 'gg_ml'),
    7 => esc_html__('Gallery saved', 'gg_ml'),
    8 => esc_html__('Gallery submitted', 'gg_ml'),
    9 => sprintf( esc_html__('Gallery scheduled for: %1$s', 'gg_ml'), date_i18n('M j, Y @ G:i', strtotime($post->post_date)) ),
    10 => esc_html__('Gallery draft updated', 'gg_ml'),
  );

  return $messages;
}
add_filter('post_updated_messages', 'gg_updated_messages');



// edit submitbox - hide minor submit minor-publishing
add_action('admin_head', 'gg_galleries_custom_submitbox');
function gg_galleries_custom_submitbox() {
	global $post_type;

    if ($post_type == 'gg_galleries') {
		echo '<style type="text/css">
		#minor-publishing {
			display: none;	
		}
		#lcwp_slider_opt_box > .inside {
			padding: 0;	
		}
		#lcwp_slider_creator_box {
			background: none;
			border: none;	
		}
		#lcwp_slider_creator_box > .handlediv {
			display: none;	
		}
		#lcwp_slider_creator_box > h3.hndle {
			background: none;
			border: none;
			padding: 12px 0 6px 0;	
			font-size: 18px;
			border-radius: 0px 0px 0px 0px;
		}
		#add_slide {
			float: left;
			margin-top: -36px;
			margin-left: 132px;
			cursor: pointer;	
		}
		.slide_form_table {
			width: 100%;	
		}
		.slide_form_table td {
			vertical-align: top;	
		}
		.second_col {
			width: 50%;
			border-left: 1px solid #ccc; 
			padding-left: 30px;
		}
		</style>';
	}
}


// customize galleries CPT table
add_filter('manage_edit-gg_galleries_columns', 'gg_edit_pt_table_head', 10, 2);
function gg_edit_pt_table_head($columns) {
	$new_cols = array();
	
	$new_cols['cb'] = '<input type="checkbox" />';
	$new_cols['gid'] = 'ID';
	$new_cols['title'] = esc_html__('Title', 'column name');
	
	$new_cols['gg_type'] 	= esc_html__('Source', 'gg_ml');
	$new_cols['gg_layout'] 	= esc_html__('Layout', 'gg_ml');
	$new_cols['gg_pag'] 	= esc_html__('Pagination', 'gg_ml');
	$new_cols['gg_img_num'] = esc_html__('Images', 'gg_ml');
	$new_cols['date'] 		= esc_html__('Date', 'column name');
	$new_cols['gg_preview'] = '';
	
	return $new_cols;
}

add_action('manage_gg_galleries_posts_custom_column', 'gg_edit_pt_table_body', 10, 2);
function gg_edit_pt_table_body($column_name, $id) {

	$type 		= get_post_meta($id, 'gg_type', true);
	$layout		= get_post_meta($id, 'gg_layout', true);
	$paginate 	= get_post_meta($id, 'gg_paginate', true);
	$img_count 	= (int)get_post_meta($id, 'gg_img_count', true);
	$first_imgs = (array)get_post_meta($id, 'gg_first_imgs_data', true);

	switch ($column_name) {
		case 'gg_type' : 
			$type = gg_gall_static::sources( get_post_meta($id, 'gg_type', true) );		
			echo (is_array($type)) ? '' : $type;
			break;
		
		case 'gid' : echo $id;
			break;
		
		case 'gg_layout' : echo ($layout == 'string') ? 'PhotoString' : ucfirst($layout);
			break;
			
		case 'gg_pag' :
			if($paginate == '1') {_e('Yes');}
			elseif($paginate == '0') {_e('No');}
			else { echo 'Default'; }
			break;
            
		case 'gg_img_num' : echo $img_count;
			break;
		
		case 'gg_preview' : 
			if(!is_array($first_imgs) || !count($first_imgs)) {
				echo '';	
			} else {
			
				$to_display = array();
				for($a=0; $a<4; $a++) {
					
					if(isset($first_imgs[$a]) && isset($first_imgs[$a]['img_src'])) { 
						$img_src = gg_static::img_src_on_type($first_imgs[$a]['img_src'], $type);	
						$to_display[] = '<img src="'. gg_static::inline_thumb_src($img_src, $width = 55, $height = 55, 80, $first_imgs[$a]['thumb']) .'" height="55" width="55"/>';		
					}
					else {
						$to_display[] = '';
					}
				}
				
				echo '
				<table class="gg_gal_list_preview">
				  <tr><td>'.$to_display[0].'</td><td>'.$to_display[1].'</td></tr>
				  <tr><td>'.$to_display[2].'</td><td>'.$to_display[3].'</td></tr>
				</table>
				';
			}
			break;

		default:
			break;
	}
	return true;
}



// auto-populated galleries icon - add class to be processed via CSS
add_action('load-edit.php', function() {
    global $typenow;
    if($typenow != 'gg_galleries') {
        return false;   
    }
    
    add_filter('post_class', function($classes, $class, $post_id) {
        if(get_post_meta($post_id, 'gg_autopop', true)) {
            $classes[] = 'gg_is_autopop_gall';
        }
        
        return $classes;
    }, 10, 3);
    
    add_action('admin_footer', function() {
        ?>
        <script type="text/javascript">
        (function() { 
            "use strict";
            
            document.querySelectorAll('.gg_is_autopop_gall a.row-title').forEach(function(el) {
                el.insertAdjacentHTML('afterend', `<span class="gg_autopop_gall_flag" title="<?php esc_attr_e('auto-populated gallery', 'gg_ml') ?>"></span>`);
            });
        })();        
        </script>
        <?php
    }, 1);
});




/////////////////////////////////////////////////////////////////////////////////




// perform gallery type filter in galleries list
function gg_gall_list_type_do_filter($query) {
    global $pagenow;
	
	if(isset($_GET['post_type']) && $_GET['post_type'] == 'gg_galleries') {

		if(is_admin() && $pagenow == 'edit.php' && isset($_GET['gg_gall_list_filter']) && $_GET['gg_gall_list_filter'] !== '') {
			$query->query_vars['meta_key'] = 'gg_type';
			$query->query_vars['meta_value'] = $_GET['gg_gall_list_filter'];
		}
	}
	
	return $query;
}
add_filter('parse_query', 'gg_gall_list_type_do_filter');



// AVOID issues with bad servers in settings redirect
function gg_settings_redirect_trick() {
    if(!isset($_GET['page']) || $_GET['page'] != 'gg_settings') {
        return true;   
    }
	ob_start();
}
add_action('admin_init', 'gg_settings_redirect_trick', 1);