<?php
/**
 * Seed a small set of news/blog posts on theme activation.
 *
 * Runs once; the guard checks an option so the posts are never
 * re-imported if the admin deletes them intentionally.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

/**
 * Create sample blog posts if they haven't been seeded yet.
 */
function northfield_seed_sample_posts() {
	if ( get_option( 'northfield_sample_posts_seeded' ) ) {
		return;
	}

	$posts = array(
		array(
			'title'    => 'Announcing our 2026–27 season',
			'slug'     => 'announcing-our-2026-27-season',
			'category' => 'Season news',
			'date'     => '2026-04-12 09:00:00',
			'excerpt'  => 'Thirty-two productions, a new partnership with Moorside Town Hall, and our first full year under Artistic Director Davinia Okonkwo.',
			'content'  => "Today we're thrilled to unveil our 2026–27 season — the first programmed in full by our new Artistic Director, Davinia Okonkwo.\n\nThe season opens in September with a bold new production of *Antigone*, directed by Rebecca Frecknall and co-produced with the Almeida. It's followed by a tour-de-force revival of *The Glass Menagerie* starring Maxine Peake, and a Christmas revival of *A Christmas Carol* that promises to become a new Yorkshire tradition.\n\nWe're equally proud to announce a new partnership with **Moorside Town Hall**: eight productions will tour across both houses, including a specially commissioned site-responsive piece from Yorkshire-based company Common Wealth.\n\nSeason tickets go on general sale on Monday 28 April at 10am; members and priority subscribers have access from Friday 25 April.\n\nWe can't wait to welcome you back.",
		),
		array(
			'title'    => 'In conversation with Marcus Okonkwo',
			'slug'     => 'in-conversation-with-marcus-okonkwo',
			'category' => 'Interviews',
			'date'     => '2026-04-05 10:30:00',
			'excerpt'  => 'Our Hamlet sits down with us to talk surveillance, grief, and why Yorkshire is the best possible place to open this show.',
			'content'  => "Marcus Okonkwo arrives at the stage door ten minutes early, in a cap and a long wool coat, and apologises — there's no need — for the cold he's been battling through rehearsals.\n\n\"I've been saving my voice,\" he explains, unwrapping a lozenge. \"Anya keeps asking me to shout less, but you try shouting less as Hamlet.\"\n\nIt's the Wednesday before the first preview, and our production of *Hamlet* — directed by Anya Kapoor, the newest addition to the theatre's associate artist roster — is taking shape at pace. The concept: a Hamlet set in a surveillance state, where Elsinore's corridors are lined with cameras and every soliloquy is potentially being logged.\n\n\"It's not a gimmick,\" Marcus insists. \"Or — well, I hope it isn't. What Anya's doing is asking: what does it mean to grieve in private, when privacy isn't possible any more? That's a question I think everyone my age understands. Every WhatsApp you send is archived somewhere. The idea of having a truly private thought feels increasingly quaint.\"\n\nHamlet opens at Northfield Theatre on 15 May. Marcus Okonkwo plays Hamlet. Tickets from £15.",
		),
		array(
			'title'    => 'Access programme for spring/summer',
			'slug'     => 'access-programme-spring-summer-2026',
			'category' => 'Access',
			'date'     => '2026-03-28 12:00:00',
			'excerpt'  => 'BSL, captioned, audio-described and relaxed performances across every main-house production this spring and summer.',
			'content'  => "Every main-house production this spring and summer has at least one access-adapted performance scheduled. Here's the full list:\n\n**Hamlet**\n- BSL: 17 May, 2:30pm\n- Captioned: 21 May, 7:30pm\n- Audio described: 17 May, 7:30pm (pre-show touch tour at 6pm)\n\n**The Gruffalo Live**\n- Relaxed: 28 May, 11am\n\n**Swan Lake**\n- Captioned: 15 July, 7:30pm\n- Audio described: 11 July, 2:30pm\n\n**Room on the Broom**\n- Relaxed: 10 June, 11am\n\n**The Glass Menagerie**\n- BSL: 22 August, 2:30pm\n- Audio described: 20 August, 7:30pm\n\nAccess bookings can be made by calling our priority line on **01484 567 891** or emailing **access@northfieldtheatre.co.uk**. Essential companions receive a complimentary ticket. Wheelchair spaces are available in both the stalls and the Dress Circle.\n\nAs always, we welcome feedback on how we can keep improving our access offer — please get in touch.",
		),
		array(
			'title'    => 'Review: A Midsummer Night\'s Dream at Northfield',
			'slug'     => 'review-midsummer-nights-dream',
			'category' => 'Reviews',
			'date'     => '2026-03-20 15:00:00',
			'excerpt'  => '"Shakespeare to fall in love with." Read what the critics made of Sam Clarkson\'s summer revival.',
			'content'  => "Our summer revival of *A Midsummer Night's Dream*, directed by Sam Clarkson, opened last week to a warm critical reception. A selection of reviews below.\n\n> *The Stage*: \"A mischievous, folkloric production that never once feels dutiful. Clarkson's Puck — a startling Niamh Doran, moving through the auditorium on silks — is the best I've seen in years. ★★★★★\"\n\n> *The Guardian*: \"Every bit as enchanting as it sounds. Bottom's transformation lands a genuine shiver; the mechanicals' play-within-a-play is laugh-out-loud funny. This is Shakespeare you can bring a ten-year-old to. ★★★★\"\n\n> *Yorkshire Post*: \"A love letter to the Dales, dressed up as a love letter to Shakespeare. We left smelling of bracken. ★★★★\"\n\n> *WhatsOnStage*: \"Northfield's ensemble company at their confident best. ★★★★\"\n\n*A Midsummer Night's Dream* runs in the Main Auditorium until 14 June. Tickets from £12.",
		),
		array(
			'title'    => 'Meet the Studio new-writing cohort',
			'slug'     => 'meet-the-studio-new-writing-cohort',
			'category' => 'Studio',
			'date'     => '2026-03-12 10:00:00',
			'excerpt'  => 'Six writers, one Studio, eighteen months. Meet the playwrights joining our new-writing attachment programme in April.',
			'content'  => "In April we welcome six playwrights into the Studio for an eighteen-month attachment programme, developed with the generous support of the Paul Hamlyn Foundation.\n\nOver the course of the attachment, each writer will develop one new play with dramaturgical support from our Studio Producer, Tomás Riera; a guaranteed rehearsed reading; and a bursary of £6,000. Two of the six plays will be selected for full production in our Studio in 2028.\n\nWe are delighted to introduce the 2026 cohort:\n\n- **Isla Muirhead** (Leeds) — writing about ageing and artificial memory\n- **Omar Diallo** (Bradford) — a verbatim piece set in a suburban mosque\n- **Greta Hanssen** (Hebden Bridge) — a solo play about an end-of-life doula\n- **Ruairi McGrath** (Huddersfield) — a Gaelic-language comedy about moving house\n- **Priya Mehta** (Halifax, joining as writer-in-residence for the season)\n- **Darren Buckley** (Moorside) — writing about the closure of a working men's club\n\nWelcome to all of them. Keep an eye on our What's On listings for rehearsed readings from September.",
		),
	);

	foreach ( $posts as $post ) {
		// Skip if a post with this slug already exists.
		$existing = get_page_by_path( $post['slug'], OBJECT, 'post' );
		if ( $existing ) {
			continue;
		}

		$content = northfield_convert_markdown_to_blocks( $post['content'] );

		$post_id = wp_insert_post( array(
			'post_type'    => 'post',
			'post_title'   => $post['title'],
			'post_name'    => $post['slug'],
			'post_content' => $content,
			'post_excerpt' => $post['excerpt'],
			'post_status'  => 'publish',
			'post_date'    => $post['date'],
		) );

		if ( ! is_wp_error( $post_id ) && ! empty( $post['category'] ) ) {
			$cat_id = wp_create_category( $post['category'] );
			if ( ! is_wp_error( $cat_id ) ) {
				wp_set_post_categories( $post_id, array( $cat_id ) );
			}
		}
	}

	update_option( 'northfield_sample_posts_seeded', 1 );
}
add_action( 'after_switch_theme', 'northfield_seed_sample_posts', 40 );

