<?php
/**
 * Expanded, duplicate-safe Sanctuary demo content.
 *
 * Scripture quotations are from the public-domain King James Version.
 * External guest videos remain hosted by their publishers and are clearly
 * identified as guest resources rather than Sanctuary Baptist productions.
 *
 * @package Sanctuary
 */

defined( 'ABSPATH' ) || exit;

/** Return a normalized KJV passage for DIY Sermons. */
function sanctuary_kjv_passage( $book, $book_name, $chapter, $start, $end, $text ) {
	return array(
		'translation' => 'eng_kjv',
		'book'        => $book,
		'book_name'   => $book_name,
		'chapter'     => absint( $chapter ),
		'verse_start' => absint( $start ),
		'verse_end'   => absint( $end ),
		'text'        => $text,
		'attribution' => 'King James Version (public domain)',
	);
}

/** Image assets used by the richer sermon, event, and portfolio demo. */
function sanctuary_demo_assets() {
	$files = array(
		'sermon_love'       => 'sermon-bible.webp',
		'sermon_shepherd'   => 'sermon-mountains.webp',
		'sermon_grace'      => 'sermon-cross.webp',
		'sermon_anchor'     => 'demo/sermon-anchor.webp',
		'sermon_potter'     => 'demo/sermon-potter.webp',
		'sermon_family'     => 'demo/sermon-family-bible.webp',
		'sermon_prayer'     => 'demo/sermon-prayer.webp',
		'sermon_harvest'    => 'demo/sermon-harvest.webp',
		'sermon_lamp'       => 'demo/sermon-lamp.webp',
		'sermon_fellowship' => 'demo/sermon-fellowship.webp',
		'sermon_guest_paul' => 'demo/sermon-path.webp',
		'sermon_guest_billy'=> 'demo/sermon-risen.webp',
		'sermon_guest_voddie' => 'demo/sermon-family-bible.webp',
		'event_worship'     => 'demo/event-worship.webp',
		'event_groups'      => 'demo/event-bible-study.webp',
		'event_service'     => 'demo/event-outreach.webp',
		'event_fellowship'  => 'demo/event-picnic.webp',
		'event_youth'       => 'demo/event-youth-retreat.webp',
		'event_women'       => 'demo/event-women.webp',
		'event_men'         => 'demo/event-men.webp',
		'event_vbs'         => 'demo/event-vbs.webp',
		'event_missions'    => 'demo/event-missions.webp',
		'portfolio_baptism' => 'demo/portfolio-baptism.webp',
		'portfolio_choir'   => 'demo/portfolio-choir.webp',
		'portfolio_pantry'  => 'demo/portfolio-pantry.webp',
		'portfolio_family'  => 'demo/portfolio-family.webp',
		'pastor_jonathan'   => 'demo/pastor-jonathan-reed.png',
		'pastor_michael'    => 'demo/pastor-michael-carter.png',
		'pastor_caleb'      => 'demo/pastor-caleb-morris.png',
	);

	$assets = array();
	foreach ( $files as $key => $file ) {
		$assets[ $key ] = array(
			'file'  => 'assets/images/' . $file,
			'title' => ucwords( str_replace( '_', ' ', $key ) ),
		);
	}
	return $assets;
}

