<?php
/** Recent-blogs importer: hero/body separation + proper Gutenberg blocks +
 *  photo-block TEXT captured as body blocks + photo DESCRIPTIONS as captions. */
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';

$blogs = json_decode( file_get_contents( WP_CONTENT_DIR . '/_imp_blog/blog-recent.json' ), true );

/* ---------- HTML -> Gutenberg blocks ---------- */
function bw_inner( $node, $doc ) { $h=''; foreach ( $node->childNodes as $c ) { $h .= $doc->saveHTML($c); } return trim($h); }
function bw_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]); $inner = bw_inner($node,$doc);
		return $inner==='' ? '' : "<!-- wp:heading {\"level\":$lvl} -->\n<h$lvl>$inner</h$lvl>\n<!-- /wp:heading -->\n\n";
	}
	switch ( $tag ) {
		case 'p': { $inner = bw_inner($node,$doc);
			return ($inner==='' || $inner==='&nbsp;') ? '' : "<!-- wp:paragraph -->\n<p>$inner</p>\n<!-- /wp:paragraph -->\n\n"; }
		case 'ul': case 'ol': { $ordered=$tag==='ol'; $items='';
			foreach ( $node->childNodes as $li ) if ( $li->nodeType===XML_ELEMENT_NODE && strtolower($li->nodeName)==='li' )
				$items .= "<!-- wp:list-item -->\n<li>".bw_inner($li,$doc)."</li>\n<!-- /wp:list-item -->\n";
			if ( $items==='' ) return '';
			$attr=$ordered?' {"ordered":true}':''; $t=$ordered?'ol':'ul';
			return "<!-- wp:list$attr -->\n<$t>\n$items</$t>\n<!-- /wp:list -->\n\n"; }
		case 'blockquote':
			return "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\">".bw_inner($node,$doc)."</blockquote>\n<!-- /wp:quote -->\n\n";
		case 'table':
			return "<!-- wp:table -->\n<figure class=\"wp-block-table\">".$doc->saveHTML($node)."</figure>\n<!-- /wp:table -->\n\n";
		case 'div': { $h=''; foreach ( $node->childNodes as $c ) $h .= bw_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: $out=$doc->saveHTML($node);
			return trim(strip_tags($out))==='' ? '' : "<!-- wp:paragraph -->\n<p>$out</p>\n<!-- /wp:paragraph -->\n\n";
	}
}
function bw_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 .= bw_node_block($n,$doc);
	return $out;
}
function bw_text_to_blocks( $html ) {
	$html = trim($html); if ( $html==='' ) return '';
	if ( preg_match('/<(p|h[1-6]|ul|ol|blockquote|table|pre|figure)\b/i', $html) ) return bw_dom_to_blocks($html);
	$html = preg_replace('/[\r\n]+/', ' ', $html);
	$parts = preg_split('/(?:<br\s*\/?>\s*){2,}/i', $html); $out='';
	foreach ( $parts as $p ) { $p = trim( preg_replace('/^(?:<br\s*\/?>\s*)+|(?:<br\s*\/?>\s*)+$/i', '', $p) );
		if ( $p==='' || ( trim(strip_tags($p))==='' && stripos($p,'<img')===false ) ) continue;
		$out .= "<!-- wp:paragraph -->\n<p>$p</p>\n<!-- /wp:paragraph -->\n\n"; }
	return $out;
}

/* ---------- image helpers (with captions) ---------- */
function bw_side( $im, $post_id, $title ) {
	$path = $im['file']; if ( empty($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), $post_id, $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;
}
function bw_img_block( $id, $alt, $caption='' ) {
	$url = wp_get_attachment_image_url( $id, 'large' );
	$fig = ($caption!=='') ? '<figcaption class="wp-element-caption">'.esc_html($caption).'</figcaption>' : '';
	return '<!-- wp:image {"id":'.$id.',"sizeSlug":"large","linkDestination":"none"} -->'
	     . '<figure class="wp-block-image size-large"><img src="'.esc_url($url).'" alt="'.esc_attr($alt).'" class="wp-image-'.$id.'"/>'.$fig.'</figure>'
	     . '<!-- /wp:image -->';
}

/* ---------- import ---------- */
$created=0; $imgs=0;
foreach ( $blogs as $b ) {
	$old = get_posts(array('post_type'=>'post','post_status'=>'any','numberposts'=>1,
		'meta_key'=>'_bw_src_blog','meta_value'=>(string)$b['laravel_blog_id'],'fields'=>'ids'));
	if ( $old ) { foreach ( get_attached_media('', $old[0]) as $a ) wp_delete_post($a->ID, true); wp_delete_post($old[0], true); }

	$arr = array('post_type'=>'post','post_status'=>'publish','post_title'=>$b['name'],'post_name'=>$b['slug'],'post_content'=>'');
	if ( ! empty($b['date']) ) { $arr['post_date']=$b['date']; $arr['post_date_gmt']=get_gmt_from_date($b['date']); }
	$pid = wp_insert_post( $arr );
	if ( is_wp_error($pid) || ! $pid ) continue;
	add_post_meta( $pid, '_bw_src_blog', (string)$b['laravel_blog_id'], true );
	$created++;

	update_field( 'field_bwm_blog_author', $b['author'], $pid );
	if ( $b['yoast_title']!=='' ) update_post_meta($pid,'_yoast_wpseo_title',$b['yoast_title']);
	if ( $b['yoast_desc'] !=='' ) update_post_meta($pid,'_yoast_wpseo_metadesc',$b['yoast_desc']);
	if ( $b['categories'] ) wp_set_object_terms($pid, $b['categories'], 'category', false);

	// HERO
	$hero = $b['hero'];
	if ( $hero ) {
		$ids = array();
		foreach ( $hero['images'] as $im ) { $a = bw_side($im, $pid, $b['name']); if ($a) { $ids[]=$a; $imgs++; } }
		if ( $ids ) {
			set_post_thumbnail( $pid, $ids[0] );
			if ( $hero['type']==='gallery' && count($ids)>1 ) {
				update_field('field_bwm_hero_type','gallery',$pid);
				update_field('field_bwm_hero_gallery',$ids,$pid);
				update_field('field_bwm_hero_cols',(int)$hero['columns'],$pid);
			} else { update_field('field_bwm_hero_type','image',$pid); }
		}
	} else { update_field('field_bwm_hero_type','image',$pid); }

	// BODY (proper blocks; hero NOT re-embedded)
	$content='';
	foreach ( $b['blocks'] as $blk ) {
		if ( $blk['type']==='text' ) { $content .= bw_text_to_blocks($blk['html']); }
		else { // in-body gallery
			$inner=array();
			foreach ( $blk['images'] as $im ) { $a=bw_side($im,$pid,$b['name']); if($a){ $imgs++; $inner[]=bw_img_block($a,$im['alt'],$im['caption']??''); } }
			if ( ! $inner ) continue;
			if ( count($inner)===1 ) { $content .= $inner[0]."\n\n"; }
			else { $cols=(int)$blk['columns'];
				$content .= '<!-- wp:gallery {"columns":'.$cols.',"linkTo":"none"} -->'
				 . '<figure class="wp-block-gallery has-nested-images columns-'.$cols.' is-cropped">'.implode('',$inner).'</figure>'
				 . '<!-- /wp:gallery -->'."\n\n"; }
		}
	}
	wp_update_post( array('ID'=>$pid,'post_content'=>trim($content)) );
}
echo "RECENT BLOGS (full): posts=$created images=$imgs\n";
