<?php

$id = "$block[id]";
if(!empty($block['anchor'])) {
	$id = $block['anchor'];
}

$args = array();

$post_type = get_field('post_type');
if (empty($post_type)) $post_type = 'post';
$args['post_type'] = $post_type;

$layout = get_field('layout');
if (empty($layout)) $layout = 'default';
$layout = preg_replace('/[^\w\-]+/', '_', $layout);
$args['layout'] = $layout;

$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);

$element_id = get_field('kadence_element');
if (empty($element_id)) $element_id = false;
$args['element_id'] = $element_id;

$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;
}

if (function_exists('bw_posts')) {
	$data = bw_posts($args);
	$data->url = get_site_url(null, '/wp-json/bw/posts');
	$posts = implode('', $data->posts);
	unset($data->posts);

	wp_localize_script('bw_post_grid_script', "$id", (array) $data);
}

?>
	<div id="<?php echo $id; ?>" class="bw-post-grid-block no-more">
		<style>
			#<?php echo $id; ?>{
				--columns: <?php echo $columns; ?>;
			}
		</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