/** Additional speakers, sermons, events, and the reusable ministry portfolio. */
function sanctuary_demo_records() {
	$audio_base = trailingslashit( get_stylesheet_directory_uri() ) . 'assets/audio/';
	$portfolio_base = trailingslashit( get_stylesheet_directory_uri() ) . 'assets/images/demo/';
	$audio_one  = get_stylesheet_directory() . '/assets/audio/anchored-in-the-storm.wav';
	$audio_two  = get_stylesheet_directory() . '/assets/audio/a-lamp-unto-my-feet.wav';

	$records = array(
		array(
			'key' => 'speaker_discipleship', 'post_type' => 'diy_speaker', 'title' => 'Pastor Caleb Morris',
			'content' => '<p>Caleb helps adults and families grow through Bible study, small groups, personal discipleship, and practical opportunities to serve.</p>',
			'excerpt' => 'Caleb equips adults and families to grow in Scripture, Christian fellowship, and faithful service.',
			'featured' => 'pastor_caleb',
			'meta' => array( '_diy_speaker_role' => 'Discipleship Pastor', '_diy_speaker_type' => 'staff', '_diy_speaker_status' => 'active', '_diy_speaker_primary_campus' => '@record:campus_main', '_diy_speaker_campuses' => array( '@record:campus_main', '@record:campus_north' ), '_diy_speaker_history' => 'Served in small-group, family, and discipleship ministry before joining the pastoral staff.', '_diy_speaker_education' => 'Biblical studies and Christian discipleship training.', '_diy_speaker_credentials' => 'Licensed gospel minister', '_diy_speaker_testimony' => 'Trusted Christ through the faithful teaching and witness of a local church.', '_diy_speaker_family' => 'Enjoys reading, hospitality, and serving alongside church families.' ),
		),
		array(
			'key' => 'speaker_billy_graham', 'post_type' => 'diy_speaker', 'title' => 'Billy Graham',
			'content' => '<p>Billy Graham was an evangelist whose ministry proclaimed the gospel of Jesus Christ around the world. This profile is included only to demonstrate an externally hosted guest message.</p>',
			'excerpt' => 'Guest evangelist resource',
			'meta' => array( '_diy_speaker_role' => 'Guest Evangelist', '_diy_speaker_type' => 'guest', '_diy_speaker_status' => 'guest', '_diy_speaker_website' => 'https://billygraham.org/' ),
		),
		array(
			'key' => 'speaker_paul_washer', 'post_type' => 'diy_speaker', 'title' => 'Paul Washer',
			'content' => '<p>Paul Washer is a preacher and the founder of HeartCry Missionary Society. This profile is included only to demonstrate an externally hosted guest message.</p>',
			'excerpt' => 'Guest preacher resource',
			'meta' => array( '_diy_speaker_role' => 'Guest Preacher', '_diy_speaker_type' => 'guest', '_diy_speaker_status' => 'guest', '_diy_speaker_website' => 'https://heartcrymissionary.com/' ),
		),
		array(
			'key' => 'speaker_voddie_baucham', 'post_type' => 'diy_speaker', 'title' => 'Voddie Baucham',
			'content' => '<p>Voddie Baucham was a pastor, preacher, author, and theological educator known for clear biblical exposition. This profile is included only to demonstrate an externally hosted guest message.</p>',
			'excerpt' => 'Guest preacher resource',
			'meta' => array( '_diy_speaker_role' => 'Guest Preacher', '_diy_speaker_type' => 'guest', '_diy_speaker_status' => 'guest', '_diy_speaker_website' => 'https://www.voddiebaucham.org/' ),
		),
	);

	$sermons = array(
		array(
			'key' => 'sermon_anchor', 'title' => 'Anchored in the Storm', 'featured' => 'sermon_anchor', 'date' => '-28 days',
			'excerpt' => 'Christian hope is secure because it rests in the finished work and unchanging promise of Christ.',
			'content' => '<p>Storms reveal what our confidence rests upon. Hebrews points weary believers beyond changing circumstances to the promise and character of God.</p><p>Our hope is not wishful thinking. It enters within the veil and rests in Jesus Christ, our faithful forerunner.</p>',
			'series' => 'Steadfast Hope', 'topics' => array( 'Hope', 'Perseverance' ), 'book' => 'Hebrews', 'speaker' => '@record:speaker_lead', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'HEB', 'Hebrews', 6, 19, 20, 'Which hope we have as an anchor of the soul, both sure and stedfast, and which entereth into that within the veil; Whither the forerunner is for us entered, even Jesus.' ),
			'transcript' => 'The anchor of the Christian soul is not lowered into the shifting sea beneath us. It is fastened in heaven itself, where Christ has entered for us. Because He is faithful, hope can remain steady when life does not.',
			'audio' => $audio_base . 'anchored-in-the-storm.wav', 'size' => file_exists( $audio_one ) ? filesize( $audio_one ) : 0, 'duration' => '00:16',
		),
		array(
			'key' => 'sermon_potter', 'title' => 'The Potter and the Clay', 'featured' => 'sermon_potter', 'date' => '-35 days',
			'excerpt' => 'God is patient and purposeful as He shapes yielded lives for His glory.',
			'content' => '<p>Jeremiah watched a potter patiently reshape a marred vessel. The picture calls God’s people to humble repentance and renewed trust.</p><p>The Potter does not discard the clay that yields to His hands; He forms it according to His wise purpose.</p>',
			'series' => 'Pictures of Grace', 'topics' => array( 'Surrender', 'Sanctification' ), 'book' => 'Jeremiah', 'speaker' => '@record:speaker_associate', 'campus' => '@record:campus_north',
			'scripture' => sanctuary_kjv_passage( 'JER', 'Jeremiah', 18, 3, 6, 'Then I went down to the potter’s house, and, behold, he wrought a work on the wheels. And the vessel that he made of clay was marred in the hand of the potter: so he made it again another vessel, as seemed good to the potter to make it.' ),
			'transcript' => 'The Potter has both authority and skill. His correction is not careless, and His purpose is not cruel. The proper response of the clay is humble surrender to the One whose hands are wise and good.',
		),
		array(
			'key' => 'sermon_family', 'title' => 'A House Built on the Word', 'featured' => 'sermon_family', 'date' => '-42 days',
			'excerpt' => 'Homes grow strong when God’s Word becomes part of ordinary conversation and daily obedience.',
			'content' => '<p>Faithful discipleship begins with loving God wholeheartedly and speaking His truth naturally in the rhythms of home.</p><p>This message offers practical encouragement for parents, grandparents, and every believer who influences the next generation.</p>',
			'series' => 'Faith at Home', 'topics' => array( 'Family', 'Discipleship' ), 'book' => 'Deuteronomy', 'speaker' => '@record:speaker_lead', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'DEU', 'Deuteronomy', 6, 5, 7, 'And thou shalt love the LORD thy God with all thine heart, and with all thy soul, and with all thy might. And these words, which I command thee this day, shall be in thine heart: And thou shalt teach them diligently unto thy children.' ),
			'transcript' => 'God’s design is not limited to one weekly lesson. His Word is to be in our hearts and then in our conversations—when we sit, walk, lie down, and rise up. The home becomes a place where truth is both spoken and lived.',
		),
		array(
			'key' => 'sermon_prayer', 'title' => 'The Church at Prayer', 'featured' => 'sermon_prayer', 'date' => '-49 days',
			'excerpt' => 'A praying church asks for holy boldness, trusts God’s sovereignty, and speaks His Word together.',
			'content' => '<p>When the early church faced opposition, believers did not first pray for comfort. They remembered God’s sovereignty and asked for courage to keep speaking.</p><p>Their united prayer still teaches the church how to respond faithfully in uncertain times.</p>',
			'series' => 'Life Together', 'topics' => array( 'Prayer', 'Church' ), 'book' => 'Acts', 'speaker' => '@record:speaker_associate', 'campus' => '@record:campus_north',
			'scripture' => sanctuary_kjv_passage( 'ACT', 'Acts', 4, 29, 31, 'And now, Lord, behold their threatenings: and grant unto thy servants, that with all boldness they may speak thy word... And when they had prayed, the place was shaken where they were assembled together.' ),
			'transcript' => 'The church prayed with Scripture in mind, God’s sovereignty in view, and gospel boldness as the request. Prayer did not lead them away from mission; prayer prepared them for mission.',
		),
		array(
			'key' => 'sermon_harvest', 'title' => 'The Lord of the Harvest', 'featured' => 'sermon_harvest', 'date' => '-56 days',
			'excerpt' => 'The compassion of Jesus moves His people to pray, go, and serve in the harvest He owns.',
			'content' => '<p>Jesus saw scattered people with compassion and called His disciples to pray for laborers.</p><p>Mission begins with His heart, depends on His authority, and sends ordinary believers into fields that are ready.</p>',
			'series' => 'Sent', 'topics' => array( 'Missions', 'Evangelism' ), 'book' => 'Matthew', 'speaker' => '@record:speaker_lead', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'MAT', 'Matthew', 9, 37, 38, 'Then saith he unto his disciples, The harvest truly is plenteous, but the labourers are few; Pray ye therefore the Lord of the harvest, that he will send forth labourers into his harvest.' ),
			'transcript' => 'Christ does not look upon the crowds with annoyance but with compassion. The harvest belongs to Him. Our first response is prayer, and our faithful response is willingness to be sent.',
		),
		array(
			'key' => 'sermon_lamp', 'title' => 'A Lamp unto My Feet', 'featured' => 'sermon_lamp', 'date' => '-63 days',
			'excerpt' => 'God’s Word gives sufficient light for faithful obedience one step at a time.',
			'content' => '<p>We often want God to reveal the entire road ahead. Psalm 119 promises something better: trustworthy light for the step He has placed before us.</p><p>Scripture guards, guides, corrects, and comforts every believer who receives it with faith.</p>',
			'series' => 'Delighting in the Word', 'topics' => array( 'Bible', 'Guidance' ), 'book' => 'Psalms', 'speaker' => '@record:speaker_associate', 'campus' => '@record:campus_north',
			'scripture' => sanctuary_kjv_passage( 'PSA', 'Psalms', 119, 105, 105, 'Thy word is a lamp unto my feet, and a light unto my path.' ),
			'transcript' => 'The lamp does not reveal every mile at once. It gives enough light for faithful obedience now. We learn to walk by opening God’s Word, receiving it humbly, and taking the next step it makes clear.',
			'audio' => $audio_base . 'a-lamp-unto-my-feet.wav', 'size' => file_exists( $audio_two ) ? filesize( $audio_two ) : 0, 'duration' => '00:17',
		),
		array(
			'key' => 'sermon_fellowship', 'title' => 'Fellowship at the Table', 'featured' => 'sermon_fellowship', 'date' => '-70 days',
			'excerpt' => 'Biblical fellowship grows as believers receive truth, share life, pray, and care for one another.',
			'content' => '<p>Acts describes a church devoted to doctrine, fellowship, breaking of bread, and prayer.</p><p>Christian community is more than friendly conversation; it is a shared life centered on Christ and shaped by His Word.</p>',
			'series' => 'Life Together', 'topics' => array( 'Fellowship', 'Church' ), 'book' => 'Acts', 'speaker' => '@record:speaker_lead', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'ACT', 'Acts', 2, 42, 42, 'And they continued stedfastly in the apostles’ doctrine and fellowship, and in breaking of bread, and in prayers.' ),
			'transcript' => 'The fellowship of the early church was anchored in apostolic truth and expressed through shared meals, prayer, generosity, and worship. The same pattern gives local churches a durable center today.',
		),
		array(
			'key' => 'sermon_guest_paul', 'title' => 'Guest Resource: Shocking Youth Message (2002)', 'featured' => 'sermon_guest_paul', 'date' => '2002-01-01',
			'excerpt' => 'An externally hosted guest message by Paul Washer calling hearers to examine the reality of their profession of faith.',
			'content' => '<p><strong>Guest resource:</strong> This externally hosted message is included to demonstrate YouTube support in DIY Sermons. It was not produced by Sanctuary Baptist Church.</p>',
			'series' => 'Guest Resources', 'topics' => array( 'Repentance', 'Faith' ), 'book' => 'Matthew', 'speaker' => '@record:speaker_paul_washer', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'MAT', 'Matthew', 7, 21, 23, 'Not every one that saith unto me, Lord, Lord, shall enter into the kingdom of heaven... And then will I profess unto them, I never knew you: depart from me, ye that work iniquity.' ),
			'video' => 'https://www.youtube.com/watch?v=uuabITeO4l8',
		),
		array(
			'key' => 'sermon_guest_billy', 'title' => 'Guest Resource: The Cross', 'featured' => 'sermon_guest_billy', 'date' => '2013-11-07',
			'excerpt' => 'Billy Graham’s externally hosted gospel presentation centered on the meaning of the cross of Jesus Christ.',
			'content' => '<p><strong>Guest resource:</strong> This Billy Graham Evangelistic Association video is included to demonstrate YouTube support in DIY Sermons. It was not produced by Sanctuary Baptist Church.</p>',
			'series' => 'Guest Resources', 'topics' => array( 'Gospel', 'Cross' ), 'book' => '1 Corinthians', 'speaker' => '@record:speaker_billy_graham', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( '1CO', '1 Corinthians', 1, 18, 18, 'For the preaching of the cross is to them that perish foolishness; but unto us which are saved it is the power of God.' ),
			'video' => 'https://www.youtube.com/watch?v=bba2Dqaw6SI',
		),
		array(
			'key' => 'sermon_guest_voddie', 'title' => 'Guest Resource: Gospel Encouragement', 'featured' => 'sermon_guest_voddie', 'date' => '2023-11-02',
			'excerpt' => 'Voddie Baucham opens Romans by showing how gospel-shaped believers encourage one another through shared faith.',
			'content' => '<p><strong>Guest resource:</strong> This externally hosted message from Grace Family Baptist Church is included to demonstrate YouTube support in DIY Sermons. It was not produced by Sanctuary Baptist Church.</p>',
			'series' => 'Guest Resources', 'topics' => array( 'Gospel', 'Encouragement' ), 'book' => 'Romans', 'speaker' => '@record:speaker_voddie_baucham', 'campus' => '@record:campus_main',
			'scripture' => sanctuary_kjv_passage( 'ROM', 'Romans', 1, 8, 13, 'First, I thank my God through Jesus Christ for you all, that your faith is spoken of throughout the whole world... That is, that I may be comforted together with you by the mutual faith both of you and me.' ),
			'video' => 'https://www.youtube.com/watch?v=PsCIXaxn4-s',
		),
	);

	foreach ( $sermons as $sermon ) {
		$meta = array(
			'_diy_sermon_date'            => 10 === strlen( $sermon['date'] ) && preg_match( '/^\d{4}-/', $sermon['date'] ) ? $sermon['date'] : '@date:' . $sermon['date'],
			'_diy_sermon_primary_speaker' => $sermon['speaker'],
			'_diy_sermon_speakers'        => array( $sermon['speaker'] ),
			'_diy_sermon_campuses'        => array( $sermon['campus'] ),
			'_diy_sermon_podcasts'        => array( '@record:podcast' ),
			'_diy_sermon_scriptures'      => array( $sermon['scripture'] ),
			'_diy_sermon_transcript'      => isset( $sermon['transcript'] ) ? $sermon['transcript'] : '',
		);
		if ( ! empty( $sermon['audio'] ) ) {
			$meta['_diy_sermon_audio_url'] = $sermon['audio'];
			$meta['_diy_sermon_file_size'] = $sermon['size'];
			$meta['_diy_sermon_duration']  = $sermon['duration'];
		}
		if ( ! empty( $sermon['video'] ) ) {
			$meta['_diy_sermon_video_url'] = $sermon['video'];
		}
		$records[] = array(
			'key' => $sermon['key'], 'post_type' => 'diy_sermon', 'title' => $sermon['title'],
			'content' => $sermon['content'], 'excerpt' => $sermon['excerpt'], 'featured' => $sermon['featured'],
			'terms' => array( 'diy_series' => array( $sermon['series'] ), 'diy_topic' => $sermon['topics'], 'diy_book' => array( $sermon['book'] ) ),
			'meta' => $meta,
		);
	}

	$events = array(
		array( 'key' => 'event_youth', 'title' => 'Student Retreat Weekend', 'featured' => 'event_youth', 'category' => 'Students', 'tags' => array( 'Retreat', 'Youth' ), 'date' => '+6 weeks', 'end' => '+6 weeks +2 days', 'start' => '17:30:00', 'finish' => '11:30:00', 'campuses' => array( '@record:campus_north' ), 'venue' => 'Foothills Bible Camp', 'excerpt' => 'A gospel-centered weekend for middle and high school students.', 'content' => '<p>Students will study Scripture, worship, build friendships, and enjoy outdoor activities with trained adult leaders. Registration and a signed permission form are required.</p>' ),
		array( 'key' => 'event_women', 'title' => 'Women in the Word', 'featured' => 'event_women', 'category' => 'Discipleship', 'tags' => array( 'Women', 'Bible Study' ), 'date' => 'next Tuesday', 'start' => '10:00:00', 'finish' => '11:30:00', 'recurrence' => 'weekly', 'campuses' => array( '@record:campus_main' ), 'venue' => 'Fellowship Classroom', 'excerpt' => 'A weekly KJV Bible study and prayer gathering for women.', 'content' => '<p>Bring your Bible and join women of every age for careful study, honest conversation, and prayer. Childcare is available by advance reservation.</p>' ),
		array( 'key' => 'event_men', 'title' => 'Men’s Prayer Breakfast', 'featured' => 'event_men', 'category' => 'Fellowship', 'tags' => array( 'Men', 'Prayer' ), 'date' => 'second Saturday of next month', 'start' => '08:00:00', 'finish' => '09:30:00', 'recurrence' => 'monthly', 'campuses' => array( '@record:campus_north' ), 'venue' => 'North Campus Hall', 'excerpt' => 'Breakfast, Scripture, and focused prayer for men and young men.', 'content' => '<p>Share a simple breakfast, hear a brief testimony, and pray for families, church leaders, missionaries, and our community.</p>' ),
		array( 'key' => 'event_vbs', 'title' => 'Vacation Bible School', 'featured' => 'event_vbs', 'category' => 'Children', 'tags' => array( 'Children', 'Family' ), 'date' => '+2 months', 'end' => '+2 months +4 days', 'start' => '09:00:00', 'finish' => '12:00:00', 'all' => true, 'venue' => 'Children’s Ministry Center', 'excerpt' => 'Five mornings of Bible truth, music, crafts, games, and friendship.', 'content' => '<p>Children will discover God’s faithfulness through age-appropriate KJV Bible lessons, music, crafts, recreation, and missions moments. Online registration is required.</p>' ),
		array( 'key' => 'event_missions', 'title' => 'Missions Celebration Banquet', 'featured' => 'event_missions', 'category' => 'Missions', 'tags' => array( 'Missions', 'All Church' ), 'date' => '+9 weeks', 'start' => '18:00:00', 'finish' => '20:00:00', 'all' => true, 'venue' => 'Main Campus Fellowship Hall', 'excerpt' => 'Celebrate gospel partnerships and hear reports from the field.', 'content' => '<p>Enjoy dinner, missionary updates, focused prayer, and practical opportunities to support local and global gospel work. The event is free; reservations help us prepare.</p>' ),
	);

	foreach ( $events as $event ) {
		$end = isset( $event['end'] ) ? $event['end'] : $event['date'];
		$meta = array(
			'_diy_event_start_date' => '@date:' . $event['date'], '_diy_event_end_date' => '@date:' . $end,
			'_diy_event_start_time' => $event['start'], '_diy_event_end_time' => $event['finish'], '_diy_event_timezone' => 'America/New_York',
			'_diy_event_recurrence' => isset( $event['recurrence'] ) ? $event['recurrence'] : 'none', '_diy_event_recurrence_every' => 1,
			'_diy_event_venue' => $event['venue'], '_diy_event_cost' => 'Free', '_diy_event_featured' => true,
		);
		if ( ! empty( $event['all'] ) ) {
			$meta['_diy_event_all_campuses'] = true;
		} else {
			$meta['_diy_event_campuses'] = $event['campuses'];
		}
		$records[] = array(
			'key' => $event['key'], 'post_type' => 'diy_event', 'title' => $event['title'], 'content' => $event['content'],
			'excerpt' => $event['excerpt'], 'featured' => $event['featured'],
			'terms' => array( 'diy_event_category' => array( $event['category'] ), 'diy_event_tag' => $event['tags'] ), 'meta' => $meta,
		);
	}

	$records[] = array(
		'key' => 'portfolio_ministry', 'post_type' => 'diy_portfolio', 'title' => 'Ministry in Motion',
		'content' => '<p>A reusable portfolio showing worship, baptism, service, and discipleship in the life of the church.</p>',
		'excerpt' => 'See how God is at work through the ministries of Sanctuary Baptist Church.', 'featured' => 'portfolio_baptism',
		'terms' => array( 'diy_portfolio_category' => array( 'Church Life' ) ),
		'meta' => array(
			'_diy_portfolio_layout' => 'grid', '_diy_portfolio_columns' => 4, '_diy_portfolio_gap' => 18,
			'_diy_portfolio_items' => array(
				array( 'type' => 'image', 'attachment_id' => 0, 'url' => $portfolio_base . 'portfolio-baptism.webp', 'title' => 'New Life in Christ', 'alt' => 'A believer being baptized during worship' ),
				array( 'type' => 'image', 'attachment_id' => 0, 'url' => $portfolio_base . 'portfolio-choir.webp', 'title' => 'Worship Together', 'alt' => 'A multigenerational church choir singing' ),
				array( 'type' => 'image', 'attachment_id' => 0, 'url' => $portfolio_base . 'portfolio-pantry.webp', 'title' => 'Serving Our Neighbors', 'alt' => 'Church volunteers serving a family at the food pantry' ),
				array( 'type' => 'image', 'attachment_id' => 0, 'url' => $portfolio_base . 'portfolio-family.webp', 'title' => 'Faith at Home', 'alt' => 'Families studying the Bible together' ),
			),
		),
	);

	$news = array(
		array(
			'key' => 'church_news_scripture', 'title' => 'A Summer of Scripture Begins', 'featured' => 'sermon_lamp', 'category' => 'Discipleship',
			'excerpt' => 'A shared reading plan will guide the church through Psalms and the Gospel of John.',
			'content' => '<p>This summer, our church family is reading through selected Psalms and the Gospel of John. Printed reading guides are available in both lobbies, and the same schedule is posted on the Ministries page.</p><p>Families, small groups, and individual readers are encouraged to discuss one truth they learned and one way they can respond in faith. “Thy word is a lamp unto my feet, and a light unto my path.” (Psalm 119:105, KJV)</p>',
		),
		array(
			'key' => 'church_news_baptism', 'title' => 'Celebrating New Life in Christ', 'featured' => 'portfolio_baptism', 'category' => 'Church Life',
			'excerpt' => 'Our church family gathered to hear testimonies and celebrate believers following Christ in baptism.',
			'content' => '<p>Baptism Sunday gave our congregation an opportunity to hear clear testimonies of repentance and faith in Jesus Christ. Each person described the grace of God and the faithful witness of believers who pointed them to Scripture.</p><p>We rejoice with these brothers and sisters and pray that they will continue to grow through worship, fellowship, service, and the Word.</p>',
		),
		array(
			'key' => 'church_news_pantry', 'title' => 'Food Pantry Adds Saturday Hours', 'featured' => 'portfolio_pantry', 'category' => 'Outreach',
			'excerpt' => 'New Saturday hours will help working families receive groceries and prayer closer to home.',
			'content' => '<p>Our community food pantry will now open on selected Saturday mornings in addition to its weekday schedule. Volunteers will prepare grocery boxes, welcome neighbors, and offer prayer when requested.</p><p>Members can help by serving a shift or donating shelf-stable food. Current needs are listed at the Welcome Center and on the Ministries page.</p>',
		),
		array(
			'key' => 'church_news_students', 'title' => 'Students Prepare for Retreat Weekend', 'featured' => 'event_youth', 'category' => 'Students',
			'excerpt' => 'Students and leaders are preparing for a gospel-centered weekend of Bible study, worship, and friendship.',
			'content' => '<p>Middle and high school students will spend a weekend studying Scripture, worshiping together, and building healthy friendships. Adult leaders are completing safety training and preparing small-group discussions.</p><p>Parents can review the schedule, packing list, and permission information on the Events page.</p>',
		),
		array(
			'key' => 'church_news_worship', 'title' => 'Choir Night Centers on the Cross', 'featured' => 'portfolio_choir', 'category' => 'Worship',
			'excerpt' => 'A special evening of congregational song and Scripture will trace the promise and accomplishment of redemption.',
			'content' => '<p>The Sanctuary choir and instrumentalists are preparing an evening of Scripture readings and songs centered on the cross of Christ. The congregation will participate throughout the service rather than simply observe a performance.</p><p>Invite a friend and arrive early. Childcare details and the service time are available on the Events page.</p>',
		),
		array(
			'key' => 'church_news_families', 'title' => 'New Bible Groups Welcome Families', 'featured' => 'portfolio_family', 'category' => 'Families',
			'excerpt' => 'New midweek groups will help families study the Bible, pray, and build lasting friendships.',
			'content' => '<p>Several new Bible groups are forming for young families, adults, and senior adults at both campuses. Each group follows the same commitment to careful Scripture study, honest prayer, and practical care.</p><p>Visit the Ministries page or speak with a Welcome Center volunteer to find a group that fits your schedule.</p>',
		),
		array(
			'key' => 'church_news_missions', 'title' => 'Missions Celebration Shares Field Reports', 'featured' => 'event_missions', 'category' => 'Missions',
			'excerpt' => 'Mission partners will share updates and practical ways the church can pray, give, and go.',
			'content' => '<p>Our annual missions celebration will include field reports, focused prayer, and opportunities to support gospel work locally and abroad. The gathering is designed for the whole church family.</p><p>Reservations help the hospitality team prepare the meal. Details are available on the Events page.</p>',
		),
		array(
			'key' => 'church_news_vbs', 'title' => 'Vacation Bible School Volunteers Gather', 'featured' => 'event_vbs', 'category' => 'Children',
			'excerpt' => 'Teachers and volunteers are preparing a safe, joyful week of Bible truth, music, crafts, and recreation.',
			'content' => '<p>Vacation Bible School volunteers will gather for training, classroom preparation, and prayer before children arrive. Every team member serving with children completes the church safety process.</p><p>Members can still assist with registration, hospitality, crafts, recreation, or classroom support. See the Events page for the volunteer meeting.</p>',
		),
		array(
			'key' => 'church_news_campuses', 'title' => 'Two Campuses, One Gospel Mission', 'featured' => 'event_worship', 'category' => 'Campuses',
			'excerpt' => 'Both campuses share one mission, one ministry philosophy, and one commitment to biblical preaching.',
			'content' => '<p>Sanctuary Baptist Church gathers in two neighborhoods while remaining one church family. Pastors, ministry leaders, and volunteers serve across both locations, and members regularly join together for worship and mission.</p><p>Campus pages include service times, directions, ministry contacts, and upcoming events for each location.</p>',
		),
	);

	foreach ( $news as $article ) {
		$records[] = array(
			'key' => $article['key'], 'post_type' => 'diy_news', 'title' => $article['title'], 'content' => $article['content'],
			'excerpt' => $article['excerpt'], 'featured' => $article['featured'],
			'terms' => array( 'diy_news_category' => array( $article['category'] ) ),
		);
	}

	$records[] = array(
		'key' => 'privacy', 'post_type' => 'page', 'title' => 'Privacy Policy',
		'content' => '<h2>About this demonstration</h2><p>This sample policy is included to demonstrate a complete church website footer. Replace it with a policy reviewed for your church, location, forms, analytics, donation provider, and other services.</p><h2>Information visitors provide</h2><p>A church may receive information submitted through contact, prayer, registration, giving, or account forms. Access should be limited to authorized staff and volunteers who need it for the stated ministry purpose.</p><h2>Prayer requests</h2><p>Prayer requests may contain sensitive information. The church should explain who receives them, how long they are retained, and how a visitor can request correction or deletion.</p><h2>Questions</h2><p>Publish a current church office email address and mailing address here for privacy questions.</p>',
		'excerpt' => 'Sample privacy information for the Sanctuary demonstration site.',
	);
	$records[] = array(
		'key' => 'terms', 'post_type' => 'page', 'title' => 'Terms and Conditions',
		'content' => '<h2>Demonstration content</h2><p>This site is a fictional church demonstration. Names, addresses, schedules, and ministry details are examples and must be replaced before using the theme for a live church.</p><h2>External resources</h2><p>Guest sermon videos remain hosted by their publishers. Availability, advertising, and playback are controlled by the external platform.</p><h2>Pastoral and emergency needs</h2><p>Website forms are not emergency services and should not be used when immediate help is required. Publish clear local emergency and pastoral-care instructions for your congregation.</p><h2>Use of content</h2><p>Before publishing real photographs, recordings, testimonies, or personal information, obtain the permissions required by your church policies and applicable law.</p>',
		'excerpt' => 'Sample terms for the Sanctuary demonstration site.',
	);

	return $records;
}

