<?php
/**
 * Brentwood Careers — front-end render.
 *
 * Outputs every published `bw_career` posting as:
 *   1. the posting description (the post body),
 *   2. an apply row: the "Open Message" (ACF `career_open_message`) beside an
 *      "Apply Now" button pointing at "Button Link" (`career_button_link`),
 *   3. a divider,
 * mirroring the stacked list on brentwood.ca/careers.
 *
 * The layout is deliberately fixed (single stacked column, always divided, all
 * postings shown) — it mirrors the live page, so there is nothing to configure.
 * Ordering is `menu_order` then newest-first, so the client can hand-order
 * postings via Page Attributes and new ones otherwise float to the top.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused — dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

$button_label = trim( (string) ( $attributes['buttonLabel'] ?? '' ) );
$empty_text   = trim( (string) ( $attributes['emptyText'] ?? '' ) );

if ( '' === $button_label ) {
	$button_label = __( 'Apply Now', 'kadence-child' );
}

if ( ! post_type_exists( 'bw_career' ) ) {
	return;
}

/**
 * Normalise the "Button Link" field so editors don't have to know about URL
 * schemes: a bare email address becomes a mailto: link. Anything that already
 * carries a scheme (or is a root-relative / anchor link) is left alone.
 *
 * @param string $link Raw field value.
 * @return string
 */
$bw_career_link = static function ( $link ) {
	$link = trim( (string) $link );
	if ( '' === $link ) {
		return '';
	}
	// Already an explicit scheme, a root-relative path, or an anchor — leave it.
	if ( preg_match( '#^(https?:|mailto:|tel:|/|\#)#i', $link ) ) {
		return $link;
	}
	// "hr@brentwood.ca" (or "Name <hr@brentwood.ca>" style values) → mailto:.
	if ( is_email( $link ) ) {
		return 'mailto:' . $link;
	}
	// A bare domain like "brentwood.ca/apply" → treat as an external URL.
	if ( preg_match( '#^[a-z0-9-]+(\.[a-z0-9-]+)+(/|$)#i', $link ) ) {
		return 'https://' . $link;
	}
	return $link;
};

$q = new WP_Query(
	array(
		'post_type'              => 'bw_career',
		'post_status'            => 'publish',
		'posts_per_page'         => -1,
		'orderby'                => array(
			'menu_order' => 'ASC',
			'date'       => 'DESC',
		),
		'no_found_rows'          => true,
		'ignore_sticky_posts'    => true,
		'update_post_term_cache' => false,
	)
);

if ( ! $q->have_posts() ) {
	if ( '' === $empty_text ) {
		return;
	}
	printf(
		'<div %s><p class="bw-careers__empty">%s</p></div>',
		get_block_wrapper_attributes( array( 'class' => 'bw-careers' ) ), // phpcs:ignore WordPress.Security.EscapeOutput
		esc_html( $empty_text )
	);
	return;
}

$items = '';

foreach ( $q->posts as $p ) {
	$msg  = trim( (string) get_post_meta( $p->ID, 'career_open_message', true ) );
	$link = $bw_career_link( get_post_meta( $p->ID, 'career_button_link', true ) );

	// Render the body with WordPress's OWN content transforms only — do NOT run
	// apply_filters( 'the_content' ) here.
	//
	// This block renders inside the host page's main loop, so in_the_loop() and
	// is_main_query() are both still true. Anything hooked to the_content that
	// gates on those (the theme's hero injector in inc/brentwood-hero.php, for
	// one) therefore fires for every posting and injects PAGE-level content —
	// which is how the Careers page hero ended up repeated above all 5 postings.
	// Applying the core filters directly renders blocks, shortcodes, paragraphs
	// and responsive images correctly with no third-party injection.
	$GLOBALS['post'] = $p; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	setup_postdata( $p );

	$desc = do_blocks( $p->post_content );
	$desc = wptexturize( $desc );
	$desc = convert_smilies( $desc );
	$desc = wpautop( $desc );
	$desc = shortcode_unautop( $desc );
	$desc = do_shortcode( $desc );
	$desc = wp_filter_content_tags( $desc );

	wp_reset_postdata();

	$item = '<article class="bw-careers__item">';

	if ( '' !== trim( (string) $desc ) ) {
		$item .= '<div class="bw-careers__desc">' . $desc . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- the_content output.
	}

	if ( '' !== $msg || '' !== $link ) {
		$item .= '<p class="bw-careers__apply">';
		if ( '' !== $msg ) {
			$item .= '<span class="bw-careers__msg">' . esc_html( $msg ) . '</span>';
		}
		if ( '' !== $link ) {
			$external = ( 0 === stripos( $link, 'http' ) );
			$item    .= '<a class="bw-careers__btn" href="' . esc_url( $link ) . '"'
				. ( $external ? ' target="_blank" rel="noopener noreferrer"' : '' )
				. '>' . esc_html( $button_label ) . '</a>';
		}
		$item .= '</p>';
	}

	$item .= '</article>';
	$item .= '<hr class="bw-careers__divider" />';

	$items .= $item;
}

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