<?php
/**
 * Brentwood Table Link — front-end render.
 *
 * A set of editable link items rendered in one of two variants:
 *   - "table": a real <table> with N equal columns; cells are centred links with
 *     an optional "›". An item flagged full-width gets its own row spanning all
 *     columns (colspan), like the "University Placement" row on brentwood.ca.
 *   - "grid": a link grid — N columns of bordered boxes (bottom border,
 *     rounded top, hover turns the border the primary colour), centred links.
 *
 * Rows follow automatically from the item count and the column setting.
 *
 * (A dynamic grid of courses lives in its own block, bw/course-table.)
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused — dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'bw_tl_color' ) ) {
	function bw_tl_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;
	}
}

if ( ! function_exists( 'bw_tl_link' ) ) {
	function bw_tl_link( $cell, $chevron, $extra_class = '' ) {
		$inner = esc_html( $cell['label'] ) . $chevron; // $chevron is a safe literal entity
		$cls   = 'bw-tl__link' . ( '' !== $extra_class ? ' ' . $extra_class : '' );
		if ( '' !== $cell['url'] ) {
			// Open in a new tab when flagged (handy for external links); rel
			// keeps the new tab from getting a handle back to this window.
			$target = ! empty( $cell['newTab'] )
				? ' target="_blank" rel="noopener noreferrer"'
				: '';
			return '<a class="' . esc_attr( $cls ) . '" href="' . esc_url( $cell['url'] ) . '"' . $target . '>' . $inner . '</a>';
		}
		return '<span class="' . esc_attr( $cls ) . '">' . $inner . '</span>';
	}
}

// ── sanitize attributes ─────────────────────────────────────────────────────
$variant_raw = $attributes['variant'] ?? 'table';
$variant     = ( 'grid' === $variant_raw ) ? 'grid' : 'table';
$columns      = max( 1, min( 6, (int) ( $attributes['columns'] ?? 2 ) ) );
$show_chevron = ! empty( $attributes['showChevron'] );
$primary      = bw_tl_color( $attributes['primaryColor'] ?? '', '#cc0000' );
$border       = bw_tl_color( $attributes['borderColor']  ?? '', '#d9d9d9' );

$text_align = $attributes['textAlign'] ?? 'center';
if ( ! in_array( $text_align, array( 'left', 'center', 'right' ), true ) ) {
	$text_align = 'center';
}
$justify_map = array( 'left' => 'flex-start', 'center' => 'center', 'right' => 'flex-end' );
$justify     = $justify_map[ $text_align ];

$valid = array();
$items = is_array( $attributes['items'] ?? null ) ? $attributes['items'] : array();
foreach ( $items as $it ) {
	$label = sanitize_text_field( $it['label'] ?? '' );
	if ( '' === $label ) {
		continue;
	}
	$valid[] = array(
		'label'  => $label,
		'url'    => esc_url_raw( $it['url'] ?? '' ),
		'full'   => ! empty( $it['fullWidth'] ),
		'newTab' => ! empty( $it['newTab'] ),
	);
}

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

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

// ── build variant markup ─────────────────────────────────────────────────────
if ( 'table' === $variant ) {
	// Group items into rows of $columns; a full-width item owns a colspan row.
	$rows = array();
	$buf  = array();
	foreach ( $valid as $cell ) {
		if ( $cell['full'] ) {
			if ( $buf ) {
				$rows[] = array( 'cells' => $buf );
				$buf    = array();
			}
			$rows[] = array( 'cells' => array( $cell ), 'span' => $columns );
		} else {
			$buf[] = $cell;
			if ( count( $buf ) === $columns ) {
				$rows[] = array( 'cells' => $buf );
				$buf    = array();
			}
		}
	}
	if ( $buf ) {
		$rows[] = array( 'cells' => $buf, 'pad' => true );
	}

	$inner_html = '<table class="bw-tl__table"><tbody>';
	foreach ( $rows as $row ) {
		$cells = $row['cells'];
		$n     = count( $cells );
		$inner_html .= '<tr>';
		foreach ( $cells as $cell ) {
			// Only an explicit full-width item spans; a short final row keeps each
			// item in its own column and pads the remainder with empty cells below.
			$colspan = ! empty( $row['span'] ) ? (int) $row['span'] : 1;
			$cs = ( $colspan > 1 ) ? ' colspan="' . $colspan . '"' : '';
			$inner_html .= '<td' . $cs . '>' . bw_tl_link( $cell, $chevron ) . '</td>';
		}
		// Pad a short final row with empty cells so a lone last item stays in its
		// column instead of stretching across the row (matches the editor layout).
		if ( ! empty( $row['pad'] ) && $n < $columns ) {
			$inner_html .= str_repeat( '<td></td>', $columns - $n );
		}
		$inner_html .= '</tr>';
	}
	$inner_html .= '</tbody></table>';
} else {
	$inner_html = '<div class="bw-tl__grid" style="--bw-tl-cols:' . (int) $columns . '">';
	foreach ( $valid as $cell ) {
		$full = $cell['full'] ? ' bw-tl__cell--full' : '';
		$inner_html .= '<div class="bw-tl__cell' . $full . '">' . bw_tl_link( $cell, $chevron ) . '</div>';
	}
	$inner_html .= '</div>';
}

// ── wrapper ──────────────────────────────────────────────────────────────────
$style = '--bw-tl-primary:' . esc_attr( $primary ) . ';--bw-tl-border:' . esc_attr( $border )
	. ';--bw-tl-align:' . esc_attr( $text_align ) . ';--bw-tl-justify:' . esc_attr( $justify ) . ';';

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