/** Add richer assets and records to the parent theme's normal demo manifest. */
function sanctuary_extend_demo_manifest( $demo ) {
	$demo['assets'] = array_merge( isset( $demo['assets'] ) ? $demo['assets'] : array(), sanctuary_demo_assets() );
	$demo['records'] = isset( $demo['records'] ) ? $demo['records'] : array();

	$featured = array(
		'speaker_lead' => 'pastor_jonathan', 'speaker_associate' => 'pastor_michael',
		'sermon_love' => 'sermon_love', 'sermon_shepherd' => 'sermon_shepherd', 'sermon_grace' => 'sermon_grace',
		'event_worship' => 'event_worship', 'event_groups' => 'event_groups', 'event_service' => 'event_service', 'event_fellowship' => 'event_fellowship',
	);
	foreach ( $demo['records'] as &$record ) {
		if ( isset( $featured[ $record['key'] ] ) ) {
			$record['featured'] = $featured[ $record['key'] ];
		}
		if ( 'speaker_lead' === $record['key'] ) {
			$record['content'] = '<p>Jonathan loves preaching the whole counsel of God, shepherding families, and helping believers take practical steps of faith.</p>';
			$record['excerpt'] = 'Jonathan serves as lead pastor with a commitment to expository preaching, prayer, and disciple-making.';
		}
		if ( 'speaker_associate' === $record['key'] ) {
			$record['excerpt'] = 'Michael serves the North Campus and helps families and small groups understand and apply Scripture.';
		}
	}
	unset( $record );
	$demo['records'] = array_merge( $demo['records'], sanctuary_demo_records() );

	foreach ( $demo['pages'] as &$page ) {
		if ( 'events' === $page['key'] ) {
			$page['content'] = '<!-- wp:heading --><h2>Gather, grow, and serve</h2><!-- /wp:heading --><p>Choose a view, search by keyword, or narrow the calendar by category, campus, or tag.</p><!-- wp:shortcode -->[diy_events_browser]<!-- /wp:shortcode -->';
		}
		if ( 'news' === $page['key'] ) {
			$page['content'] = '<!-- wp:paragraph {"className":"sanctuary-news-intro"} --><p class="sanctuary-news-intro">Stories of worship, discipleship, fellowship, missions, and service from across our church family.</p><!-- /wp:paragraph --><!-- wp:shortcode -->[diy_news_center count="9"]<!-- /wp:shortcode -->';
		}
		if ( 'contact' === $page['key'] ) {
			$page['content'] = sanctuary_contact_page_content();
		}
		if ( 'prayer' === $page['key'] ) {
			$page['content'] = sanctuary_prayer_page_content();
		}
		if ( 'about' === $page['key'] ) {
			$page['content'] = sanctuary_about_page_content();
		}
	}
	unset( $page );
	$demo['menus']['footer_legal'] = array(
		'name'  => 'Legal Menu',
		'items' => array( 'privacy', 'terms', 'contact' ),
	);
	return $demo;
}