/**
 * The repair tool (Tools → Northfield Repair) rebuilds sample posts
 * for existing installs. No admin_init hook — that caused worker
 * starvation on concurrent admin requests.
 */

/**
 * Convert a subset of markdown (paragraphs, ** bold, * italic, > quotes,
 * list items with -) to Gutenberg block markup.
 *
 * @param string $text The markdown source text.
 * @return string Gutenberg block markup.
 */
function northfield_convert_markdown_to_blocks( $text ) {
	$paragraphs = preg_split( '/\n\n+/', trim( $text ) );
	$blocks     = array();

	foreach ( $paragraphs as $para ) {
		$para = trim( $para );
		if ( '' === $para ) {
			continue;
		}

		// Blockquote.
		if ( str_starts_with( $para, '> ' ) ) {
			$quote = substr( $para, 2 );
			$quote = northfield_apply_inline_formatting( $quote );
			$blocks[] = "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>" . $quote . "</p></blockquote>\n<!-- /wp:quote -->";
			continue;
		}

		// Unordered list: a block of lines all starting with "- "
		$lines = preg_split( '/\n/', $para );
		$is_list = true;
		foreach ( $lines as $line ) {
			if ( ! str_starts_with( trim( $line ), '- ' ) ) {
				$is_list = false;
				break;
			}
		}

		if ( $is_list ) {
			$items = array_map( function ( $line ) {
				$line = ltrim( trim( $line ), '- ' );
				return '<li>' . northfield_apply_inline_formatting( $line ) . '</li>';
			}, $lines );
			$blocks[] = "<!-- wp:list -->\n<ul class=\"wp-block-list\">" . implode( '', $items ) . "</ul>\n<!-- /wp:list -->";
			continue;
		}

		// Paragraph.
		$html = northfield_apply_inline_formatting( $para );
		$blocks[] = "<!-- wp:paragraph -->\n<p>" . $html . "</p>\n<!-- /wp:paragraph -->";
	}

	return implode( "\n\n", $blocks );
}

/**
 * Apply inline markdown formatting: **bold** and *italic*.
 *
 * @param string $text Raw text.
 * @return string HTML-safe text with inline formatting.
 */
function northfield_apply_inline_formatting( $text ) {
	$text = esc_html( $text );
	$text = preg_replace( '/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text );
	$text = preg_replace( '/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/', '<em>$1</em>', $text );
	return $text;
}
