<?php
/** Brentwood 100 importer — creates one `bw_hundred` CPT post per item from
 *  _imp_brentwood_100/items.json (built by migration/build_brentwood_100.py).
 *  Resumable + idempotent: keyed on `_bw_src_element` (Laravel type:content_id);
 *  finished posts carry `_bw_done` and are skipped; partial ones are redone.
 *  Run:  srv-gw wp --project brentwooddev -- eval-file \
 *          /var/www/html/wp-content/_imp_brentwood_100/../../ ... (see note) OR
 *        copy this file into the container path and eval-file it.
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
@set_time_limit( 0 );

$items = json_decode( file_get_contents( WP_CONTENT_DIR . '/_imp_brentwood_100/items.json' ), true );
if ( ! is_array( $items ) ) { echo "ERROR: items.json not found or invalid\n"; return; }

/* ---------- HTML -> Gutenberg blocks (copied from import-blog-full.php) ---------- */
function bw100_inner( $n, $d ) { $h = ''; foreach ( $n->childNodes as $c ) { $h .= $d->saveHTML( $c ); } return trim( $h ); }
function bw100_node_block( $node, $doc ) {
	if ( $node->nodeType === XML_TEXT_NODE ) { $t = trim( $node->textContent ); return $t === '' ? '' : "<!-- wp:paragraph -->\n<p>" . esc_html( $t ) . "</p>\n<!-- /wp:paragraph -->\n\n"; }
	if ( $node->nodeType !== XML_ELEMENT_NODE ) { return ''; }
	$tag = strtolower( $node->nodeName );
	if ( preg_match( '/^h([1-6])$/', $tag, $m ) ) { $lvl = max( 2, (int) $m[1] ); $in = bw100_inner( $node, $doc ); return $in === '' ? '' : "<!-- wp:heading {\"level\":$lvl} -->\n<h$lvl>$in</h$lvl>\n<!-- /wp:heading -->\n\n"; }
	switch ( $tag ) {
		case 'p': $in = bw100_inner( $node, $doc ); return ( $in === '' || $in === '&nbsp;' ) ? '' : "<!-- wp:paragraph -->\n<p>$in</p>\n<!-- /wp:paragraph -->\n\n";
		case 'ul': case 'ol': { $ord = $tag === 'ol'; $items = '';
			foreach ( $node->childNodes as $li ) { if ( $li->nodeType === XML_ELEMENT_NODE && strtolower( $li->nodeName ) === 'li' ) { $items .= "<!-- wp:list-item -->\n<li>" . bw100_inner( $li, $doc ) . "</li>\n<!-- /wp:list-item -->\n"; } }
			if ( $items === '' ) { return ''; } $a = $ord ? ' {"ordered":true}' : ''; $t = $ord ? 'ol' : 'ul';
			return "<!-- wp:list$a -->\n<$t>\n$items</$t>\n<!-- /wp:list -->\n\n"; }
		case 'blockquote': return "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\">" . bw100_inner( $node, $doc ) . "</blockquote>\n<!-- /wp:quote -->\n\n";
		case 'div': { $h = ''; foreach ( $node->childNodes as $c ) { $h .= bw100_node_block( $c, $doc ); } return $h; }
		case 'br': return '';
		case 'img': case 'figure': return "<!-- wp:html -->\n" . $doc->saveHTML( $node ) . "\n<!-- /wp:html -->\n\n";
		default: $o = $doc->saveHTML( $node ); return trim( strip_tags( $o ) ) === '' ? '' : "<!-- wp:paragraph -->\n<p>$o</p>\n<!-- /wp:paragraph -->\n\n";
	}
}
function bw100_dom_to_blocks( $html ) {
	libxml_use_internal_errors( true ); $doc = new DOMDocument();
	$doc->loadHTML( '<?xml encoding="utf-8"?><div id="bwroot">' . $html . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
	libxml_clear_errors(); $xp = new DOMXPath( $doc ); $root = $xp->query( '//*[@id="bwroot"]' )->item( 0 );
	if ( ! $root ) { return ''; } $out = ''; foreach ( iterator_to_array( $root->childNodes ) as $n ) { $out .= bw100_node_block( $n, $doc ); } return $out;
}
function bw100_text_to_blocks( $html ) {
	$html = trim( (string) $html ); if ( $html === '' ) { return ''; }
	if ( preg_match( '/<(p|h[1-6]|ul|ol|blockquote|table|pre|figure)\b/i', $html ) ) { return bw100_dom_to_blocks( $html ); }
	return "<!-- wp:paragraph -->\n<p>$html</p>\n<!-- /wp:paragraph -->\n\n";
}
/* ---------- image sideload (copied from import-blog-full.php) ---------- */
function bw100_side( $im, $pid, $title ) {
	$path = $im['file'] ?? ''; if ( $path === '' || ! file_exists( $path ) ) { return null; }
	$tmp = wp_tempnam( basename( $path ) ); if ( ! copy( $path, $tmp ) ) { @unlink( $tmp ); return null; }
	$att = media_handle_sideload( array( 'name' => basename( $path ), 'tmp_name' => $tmp ), $pid, $title );
	if ( is_wp_error( $att ) ) { @unlink( $tmp ); return null; }
	if ( ! empty( $im['alt'] ) ) { update_post_meta( $att, '_wp_attachment_image_alt', $im['alt'] ); }
	if ( ! empty( $im['caption'] ) ) { wp_update_post( array( 'ID' => $att, 'post_excerpt' => $im['caption'] ) ); }
	return $att;
}

/* ---------- run ---------- */
global $wpdb;
$done = 0; $skip = 0; $imgs = 0;
foreach ( $items as $it ) {
	$key = (string) $it['src_key'];
	$existing = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_bw_src_element' AND meta_value=%s LIMIT 1", $key ) );
	if ( $existing ) {
		if ( get_post_meta( $existing, '_bw_done', true ) ) { $skip++; continue; }
		foreach ( get_attached_media( '', $existing ) as $a ) { wp_delete_post( $a->ID, true ); }
		wp_delete_post( $existing, true );
	}

	$title = trim( (string) $it['title'] );
	if ( $title === '' ) { $title = $it['number'] !== '' ? ( 'Item ' . $it['number'] ) : 'Untitled item'; }
	$content = bw100_text_to_blocks( $it['body'] ?? '' );

	$pid = wp_insert_post( array(
		'post_type'    => 'bw_hundred',
		'post_status'  => $it['status'] === 'draft' ? 'draft' : 'publish',
		'post_title'   => $title,
		'post_name'    => $it['anchor'],
		'post_content' => wp_slash( $content ),
		'menu_order'   => ( $it['number'] !== '' ) ? (int) $it['number'] : 999,
	), true );
	if ( is_wp_error( $pid ) || ! $pid ) { echo "  insert failed: $key\n"; continue; }
	add_post_meta( $pid, '_bw_src_element', $key, true );

	if ( ! empty( $it['cover'] ) ) {
		$a = bw100_side( $it['cover'], $pid, $title );
		if ( $a ) { set_post_thumbnail( $pid, $a ); $imgs++; }
	}
	$gids = array();
	foreach ( ( $it['gallery'] ?? array() ) as $im ) {
		$a = bw100_side( $im, $pid, $title );
		if ( $a ) { $gids[] = $a; $imgs++; }
	}
	if ( $gids ) { update_field( 'field_bwm_hundred_gallery', $gids, $pid ); }

	update_field( 'field_bwm_hundred_type', $it['type'], $pid );
	if ( $it['number'] !== '' ) { update_field( 'field_bwm_hundred_number', (int) $it['number'], $pid ); }
	if ( ! empty( $it['caption'] ) ) { update_field( 'field_bwm_hundred_caption', $it['caption'], $pid ); }
	update_field( 'field_bwm_hundred_span', max( 1, min( 4, (int) ( $it['span'] ?: 1 ) ) ), $pid );
	update_field( 'field_bwm_hundred_vspan', 1, $pid );
	if ( ! empty( $it['needs_video'] ) ) { update_post_meta( $pid, '_bw100_needs_video', 1 ); }

	update_post_meta( $pid, '_bw_done', 1 );
	$done++;
}
echo "DONE brentwood-100 import: imported=$done skipped=$skip images=$imgs total=" . count( $items ) . "\n";