/** About-page copy with the reusable active-staff speaker directory. */
function sanctuary_about_page_content() {
	$content  = '<!-- wp:heading --><h2>Our mission</h2><!-- /wp:heading -->';
	$content .= '<p>We glorify God through Christ-centered worship, expository preaching, earnest prayer, and loving service to our neighbors.</p>';
	$content .= '<!-- wp:heading --><h2>Our story</h2><!-- /wp:heading -->';
	$content .= '<p>What began as a small gathering of believers has grown into one church serving several neighborhoods. Through every season, God’s Word, prayer, fellowship, and the good news of Jesus Christ have remained at the center.</p>';
	$content .= '<!-- wp:heading {"anchor":"leadership"} --><h2 id="leadership">Leadership</h2><!-- /wp:heading -->';
	$content .= '<p>Our pastors and ministry leaders seek to equip every believer for faithful Christian living and service.</p>';
	$content .= '<!-- wp:shortcode -->[diy_speakers group="staff" status="active" columns="3" count="6" show_role="yes" show_excerpt="yes" show_button="yes" button_label="Read More"]<!-- /wp:shortcode -->';
	return $content;
}

/** Contact-page copy, with a form shortcode added after Contact Form 7 is available. */
function sanctuary_contact_page_content( $shortcode = '' ) {
	$content  = '<!-- wp:heading --><h2>We would love to hear from you</h2><!-- /wp:heading -->';
	$content .= '<p>Use this form for general questions, ministry information, or help planning a visit. For urgent pastoral care, please call the church office.</p>';
	$content .= '<div class="sanctuary-contact-details"><p><strong>Main office</strong><br>1234 Grace Avenue<br>Greenville, SC 29601</p><p><strong>Office hours</strong><br>Monday–Thursday<br>9:00 AM–4:00 PM</p><p><strong>Contact</strong><br>(555) 010-2000<br>hello@example.org</p></div>';
	$content .= $shortcode ? '<!-- wp:shortcode -->' . $shortcode . '<!-- /wp:shortcode -->' : '<p class="sanctuary-form-note"><em>Activate Contact Form 7 to add the ready-made Sanctuary Contact form automatically.</em></p>';
	return $content;
}

