<?php
/**
 * Beaver Builder Module: AZ Post Grid & Carousel (AJAX)
 */

class FLAZPostGridCustomModule extends FLBuilderModule {
	public function __construct() {
		parent::__construct([
			'name'            => __('AZ Post Grid & Carousel Custom', 'fl-builder'),
			'description'     => __('Grid with AJAX filters & load more.', 'fl-builder'),
			'category'        => __('Custom Modules', 'fl-builder'),
			'dir'             => plugin_dir_path(__FILE__),
			'url'             => plugin_dir_url(__FILE__),
			'editor_export'   => true,
			'partial_refresh' => true,
			'enabled'         => true,
			'icon'            => 'schedule.svg',
		]);

		$this->add_css('az-post-grid');
	}

	public function enqueue_scripts() {
		// Add Swiper later if you enable carousel
	}
}

/** Helpers */
if ( ! function_exists('az_get_all_post_types') ) {
	function az_get_all_post_types() {
		$pts  = get_post_types(['public' => true], 'objects');
		$opts = [];
		foreach ($pts as $pt) {
			$opts[$pt->name] = $pt->labels->singular_name;
		}
		return $opts;
	}
}

/**
 * Robust token renderer.
 * Replaces [[token]] or {{token}} (tolerates spaces) with values from $resolver.
 */
if ( ! function_exists('az_render_tokens') ) {
	function az_render_tokens($tpl, array $resolver) {
		// [[ token ]]
		$tpl = preg_replace_callback(
			'/\[\[\s*([a-z0-9_]+)\s*\]\]/i',
			function($m) use ($resolver) {
				$key = strtolower($m[1]);
				return array_key_exists($key, $resolver) ? $resolver[$key] : '';
			},
			$tpl
		);
		// {{ token }}
		$tpl = preg_replace_callback(
			'/\{\{\s*([a-z0-9_]+)\s*\}\}/i',
			function($m) use ($resolver) {
				$key = strtolower($m[1]);
				return array_key_exists($key, $resolver) ? $resolver[$key] : '';
			},
			$tpl
		);
		return $tpl;
	}
}

/** Register module controls */
FLBuilder::register_module('FLAZPostGridCustomModule', [
	'general' => [
		'title'    => __('General', 'fl-builder'),
		'sections' => [
			'settings' => [
				'title'  => __('Settings', 'fl-builder'),
				'fields' => [
					'layout_type' => [
						'type'    => 'select',
						'label'   => __('Layout', 'fl-builder'),
						'default' => 'grid',
						'options' => [
							'grid'     => __('Grid', 'fl-builder'),
							'carousel' => __('Carousel (AJAX not enabled)', 'fl-builder'),
						],
					],
					'post_type' => [
						'type'    => 'select',
						'label'   => __('Post Type', 'fl-builder'),
						'default' => 'business-matchmaking',
						'options' => az_get_all_post_types(),
					],
					'posts_count' => [
						'type'    => 'text',
						'label'   => __('Posts per page', 'fl-builder'),
						'default' => '6',
					],
					'custom_layout_code' => [
						'type'        => 'code',
						'label'       => __('Custom Item Markup (HTML)', 'fl-builder'),
						'rows'        => 10,
						'editor'      => 'html',
						'placeholder' => '<article class="bm-card"><a class="bm-thumb" href="[[post_permalink]]">[[post_thumbnail]]</a><div class="bm-body"><h3><a href="[[post_permalink]]">[[post_title]]</a></h3><p>[[acf_short_summary]]</p><div class="bm-badges"><span class="bm-badge">[[tax_industry]]</span><span class="bm-badge">[[tax_partnership]]</span></div><div class="bm-meta"><span>Posted: [[post_date]]</span><span>[[company_name]]</span></div><a class="bm-cta" href="[[post_permalink]]">View Details</a></div></article>',
						'description' => __('Tokens: post_*, acf_* plus [[tax_industry]], [[tax_partnership]], [[company_name]]', 'fl-builder'),
					],
					'show_front_filters' => [
						'type'    => 'select',
						'label'   => __('Show filter bar', 'fl-builder'),
						'default' => 'yes',
						'options' => [
							'yes' => __('Yes', 'fl-builder'),
							'no'  => __('No',  'fl-builder'),
						],
					],
					'load_more_text' => [
						'type'    => 'text',
						'label'   => __('Load More button text', 'fl-builder'),
						'default' => 'Load More',
					],
				],
			],
		],
	],
]);

/** AJAX: fetch items (filter + paging) */
add_action('wp_ajax_az_pg_fetch',        'az_pg_fetch_callback');
add_action('wp_ajax_nopriv_az_pg_fetch', 'az_pg_fetch_callback');

