<?php
/**
 * Snax News Post Row Categories
 *
 * @package snax 1.11
 * @subpackage Theme
 */

global $snax_post_format;
$snax_categories_classes = array();

if ( snax_has_field_errors( 'category_id' ) ) {
	$snax_categories_classes[] =  'snax-validation-error';
}

if ( snax_is_category_field_required( $snax_post_format ) ) {
	$snax_categories_classes[] = 'snax-field-required';
}

$snax_taxonomy = get_query_var( 'snax_categories_taxonomy', 'category' );
?>

<div class="snax-edit-post-row-categories <?php echo implode( ' ', array_map( 'sanitize_html_class', $snax_categories_classes ) ); ?>">

	<!-- Visible only if wrapper has error class added -->
	<span class="snax-validation-tip"><?php esc_html_e( 'This field is required', 'snax' ); ?></span>

	<label for="snax-post-category"><?php esc_html_e( 'Category', 'snax' ); ?></label>
	<?php
	wp_dropdown_categories( array(
		'taxonomy'          => $snax_taxonomy,
		'name'             	=> 'snax-post-category[]',
		'id'               	=> 'snax-post-category',
		'show_option_none' 	=> esc_html__( '- Select category -', 'snax' ),
		'include'          	=> snax_get_post_included_categories( $snax_post_format, $snax_taxonomy ),
		'exclude'          	=> snax_get_post_excluded_categories( $snax_taxonomy ),
		'orderby'          	=> 'name',
		'hide_empty'		=> '0',
		'hierarchical'       => 'true',
	) );
	?>
	<?php
    $selected_categories = snax_get_field_values( 'categories' );
    ?>

	<script>
        // wp_dropdown_categories() doesn't support multi select and multi values selection.
		(function ($) {
            <?php if ( snax_is_category_multi_allowed( $snax_post_format ) ) : ?>
			$('#snax-post-category').attr('multiple', 'multiple').attr('size', 5);
			$('#snax-post-category option:first-child').prop('selected', false);
            <?php endif; ?>
            <?php if ( ! empty( $selected_categories ) ) {
                foreach ( $selected_categories as $selected_category_id ) {
                    printf( "$('#snax-post-category option[value=". absint( $selected_category_id ) ."]').attr('selected', 'selected');" );
                }
            }
            ?>
		})(jQuery);
	</script>

</div>