/** Prayer-page copy, with a form shortcode added after Contact Form 7 is available. */
function sanctuary_prayer_page_content( $shortcode = '' ) {
	$content  = '<!-- wp:heading --><h2>How may we pray for you?</h2><!-- /wp:heading -->';
	$content .= '<p>Our pastoral team and prayer volunteers consider it a privilege to pray with you. Choose the confidentiality option that best fits your request. For urgent or emergency needs, contact appropriate local services directly.</p>';
	$content .= '<blockquote><p>“Casting all your care upon him; for he careth for you.”</p><cite>1 Peter 5:7, KJV</cite></blockquote>';
	$content .= $shortcode ? '<!-- wp:shortcode -->' . $shortcode . '<!-- /wp:shortcode -->' : '<p class="sanctuary-form-note"><em>Activate Contact Form 7 to add the ready-made Prayer Request form automatically.</em></p>';
	return $content;
}

/** Find an existing demo object by its stable key. */
function sanctuary_demo_object_id( $key, $post_type = 'any' ) {
	$ids = get_posts(
		array(
			'post_type' => $post_type, 'post_status' => 'any', 'posts_per_page' => 1, 'fields' => 'ids',
			'meta_query' => array(
				array( 'key' => '_diy_church_demo_theme', 'value' => get_stylesheet() ),
				array( 'key' => '_diy_church_demo_key', 'value' => sanitize_key( $key ) ),
			),
		)
	);
	return $ids ? absint( $ids[0] ) : 0;
}

