<?php

/**
 * Register My Brindle Tab.
 */
if ( ! function_exists( 'mb_register_menu_page_brindle' ) ) {
	function mb_register_menu_page_brindle() {
		add_menu_page(
			'My Brindle',
			'My Brindle',
			'manage_options',
			'my-brindle.php',
			'',
			QP_PLUGIN_URL . 'images/menu-icon.png',
			75
		);
	}

	add_action( 'admin_menu', 'mb_register_menu_page_brindle' );
}

add_action( 'admin_menu', 'qp_register_custom_submenu_page', 15 );
function qp_register_custom_submenu_page() {
	$query = new WP_Query( array(
		'post_type' => 'qp_popup',
	) );

	$url        = 'quickpop.php';
	$callback = function() {
		include_once QP_PLUGIN_DIR . 'templates/quickpop-listing.php';
	};

	add_submenu_page(
		'my-brindle.php',
		'QuickPop',
		'QuickPop',
		'manage_options',
		$url,
		$callback,
		80
	);
}

/* Register Admin Sub Menu */
add_action( 'admin_menu', 'qp_submissions_submenu', 20 );
function qp_submissions_submenu(){
    add_submenu_page(
        'my-brindle.php',
        'Submssions',
        'Submissions',
        'edit_posts',
        'edit.php?post_type=qp_submissions'
    );
}

add_action( 'admin_menu', 'qp_register_custom_submenu_popup_library', 16 );
function qp_register_custom_submenu_popup_library() {
	$query = new WP_Query( array(
		'post_type' => 'qp_popup',
	) );

	$url        = 'quickpop.php';
	$callback = function() {
		include_once QP_PLUGIN_DIR . 'templates/quickpop-listing.php';
	};

	add_submenu_page(
		'my-brindle.php',
		'Popups Library',
		'Popups Library',
		'manage_options',
		$url,
		$callback,
		80
	);
}

/**
 * Fix Parent Admin Menu Item
 */
add_filter( 'parent_file', 'qp_cpt_parent_file_fix' );
function qp_cpt_parent_file_fix( $parent_file ){

    /* Get current screen */
    global $current_screen, $self;

    /**
     * Add upload.php as parent file/menu if
     * it's Post Type list Screen or Edit screen of our post type.
     */
    if ( in_array( $current_screen->base, array( 'post', 'edit' ) ) && in_array( $current_screen->post_type, array( 'qp_submissions', 'qp_popup' ) ) ) {
        $parent_file = 'my-brindle.php';
    }

    return $parent_file;
}

/**
 * Fix Sub Menu Item Highlights
 */
add_filter( 'submenu_file', 'qp_submenu_file_fix' );
function qp_submenu_file_fix( $submenu_file ){

    /* Get current screen */
    global $current_screen, $self;

    if ( in_array( $current_screen->base, array( 'post', 'edit' ) ) ) {
        if ( $current_screen->post_type == 'qp_popup' ) {
	        $submenu_file = 'quickpop.php';
        } elseif ( $current_screen->post_type == 'qp_submissions' ) {
	        $submenu_file = 'edit.php?post_type=qp_submissions';
	    }
	}

    return $submenu_file;
}
