<?php
/**
 * Brentwood Course Table — front-end render.
 *
 * A dynamic grid of courses pulled from the Courses post type, optionally
 * filtered by one of its taxonomies. Each course is a centred link in a
 * bordered cell (N columns). On click it either:
 *   - "modal" (default): opens the course description + Ministry Credit in a
 *     shared pop-up (mirrors the course pop-up on brentwood.ca), or
 *   - "link": navigates to the course page.
 *
 * Deliberately reuses the bw/table-link "courses" grid markup, CSS
 * (bw-table-link style handle) and modal JS (bw-table-link-view) so the two
 * blocks share one implementation and never drift apart. The query + modal
 * body come from the shared helpers in inc/bw-course.php.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused — dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

require_once get_stylesheet_directory() . '/inc/bw-course.php';

if ( ! function_exists( 'bw_ct_color' ) ) {
	function bw_ct_color( $value, $default = '' ) {
		$value = trim( (string) $value );
		if ( '' === $value ) {
			return $default;
		}
		if ( preg_match( '/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i', $value )
			|| preg_match( '/^rgba?\(\s*[0-9.,%\s\/]+\)$/i', $value )
			|| preg_match( '/^var\(\s*--[a-z0-9\-]+\s*\)$/i', $value ) ) {
			return $value;
		}
		return $default;
	}
}

// ── sanitize attributes ─────────────────────────────────────────────────────
$columns      = max( 1, min( 6, (int) ( $attributes['columns'] ?? 3 ) ) );
$show_chevron = ! empty( $attributes['showChevron'] );
$modal        = ( 'link' !== strtolower( (string) ( $attributes['click'] ?? 'modal' ) ) ); // modal is the default
$primary      = bw_ct_color( $attributes['primaryColor'] ?? '', '#cc0000' );
$border       = bw_ct_color( $attributes['borderColor']  ?? '', '#d9d9d9' );

// Multi-taxonomy filters (new). Fall back to the legacy single-taxonomy
// attributes for blocks saved before multi-filter support.
$filters = array();
if ( ! empty( $attributes['filters'] ) && is_array( $attributes['filters'] ) ) {
	foreach ( $attributes['filters'] as $f ) {
		$filters[] = array(
			'tax'      => $f['tax'] ?? '',
			'terms'    => $f['terms'] ?? array(),
			'operator' => $f['operator'] ?? 'IN',
		);
	}
} elseif ( ! empty( $attributes['tax'] ) ) {
	$filters[] = array(
		'tax'      => $attributes['tax'],
		'terms'    => $attributes['terms'] ?? array(),
		'operator' => $attributes['relation'] ?? 'IN',
	);
}

$courses = bw_course_query( array(
	'filters'         => $filters,
	'filter_relation' => $attributes['filterRelation'] ?? 'AND',
	'orderby'         => $attributes['orderby'] ?? 'title',
	'order'           => $attributes['order'] ?? 'asc',
	'limit'           => $attributes['limit'] ?? 0,
	'exclude'         => $attributes['exclude'] ?? array(),
	'ap_only'         => ! empty( $attributes['apOnly'] ),
	'elective_only'   => ! empty( $attributes['electiveOnly'] ),
) );

if ( empty( $courses ) ) {
	return;
}

$chevron = $show_chevron ? '&nbsp;&gt;' : '';

// ── build grid markup (identical classes to bw/table-link courses grid) ──────
$grid_class = 'bw-tl__grid' . ( $modal ? ' bw-tl__grid--modal' : '' );
$inner_html = '<div class="' . $grid_class . '" style="--bw-tl-cols:' . (int) $columns . '">';
foreach ( $courses as $cell ) {
	if ( $modal && ! empty( $cell['id'] ) ) {
		// Real link to the course (works with JS off) + inert <template> with the
		// pop-up content. bw-table-link-view intercepts the click, prevents the
		// navigation, and clones the template into one shared modal.
		$href        = '' !== $cell['url'] ? ' href="' . esc_url( $cell['url'] ) . '"' : '';
		$inner_html .= '<div class="bw-tl__cell">'
			. '<a class="bw-tl__link bw-tl__modal-trigger"' . $href . ' aria-haspopup="dialog">'
			. esc_html( $cell['label'] ) . $chevron // $chevron is a safe literal entity
			. '</a>'
			. '<template class="bw-tl__course">' . bw_course_modal_html( $cell['id'] ) . '</template>' // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in helper
			. '</div>';
	} else {
		$inner = esc_html( $cell['label'] ) . $chevron; // $chevron is a safe literal entity
		if ( '' !== $cell['url'] ) {
			$link = '<a class="bw-tl__link" href="' . esc_url( $cell['url'] ) . '">' . $inner . '</a>';
		} else {
			$link = '<span class="bw-tl__link">' . $inner . '</span>';
		}
		$inner_html .= '<div class="bw-tl__cell">' . $link . '</div>';
	}
}
$inner_html .= '</div>';

// ── wrapper ──────────────────────────────────────────────────────────────────
// bw-tl + bw-tl--courses bring the shared grid/modal CSS; bw-course-table is a
// hook for any course-table-specific overrides (style.css).
$style = '--bw-tl-primary:' . esc_attr( $primary ) . ';--bw-tl-border:' . esc_attr( $border ) . ';';

printf(
	'<div %s>%s</div>',
	get_block_wrapper_attributes( array( 'class' => 'bw-tl bw-tl--courses bw-course-table', 'style' => $style ) ), // phpcs:ignore WordPress.Security.EscapeOutput
	$inner_html // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts above
);