/** Keep the fictional pastoral team in a deliberate leadership order. */
function sanctuary_order_demo_leadership() {
	$positions = array( 'speaker_lead' => 0, 'speaker_associate' => 10, 'speaker_discipleship' => 20 );
	foreach ( $positions as $key => $position ) {
		$post_id = sanctuary_demo_object_id( $key, 'diy_speaker' );
		if ( $post_id ) {
			wp_update_post( array( 'ID' => $post_id, 'menu_order' => absint( $position ) ) );
		}
	}
}

/** Create the four useful demo widget areas without overwriting later user choices. */
function sanctuary_provision_footer_widgets() {
	if ( get_option( 'sanctuary_demo_footer_widgets' ) ) {
		return;
	}

	$about_url      = esc_url( home_url( '/about/' ) );
	$new_here_url   = esc_url( home_url( '/new-here/' ) );
	$sermons_url    = esc_url( home_url( '/sermons/' ) );
	$events_url     = esc_url( home_url( '/events/' ) );
	$ministries_url = esc_url( home_url( '/ministries/' ) );
	$give_url       = esc_url( home_url( '/give/' ) );
	$prayer_url     = esc_url( home_url( '/prayer/' ) );
	$widgets = array(
		array(
			'title'   => 'Sanctuary Baptist Church',
			'content' => '<p>A Christ-centered church committed to biblical worship, faithful discipleship, earnest prayer, and loving service.</p><p><a href="' . $about_url . '">Meet our church</a></p>',
		),
		array(
			'title'   => 'This Weekend',
			'content' => '<p><strong>Main Campus</strong><br>Sunday School 9:00 AM<br>Worship 11:00 AM</p><p><strong>North Campus</strong><br>Sunday School 9:00 AM<br>Worship 11:00 AM</p>',
		),
		array(
			'title'   => 'Explore',
			'content' => '<ul><li><a href="' . $new_here_url . '">Plan Your Visit</a></li><li><a href="' . $sermons_url . '">Sermons</a></li><li><a href="' . $events_url . '">Events</a></li><li><a href="' . $ministries_url . '">Ministries</a></li><li><a href="' . $give_url . '">Give</a></li></ul>',
		),
		array(
			'title'   => 'Contact',
			'content' => '<p>1234 Grace Avenue<br>Greenville, SC 29601</p><p><a href="tel:+15550102000">(555) 010-2000</a><br><a href="mailto:hello@example.org">hello@example.org</a></p><p><a href="' . $prayer_url . '">Share a prayer request</a></p>',
		),
	);

	$settings = get_option( 'widget_custom_html', array() );
	if ( ! is_array( $settings ) ) {
		$settings = array();
	}
	$numeric = array_filter( array_map( 'absint', array_keys( $settings ) ) );
	$next    = $numeric ? max( $numeric ) + 1 : 2;
	$created = array();
	$areas   = wp_get_sidebars_widgets();

	foreach ( $widgets as $index => $widget ) {
		$instance = $next++;
		$settings[ $instance ] = array(
			'title'   => $widget['title'],
			'content' => $widget['content'] . '<!-- sanctuary-demo-footer-' . ( $index + 1 ) . ' -->',
		);
		$widget_id = 'custom_html-' . $instance;
		$sidebar   = 'footer-' . ( $index + 1 );
		$areas[ $sidebar ]   = isset( $areas[ $sidebar ] ) && is_array( $areas[ $sidebar ] ) ? $areas[ $sidebar ] : array();
		$areas[ $sidebar ][] = $widget_id;
		$created[] = $widget_id;
	}

	$settings['_multiwidget'] = 1;
	update_option( 'widget_custom_html', $settings );
	wp_set_sidebars_widgets( $areas );
	update_option( 'sanctuary_demo_footer_widgets', $created, false );
}

/** Upgrade old demo widget links for WordPress multisite subdirectory installs. */
function sanctuary_upgrade_footer_widget_links() {
	if ( '1.4.0' === get_option( 'sanctuary_demo_footer_links_version' ) ) {
		return;
	}
	$widget_ids = (array) get_option( 'sanctuary_demo_footer_widgets', array() );
	$settings   = get_option( 'widget_custom_html', array() );
	$changed    = false;
	$paths      = array( 'about', 'new-here', 'sermons', 'events', 'ministries', 'give', 'prayer' );
	foreach ( $widget_ids as $widget_id ) {
		$instance = absint( str_replace( 'custom_html-', '', $widget_id ) );
		if ( ! $instance || empty( $settings[ $instance ]['content'] ) ) {
			continue;
		}
		foreach ( $paths as $path ) {
			$settings[ $instance ]['content'] = str_replace(
				'href="/' . $path . '/"',
				'href="' . esc_url( home_url( '/' . $path . '/' ) ) . '"',
				$settings[ $instance ]['content']
			);
		}
		$changed = true;
	}
	if ( $changed ) {
		update_option( 'widget_custom_html', $settings );
	}
	update_option( 'sanctuary_demo_footer_links_version', '1.4.0', false );
}

/** Apply new footer controls to demos imported before the parent footer builder existed. */
function sanctuary_provision_footer_theme_mods() {
	if ( get_option( 'sanctuary_demo_footer_mods_version' ) === '1.4.0' ) {
		return;
	}
	$mods = array(
		'footer_upper_enable' => true, 'footer_widget_columns' => 4,
		'footer_column_1_width' => 2, 'footer_column_2_width' => 1, 'footer_column_3_width' => 1, 'footer_column_4_width' => 1,
		'footer_lower_columns' => '3', 'footer_lower_center' => 'Worship · Grow · Serve',
	);
	foreach ( $mods as $key => $value ) {
		set_theme_mod( $key, $value );
	}
	update_option( 'sanctuary_demo_footer_mods_version', '1.4.0', false );
}

/** Assign a legal menu on upgraded demos that predate the footer builder. */
function sanctuary_provision_legal_menu() {
	$locations = get_theme_mod( 'nav_menu_locations', array() );
	if ( ! empty( $locations['footer_legal'] ) ) {
		return;
	}

	$menu = wp_get_nav_menu_object( 'Sanctuary Legal Menu' );
	$menu_id = $menu ? absint( $menu->term_id ) : wp_create_nav_menu( 'Sanctuary Legal Menu' );
	if ( is_wp_error( $menu_id ) || ! $menu_id ) {
		return;
	}

	if ( ! $menu ) {
		foreach ( array( 'privacy', 'terms', 'contact' ) as $key ) {
			$post_id = sanctuary_demo_object_id( $key, 'page' );
			if ( $post_id ) {
				wp_update_nav_menu_item( $menu_id, 0, array(
					'menu-item-object-id' => $post_id,
					'menu-item-object'    => 'page',
					'menu-item-type'      => 'post_type',
					'menu-item-status'    => 'publish',
				) );
			}
		}
	}

	$locations['footer_legal'] = $menu_id;
	set_theme_mod( 'nav_menu_locations', $locations );

	$record = get_option( 'diy_church_child_demo_' . get_stylesheet(), array() );
	$record['menus'] = isset( $record['menus'] ) && is_array( $record['menus'] ) ? $record['menus'] : array();
	$record['menus'][] = $menu_id;
	$record['menus'] = array_values( array_unique( array_map( 'absint', $record['menus'] ) ) );
	update_option( 'diy_church_child_demo_' . get_stylesheet(), $record, false );
}

