<?php
/**
 * Travel Insight Pro gallery metabox file.
 *
 * This is the template that includes all the other files for metaboxes of Travel Insight Pro theme
 *
 * @package Theme Palace
 * @subpackage Travel Insight Pro
 * @since Travel Insight Pro 1.0
 */

/**
 * Outputs the category for gallery page template
 */
function travel_insight_pro_gallery_template_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'travel_insight_pro_nonce' );
    $categories = get_post_meta( $post->ID, 'travel-insight-pro-gallery-template', true );

    $all_categories       = get_categories(); // get all default wordpress categories
    ?>

    <p>
     <label for="travel-insight-pro-gallery-template" class="travel-insight-pro-row-title"><?php esc_html_e( 'Select Categories', 'travel-insight-pro' )?></label>
     <select name="travel-insight-pro-gallery-template[]" id="travel-insight-pro-gallery-template" multiple>
        <?php foreach ( $all_categories as $key => $category ) { 
        $selected = in_array( $category->term_id, $categories ) ? 'selected' : '';
        ?>
        <option value="<?php echo esc_attr( $category->term_id );?>" <?php echo esc_attr( $selected ); ?>><?php echo esc_html( $category->name ); ?></option>
        <?php } ?>
     </select>
    </p>
    <?php
}

/**
 * Saves the page tab category input
 */
function travel_insight_pro_gallery_template_meta_save( $post_id ) {

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'travel_insight_pro_nonce' ] ) && wp_verify_nonce( sanitize_key( $_POST[ 'travel_insight_pro_nonce' ] ), basename( __FILE__ ) ) ) ? 'true' : 'false';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || ! $is_valid_nonce ) {
        return;
    }

    // Checks for input and sanitizes/saves if needed
    if( isset( $_POST[ 'travel-insight-pro-gallery-template' ] ) ) {
        update_post_meta( $post_id, 'travel-insight-pro-gallery-template', array_map( 'absint', $_POST[ 'travel-insight-pro-gallery-template'] ) );
    }

}
add_action( 'save_post', 'travel_insight_pro_gallery_template_meta_save' );

/**
 * Adds a meta box to the post editing screen
 */
function travel_insight_pro_custom_meta() {
    global $post;
    $page_template = get_post_meta( $post->ID, '_wp_page_template', true );

    if( $page_template == 'custom-template/gallery-template.php' ){
        add_meta_box( 'travel_insight_pro_custom_tab_page', esc_html__( 'Select Categories for Gallery', 'travel-insight-pro' ), 'travel_insight_pro_gallery_template_callback', array( 'page' ) );
    }
}
add_action( 'add_meta_boxes', 'travel_insight_pro_custom_meta' );