function az_pg_fetch_callback() {
	check_ajax_referer('az_pg_nonce', 'security');

	$post_type = isset($_POST['post_type']) ? sanitize_key(wp_unslash($_POST['post_type'])) : 'business-matchmaking';
	$per_page  = isset($_POST['per_page'])  ? max(1, (int) $_POST['per_page']) : 6;
	$page      = isset($_POST['page'])      ? max(1, (int) $_POST['page']) : 1;
	$industry  = isset($_POST['industry'])  ? sanitize_title(wp_unslash($_POST['industry'])) : '';
	$ptype     = isset($_POST['ptype'])     ? sanitize_title(wp_unslash($_POST['ptype'])) : '';
	$tmpl_b64  = isset($_POST['tmpl'])      ? wp_unslash($_POST['tmpl']) : '';
	$template  = $tmpl_b64 ? base64_decode($tmpl_b64) : '';

	$args = [
		'post_type'      => $post_type,
		'posts_per_page' => $per_page,
		'paged'          => $page,
		'orderby'        => 'date',
		'order'          => 'DESC',
	];

	$tax_query = [];
	if ($industry) {
		$tax_query[] = [
			'taxonomy' => 'category-industry',
			'field'    => 'slug',
			'terms'    => $industry,
		];
	}
	if ($ptype) {
		$tax_query[] = [
			'taxonomy' => 'partnership-type',
			'field'    => 'slug',
			'terms'    => $ptype,
		];
	}
	if ($tax_query) {
		$args['tax_query'] = (count($tax_query) > 1) ? array_merge(['relation' => 'AND'], $tax_query) : $tax_query;
	}

	$q = new WP_Query($args);

	ob_start();

	if ($q->have_posts()) {
		while ($q->have_posts()) {
			$q->the_post();

			// ACF fields
			$acf_email        = get_field('email')         ?: '';
			$acf_budget_range = get_field('budget_range')  ?: '';
			$acf_location     = get_field('location')      ?: '';
			$acf_summary      = get_field('short_summary') ?: '';

			// Taxonomies
			$ind_terms = get_the_terms(get_the_ID(), 'category-industry');
			$pt_terms  = get_the_terms(get_the_ID(), 'partnership-type');
			$ind_str   = $ind_terms ? implode(', ', wp_list_pluck($ind_terms, 'name')) : '';
			$pt_str    = $pt_terms  ? implode(', ', wp_list_pluck($pt_terms, 'name'))  : '';

			// Company (from ACF user field bm_owner -> UM meta company_name)
			$company  = '';
			$owner_id = function_exists('get_field') ? (int) get_field('bm_owner', get_the_ID()) : 0;
			if ($owner_id) {
				$company = get_user_meta($owner_id, 'company_name', true);
				if (! $company) {
					$company = get_the_author_meta('display_name', $owner_id);
				}
			}

			$resolver = [
				// core
				'post_title'         => esc_html(get_the_title()),
				'post_excerpt'       => esc_html(wp_trim_words(get_the_excerpt(), 20)),
				'post_permalink'     => esc_url(get_permalink()),
				'post_date'          => esc_html(get_the_date('M j, Y')),
				'post_thumbnail'     => get_the_post_thumbnail(null, 'large'),
				'post_thumbnail_url' => esc_url(get_the_post_thumbnail_url(null, 'large')),

				// acf
				'acf_email'         => esc_html($acf_email),
				'acf_budget_range'  => esc_html($acf_budget_range),
				'acf_location'      => esc_html($acf_location),
				// Trim ACF short summary to 20 words with ellipsis
'acf_short_summary' => esc_html(
    wp_trim_words( strip_tags( $acf_summary ), 20, '…' )
),

				'acf_email_link'    => $acf_email ? '<a class="bm-mail" href="mailto:' . esc_attr($acf_email) . '">Email</a>' : '',

				// extra
				'tax_industry'     => esc_html($ind_str),
				'tax_partnership'  => esc_html($pt_str),
				'company_name'     => esc_html($company),
			];

			echo '<div class="az-grid-item">';

			if ($template) {
				echo az_render_tokens($template, $resolver); // phpcs:ignore WordPress.Security.EscapeOutput
			} else {
				?>
				<a class="post-thumb" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('large'); ?></a>
				<h3 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
				<p class="excerpt"><?php echo esc_html($acf_summary ? wp_trim_words($acf_summary, 25) : wp_trim_words(get_the_excerpt(), 20)); ?></p>
				<ul class="bm-mini">
					<?php if ($acf_location)     echo '<li><strong>Location:</strong> ' . esc_html($acf_location)     . '</li>'; ?>
					<?php if ($acf_budget_range) echo '<li><strong>Budget:</strong> '   . esc_html($acf_budget_range) . '</li>'; ?>
					<?php if ($acf_email)        echo '<li><a class="bm-mail" href="mailto:' . esc_attr($acf_email) . '">Email</a></li>'; ?>
				</ul>
				<?php
			}

			echo '</div>';
		}
	} else {
		echo '<div class="az-no-posts"><p>' . esc_html__('No posts found.', 'az') . '</p></div>';
	}

	$html = ob_get_clean();
	wp_reset_postdata();

	wp_send_json([
		'success'   => true,
		'html'      => $html,
		'max_pages' => (int) $q->max_num_pages,
	]);
}
