<?php

$id = "$block[id]";
if(!empty($block['anchor'])) {
	$id = $block['anchor'];
}

$args = array();


$layout = get_field('layout');
if (empty($layout)) $layout = 'default';
$layout = preg_replace('/[^\w\-]+/', '_', $layout);
$args['layout'] = $layout;

$post_type = get_field('post_type');
if (empty($post_type)) $post_type = 'post';
$args['post_type'] = $post_type;

$columns = intval(get_field('columns'));
if (empty($columns)) $columns = 1;

$rows = intval(get_field('rows'));
if (empty($rows)) $rows = 10;

$args['posts_per_page'] = min($rows * $columns, 50);

$meta_key = get_field('meta_key');
$meta_value = get_field('meta_value');
if (!empty($meta_key) && !empty($meta_value)) {
	$args['meta'] = array();
	$args['meta'][$meta_key] = $meta_value;
}

$filter_tax = get_field('filter_tax');
$filter_term = get_field('filter_term');
if (!empty($filter_tax) && !empty($filter_term)) {
	$args['taxonomy'] = array();
	$args['taxonomy'][$filter_tax] = $filter_term;
}

if (function_exists('bw_posts')) {
	$data = bw_posts($args);
	$data->url = get_site_url(null, '/wp-json/bw/postgrid/posts');
	$posts = implode('', $data->posts);
	unset($data->posts);

	wp_localize_script('bw_post_grid_script', "$id", (array) $data);
}
$class_names = array();

$show_meta = get_field( 'show_meta' );
if ( ! $show_meta ) $class_names[] = 'bw-hide-post-meta';

$show_excerpt = get_field( 'show_excerpt' );
if ( ! $show_excerpt ) $class_names[] = 'bw-hide-post-excerpt';

$show_read_more = get_field( 'show_read_more' );
if ( ! $show_read_more ) $class_names[] = 'bw-hide-post-read-more';

$read_more_text = get_field('read_more_text');
if (empty($read_more_text)) $read_more_text = 'Read More';

?>
	<div id="<?php echo $id; ?>" class="bw-post-grid bw-skip-fade <?php echo implode( ' ', $class_names ); ?>">
		<style>
			#<?php echo $id; ?>{
				--columns: <?php echo $columns; ?>;
				--read-more-text: '<?php echo $read_more_text; ?>';
			}
		</style>
		<?php

		if (file_exists(get_stylesheet_directory() . "/acf-blocks/bw-post-grid/layouts/{$layout}/post-grid-template.php")) {
			include get_stylesheet_directory() . "/acf-blocks/bw-post-grid/layouts/{$layout}/post-grid-template.php";
		} else {
			include get_stylesheet_directory() . "/acf-blocks/bw-post-grid/layouts/default/post-grid-template.php";
		}

		?>
	</div>
<?php
