<?php
/**
 * Brentwood Calendar — front-end render (Phase 3).
 *
 * Server-renders the "Select Calendars" panel, the controls (start date, search,
 * per-page, timezone toggle), the first page of upcoming events, and the pager —
 * styled to mirror brentwood.ca/calendar. The list HTML comes from
 * bw_cal_render_list() (the SAME function the REST endpoint uses) so live updates
 * re-render identically. Interaction is driven by view.js via
 * GET /wp-json/bw/v1/calendar-events.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Unused (dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'bw_cal_get_events' ) ) {
	return;
}

$sources = bw_cal_sources();

$selected = ! empty( $attributes['calendars'] )
	? array_values( array_intersect( $attributes['calendars'], array_keys( $sources ) ) )
	: array_keys( array_filter( $sources, function ( $s ) {
		return ! empty( $s['default'] );
	} ) );

$per_page     = isset( $attributes['perPage'] ) ? max( 1, min( 50, (int) $attributes['perPage'] ) ) : 10;
$show_sidebar = ! isset( $attributes['showSidebar'] ) || false !== $attributes['showSidebar'];
$show_search  = ! isset( $attributes['showSearch'] ) || false !== $attributes['showSearch'];
$show_note    = ! isset( $attributes['showNote'] ) || false !== $attributes['showNote'];
$show_mini    = ! isset( $attributes['showMini'] ) || false !== $attributes['showMini'];

// The sidebar note is now editable InnerBlocks ($content). Older placements have no
// $content, so fall back to the original copy. (The editor rebuilds the sidebar
// itself and asks SSR only for the main column, so this sidebar markup — note
// included — runs only on the real front end.)
$default_note   = '<p>Dates of leaves may be subject to change. Families will be notified of any changes to these details.</p>'
	. '<p>PLEASE NOTE that, unless leave periods begin after academic classes (i.e., after the morning), they are marked here as beginning at <strong>3:00 am Pacific Time</strong>. That is because Brentwood Transportation typically begins driving students to airports, etc. as early as that time.</p>'
	. '<p>Please refer to our <a class="bw-cal__note-link" href="#">detailed Travel site</a> for details.</p>';
$note_html      = ( '' !== trim( (string) $content ) ) ? $content : $default_note;

$today = ( new DateTimeImmutable( 'today', new DateTimeZone( bw_cal_tz() ) ) )->format( 'Y-m-d' );

$result = bw_cal_get_events(
	array(
		'calendars'  => $selected,
		'per_page'   => $per_page,
		'page'       => 1,
		'start_date' => $today,
	)
);

$list_html = bw_cal_render_list( $result['events'], new DateTimeZone( bw_cal_tz() ) );
$pages     = (int) ceil( $result['total'] / max( 1, $per_page ) );
$mini      = bw_cal_mini_data( $selected, new DateTimeZone( bw_cal_tz() ), $today );
$marks     = $mini['marks'];

// The editor reconstructs the sidebar itself (so the note edits in place) and asks
// ServerSideRender for ONLY the main events column via ?bw_cal_part=main. Capture
// the main column once so it serves both the full render and that editor preview.
$cal_part = isset( $_GET['bw_cal_part'] ) ? sanitize_key( wp_unslash( $_GET['bw_cal_part'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only preview switch, no state change
ob_start();
?>
<section class="bw-cal__main">
	<header class="bw-cal__header">
		<span class="bw-cal__header-icon"><?php echo bw_cal_icon( 'calendar' ); // phpcs:ignore WordPress.Security.EscapeOutput ?></span>
		<span class="bw-cal__heading">Brentwood Calendars</span>
		<label class="bw-cal__startdate">
			<?php echo bw_cal_icon( 'calendar' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
			<span class="bw-cal__startdate-label">Start Date:</span>
			<input type="date" class="bw-cal__date-input" value="<?php echo esc_attr( $today ); ?>" />
		</label>
		<?php if ( $show_search ) : ?>
			<label class="bw-cal__search">
				<?php echo bw_cal_icon( 'search' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
				<input type="search" class="bw-cal__search-input" placeholder="Search Events" />
			</label>
		<?php endif; ?>
	</header>

	<div class="bw-cal__body">
		<div class="bw-cal__tz">
			<span class="bw-cal__tz-text">Timezone: <span class="bw-cal__tz-label">Brentwood (PDT)</span></span>
			<button type="button" class="bw-cal__tz-toggle" hidden></button>
		</div>

		<div class="bw-cal__list" aria-live="polite">
			<?php echo $list_html; // phpcs:ignore WordPress.Security.EscapeOutput ?>
		</div>

		<div class="bw-cal__footer">
			<span class="bw-cal__count"><?php echo esc_html( $result['total'] ); ?> Items</span>
			<div class="bw-cal__pager" data-page="1" data-pages="<?php echo esc_attr( $pages ); ?>"></div>
			<label class="bw-cal__perpage">
				<span>Per Page</span>
				<input type="number" class="bw-cal__perpage-input" value="<?php echo esc_attr( $per_page ); ?>" min="5" max="50" step="5" />
			</label>
		</div>
	</div>
</section>
<?php
$main_html = ob_get_clean();

// Editor preview: hand back only the main column.
if ( 'main' === $cal_part ) {
	echo $main_html; // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts above
	return;
}

$wrapper = get_block_wrapper_attributes(
	array(
		'class' => 'bw-cal' . ( $show_sidebar ? '' : ' bw-cal--no-sidebar' ),
	)
);
?>
<div <?php echo $wrapper; // phpcs:ignore WordPress.Security.EscapeOutput ?>
	data-rest="<?php echo esc_url( rest_url( 'bw/v1/calendar-events' ) ); ?>"
	data-nonce="<?php echo esc_attr( wp_create_nonce( 'wp_rest' ) ); ?>"
	data-home-tz="<?php echo esc_attr( bw_cal_tz() ); ?>"
	data-home-tz-label="Brentwood (PDT)"
	data-perpage="<?php echo esc_attr( $per_page ); ?>"
	data-start="<?php echo esc_attr( $today ); ?>"
	data-marks="<?php echo esc_attr( wp_json_encode( $marks ) ); ?>">

	<?php if ( $show_sidebar ) : ?>
	<aside class="bw-cal__sidebar">
		<div class="bw-cal__sidebar-title"><?php echo esc_html( count( $selected ) > 1 ? 'Select Calendars' : 'Calendars' ); ?></div>
		<ul class="bw-cal__calendars">
			<?php foreach ( $selected as $key ) : $src = $sources[ $key ]; ?>
				<li class="bw-cal__calendar">
					<label class="bw-cal__cal-toggle">
						<input type="checkbox" class="bw-cal__cal-check"
							value="<?php echo esc_attr( $key ); ?>"
							<?php checked( true ); ?> />
						<span class="bw-cal__cal-icon">
							<span class="bw-cal__cal-on"><?php echo bw_cal_icon( 'check-circle' ); // phpcs:ignore WordPress.Security.EscapeOutput ?></span>
							<span class="bw-cal__cal-off"><?php echo bw_cal_icon( 'circle' ); // phpcs:ignore WordPress.Security.EscapeOutput ?></span>
						</span>
						<span class="bw-cal__cal-name"><?php echo esc_html( $src['label'] ); ?></span>
					</label>
					<a class="bw-cal__add"
						href="<?php echo esc_url( bw_cal_webcal_url( $src['gid'] ), array( 'webcal' ) ); ?>">
						<?php echo bw_cal_icon( 'calendar' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>
						<span>Add to my Calendar</span>
					</a>
				</li>
			<?php endforeach; ?>
		</ul>

		<?php if ( $show_note ) : ?>
		<div class="bw-cal__note"><?php echo $note_html; // phpcs:ignore WordPress.Security.EscapeOutput -- InnerBlocks self-escape; default copy is a trusted literal ?></div>
		<?php endif; ?>

		<?php if ( $show_mini ) : ?>
		<div class="bw-cal__mini" aria-label="Events calendar"></div>
		<script type="application/json" class="bw-cal__events-data"><?php echo wp_json_encode( $mini['events'], JSON_HEX_TAG | JSON_HEX_AMP ); // phpcs:ignore WordPress.Security.EscapeOutput ?></script>
		<?php endif; ?>
	</aside>
	<?php endif; ?>

	<?php echo $main_html; // phpcs:ignore WordPress.Security.EscapeOutput -- assembled from escaped parts above ?>
</div>