/** Create one Contact Form 7 form through its public object API. */
function sanctuary_create_contact_form( $key, $title, $form_markup, $subject, $mail_body ) {
	$existing = get_posts( array(
		'post_type'      => 'wpcf7_contact_form',
		'post_status'    => 'any',
		'posts_per_page' => 1,
		'fields'         => 'ids',
		'meta_key'       => '_sanctuary_demo_form_key',
		'meta_value'     => sanitize_key( $key ),
	) );
	if ( $existing ) {
		return WPCF7_ContactForm::get_instance( absint( $existing[0] ) );
	}

	$form = WPCF7_ContactForm::get_template( array( 'title' => $title ) );
	if ( ! $form ) {
		return false;
	}
	$properties = $form->get_properties();
	$properties['form'] = $form_markup;
	$mail = isset( $properties['mail'] ) && is_array( $properties['mail'] ) ? $properties['mail'] : array();
	$mail['subject']            = $subject;
	$mail['sender']             = '[_site_title] <wordpress@[_site_domain]>';
	$mail['recipient']          = sanitize_email( get_option( 'admin_email' ) );
	$mail['body']               = $mail_body;
	$mail['additional_headers'] = 'Reply-To: [your-email]';
	$mail['attachments']        = '';
	$mail['use_html']           = false;
	$mail['exclude_blank']      = true;
	$properties['mail'] = $mail;
	$form->set_properties( $properties );
	$post_id = $form->save();
	if ( ! $post_id ) {
		return false;
	}
	update_post_meta( $post_id, '_sanctuary_demo_form_key', sanitize_key( $key ) );
	return WPCF7_ContactForm::get_instance( $post_id );
}

/** Build the Contact and Prayer Request forms and place them on their demo pages. */
function sanctuary_provision_contact_forms() {
	if ( get_option( 'sanctuary_demo_contact_forms_provisioned' ) || ! class_exists( 'WPCF7_ContactForm' ) ) {
		return;
	}

	$contact_markup = '<div class="sanctuary-form-grid"><p><label>Your name *[text* your-name autocomplete:name]</label></p><p><label>Email address *[email* your-email autocomplete:email]</label></p><p><label>Phone number[tel your-phone autocomplete:tel]</label></p><p><label>Subject *[text* your-subject]</label></p></div><p><label>How can we help? *[textarea* your-message]</label></p><p>[acceptance privacy-consent] I understand that this information will be sent to church staff for a response. [/acceptance]</p><p>[submit "Send message"]</p>';
	$prayer_markup  = '<div class="sanctuary-form-grid"><p><label>Your name *[text* your-name autocomplete:name]</label></p><p><label>Email address *[email* your-email autocomplete:email]</label></p><p><label>Campus[select your-campus "Main Campus" "North Campus" "I am not sure"]</label></p><p><label>Confidentiality[select confidentiality "Pastoral team only" "Prayer team" "May be shared without my name"]</label></p></div><p><label>Prayer request *[textarea* prayer-request]</label></p><p><label>[checkbox follow-up use_label_element "I would like a pastor or ministry leader to contact me."]</label></p><p>[acceptance privacy-consent] I understand that this request will be handled according to the confidentiality option selected above. [/acceptance]</p><p>[submit "Share prayer request"]</p>';

	$contact = sanctuary_create_contact_form(
		'contact',
		'Sanctuary Contact',
		$contact_markup,
		'[_site_title] contact: [your-subject]',
		"Name: [your-name]\nEmail: [your-email]\nPhone: [your-phone]\nSubject: [your-subject]\n\nMessage:\n[your-message]\n\nSubmitted from [_url]"
	);
	$prayer = sanctuary_create_contact_form(
		'prayer',
		'Sanctuary Prayer Request',
		$prayer_markup,
		'[_site_title] prayer request from [your-name]',
		"Name: [your-name]\nEmail: [your-email]\nCampus: [your-campus]\nConfidentiality: [confidentiality]\nFollow-up: [follow-up]\n\nPrayer request:\n[prayer-request]\n\nSubmitted from [_url]"
	);

	if ( $contact ) {
		$page_id = sanctuary_demo_object_id( 'contact', 'page' );
		if ( $page_id ) {
			wp_update_post( array( 'ID' => $page_id, 'post_content' => sanctuary_contact_page_content( $contact->shortcode() ) ) );
		}
	}
	if ( $prayer ) {
		$page_id = sanctuary_demo_object_id( 'prayer', 'page' );
		if ( $page_id ) {
			wp_update_post( array( 'ID' => $page_id, 'post_content' => sanctuary_prayer_page_content( $prayer->shortcode() ) ) );
		}
	}

	if ( $contact && $prayer ) {
		update_option(
			'sanctuary_demo_contact_forms_provisioned',
			array( 'contact' => absint( $contact->id() ), 'prayer' => absint( $prayer->id() ) ),
			false
		);
	}
}

/** Provision optional demo integrations after import and after later plugin activation. */
function sanctuary_provision_demo_extras() {
	if ( ! is_admin() || ! current_user_can( 'manage_options' ) || 'demo' !== get_option( 'diy_church_child_setup_complete_' . get_stylesheet() ) ) {
		return;
	}
	update_option( 'page_for_posts', 0 );
	sanctuary_provision_footer_widgets();
	sanctuary_upgrade_footer_widget_links();
	sanctuary_provision_footer_theme_mods();
	sanctuary_provision_legal_menu();
	sanctuary_provision_contact_forms();
}
add_action( 'admin_init', 'sanctuary_provision_demo_extras', 80 );

/** Import one expanded asset once, including recovery after an interrupted request. */
function sanctuary_upgrade_asset( $key, $asset ) {
	$existing = get_posts(
		array(
			'post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => 1, 'fields' => 'ids',
			'meta_key' => '_sanctuary_demo_asset_key', 'meta_value' => sanitize_key( $key ),
		)
	);
	if ( $existing ) {
		return absint( $existing[0] );
	}
	$id = function_exists( 'diy_church_child_import_asset' ) ? diy_church_child_import_asset( $asset['file'], $asset['title'] ) : 0;
	if ( $id ) {
		update_post_meta( $id, '_sanctuary_demo_asset_key', sanitize_key( $key ) );
	}
	return $id;
}

/** Safely add the richer content to sites that imported Sanctuary 1.2 demo data. */
function sanctuary_upgrade_existing_demo() {
	if ( ! is_admin() || ! current_user_can( 'manage_options' ) || 'demo' !== get_option( 'diy_church_child_setup_complete_' . get_stylesheet() ) ) {
		return;
	}
	if ( version_compare( (string) get_option( 'sanctuary_demo_content_version', '0' ), '1.4.1', '>=' ) ) {
		return;
	}
	if ( ! function_exists( 'diy_church_child_resolve_value' ) || ! function_exists( 'diy_church_get_child_theme_profile' ) ) {
		return;
	}

	$profile = diy_church_get_child_theme_profile();
	$demo    = isset( $profile['demo'] ) ? $profile['demo'] : array();
	$assets  = array();
	$record  = get_option( 'diy_church_child_demo_' . get_stylesheet(), array( 'posts' => array(), 'attachments' => array(), 'menus' => array() ) );
	foreach ( sanctuary_demo_assets() as $key => $asset ) {
		$assets[ $key ] = sanctuary_upgrade_asset( $key, $asset );
		if ( $assets[ $key ] ) {
			$record['attachments'][] = $assets[ $key ];
		}
	}

	$ids = array();
	foreach ( array_merge( isset( $demo['pages'] ) ? $demo['pages'] : array(), isset( $demo['records'] ) ? $demo['records'] : array() ) as $item ) {
		$id = sanctuary_demo_object_id( $item['key'], isset( $item['post_type'] ) ? $item['post_type'] : 'page' );
		if ( $id ) {
			$ids[ $item['key'] ] = $id;
		}
	}

	$extra = sanctuary_demo_records();
	foreach ( $extra as $item ) {
		$key = sanitize_key( $item['key'] );
		if ( ! empty( $ids[ $key ] ) || ! post_type_exists( $item['post_type'] ) ) {
			continue;
		}
		$post_id = wp_insert_post(
			array(
				'post_type' => sanitize_key( $item['post_type'] ), 'post_status' => 'publish',
				'post_title' => sanitize_text_field( $item['title'] ), 'post_name' => sanitize_title( $item['title'] ),
				'post_content' => isset( $item['content'] ) ? wp_kses_post( $item['content'] ) : '',
				'post_excerpt' => isset( $item['excerpt'] ) ? sanitize_textarea_field( $item['excerpt'] ) : '',
			), true
		);
		if ( is_wp_error( $post_id ) ) {
			continue;
		}
		$ids[ $key ] = $post_id;
		$record['posts'][] = $post_id;
		update_post_meta( $post_id, '_diy_church_demo_theme', get_stylesheet() );
		update_post_meta( $post_id, '_diy_church_demo_key', $key );
	}

	foreach ( $extra as $item ) {
		$key = sanitize_key( $item['key'] );
		if ( empty( $ids[ $key ] ) ) {
			continue;
		}
		$post_id = $ids[ $key ];
		foreach ( isset( $item['meta'] ) ? $item['meta'] : array() as $meta_key => $value ) {
			update_post_meta( $post_id, sanitize_key( $meta_key ), diy_church_child_resolve_value( $value, $ids, $assets ) );
		}
		if ( ! empty( $item['featured'] ) && ! empty( $assets[ $item['featured'] ] ) ) {
			set_post_thumbnail( $post_id, $assets[ $item['featured'] ] );
		}
		foreach ( isset( $item['terms'] ) ? $item['terms'] : array() as $taxonomy => $terms ) {
			if ( taxonomy_exists( $taxonomy ) ) {
				wp_set_object_terms( $post_id, array_map( 'sanitize_text_field', (array) $terms ), sanitize_key( $taxonomy ) );
			}
		}
		if ( 'diy_event' === get_post_type( $post_id ) && class_exists( 'DIY_Church_Events_Meta' ) ) {
			$event_meta = new DIY_Church_Events_Meta();
			update_post_meta( $post_id, '_diy_event_next_start', $event_meta->calculate_next_start( $post_id ) );
		}
	}

	$featured = array(
		'speaker_lead' => 'pastor_jonathan', 'speaker_associate' => 'pastor_michael', 'speaker_discipleship' => 'pastor_caleb',
		'sermon_love' => 'sermon_love', 'sermon_shepherd' => 'sermon_shepherd', 'sermon_grace' => 'sermon_grace',
		'event_worship' => 'event_worship', 'event_groups' => 'event_groups', 'event_service' => 'event_service', 'event_fellowship' => 'event_fellowship',
	);
	foreach ( $featured as $object_key => $asset_key ) {
		$id = isset( $ids[ $object_key ] ) ? $ids[ $object_key ] : sanctuary_demo_object_id( $object_key );
		if ( $id && ! empty( $assets[ $asset_key ] ) ) {
			set_post_thumbnail( $id, $assets[ $asset_key ] );
		}
	}
	$leadership_profiles = array(
		'speaker_lead' => array( 'content' => '<p>Jonathan loves preaching the whole counsel of God, shepherding families, and helping believers take practical steps of faith.</p>', 'excerpt' => 'Jonathan serves as lead pastor with a commitment to expository preaching, prayer, and disciple-making.' ),
		'speaker_associate' => array( 'excerpt' => 'Michael serves the North Campus and helps families and small groups understand and apply Scripture.' ),
	);
	foreach ( $leadership_profiles as $profile_key => $profile_data ) {
		$profile_id = isset( $ids[ $profile_key ] ) ? absint( $ids[ $profile_key ] ) : sanctuary_demo_object_id( $profile_key, 'diy_speaker' );
		if ( $profile_id ) {
			$update = array( 'ID' => $profile_id, 'post_excerpt' => $profile_data['excerpt'] );
			if ( isset( $profile_data['content'] ) ) {
				$update['post_content'] = $profile_data['content'];
			}
			wp_update_post( $update );
		}
	}

	$events_page = sanctuary_demo_object_id( 'events', 'page' );
	if ( $events_page ) {
		wp_update_post( array( 'ID' => $events_page, 'post_content' => '<!-- wp:heading --><h2>Gather, grow, and serve</h2><!-- /wp:heading --><p>Choose a view, search by keyword, or narrow the calendar by category, campus, or tag.</p><!-- wp:shortcode -->[diy_events_browser]<!-- /wp:shortcode -->' ) );
	}
	$news_page = sanctuary_demo_object_id( 'news', 'page' );
	if ( $news_page ) {
		wp_update_post( array( 'ID' => $news_page, 'post_content' => '<!-- wp:paragraph {"className":"sanctuary-news-intro"} --><p class="sanctuary-news-intro">Stories of worship, discipleship, fellowship, missions, and service from across our church family.</p><!-- /wp:paragraph --><!-- wp:shortcode -->[diy_news_center count="9"]<!-- /wp:shortcode -->' ) );
	}
	$contact_page = sanctuary_demo_object_id( 'contact', 'page' );
	if ( $contact_page ) {
		wp_update_post( array( 'ID' => $contact_page, 'post_content' => sanctuary_contact_page_content() ) );
	}
	$prayer_page = sanctuary_demo_object_id( 'prayer', 'page' );
	if ( $prayer_page ) {
		wp_update_post( array( 'ID' => $prayer_page, 'post_content' => sanctuary_prayer_page_content() ) );
	}
	$about_page = sanctuary_demo_object_id( 'about', 'page' );
	if ( $about_page ) {
		wp_update_post( array( 'ID' => $about_page, 'post_content' => sanctuary_about_page_content() ) );
	}
	update_option( 'page_for_posts', 0 );

	$record['posts']       = array_values( array_unique( array_map( 'absint', isset( $record['posts'] ) ? $record['posts'] : array() ) ) );
	$record['attachments'] = array_values( array_unique( array_map( 'absint', isset( $record['attachments'] ) ? $record['attachments'] : array() ) ) );
	update_option( 'diy_church_child_demo_' . get_stylesheet(), $record, false );
	update_option( 'sanctuary_demo_content_version', '1.4.1', false );
	sanctuary_order_demo_leadership();
	sanctuary_provision_footer_widgets();
	sanctuary_provision_legal_menu();
	sanctuary_provision_contact_forms();
}
add_action( 'admin_init', 'sanctuary_upgrade_existing_demo', 40 );

/** A fresh 1.4.1 import already contains the richer objects. */
function sanctuary_mark_fresh_demo_version() {
	update_option( 'sanctuary_demo_content_version', '1.4.1', false );
	update_option( 'page_for_posts', 0 );
	sanctuary_order_demo_leadership();
	sanctuary_provision_footer_widgets();
	sanctuary_provision_legal_menu();
	sanctuary_provision_contact_forms();
}
add_action( 'diy_church_child_demo_imported', 'sanctuary_mark_fresh_demo_version', 30 );
