<?php
/** FULL blog importer — resumable. Hero/body split, proper Gutenberg blocks,
 *  photo-block text, captions. Skips posts already finished (_bw_done). */
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);

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

/* ---------- HTML -> Gutenberg blocks ---------- */
function bw_inner($n,$d){ $h=''; foreach($n->childNodes as $c){ $h.=$d->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]); $in=bw_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=bw_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>".bw_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\">".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: $o=$doc->saveHTML($node); return trim(strip_tags($o))===''?'':"<!-- wp:paragraph -->\n<p>$o</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;
}
/* ---------- images ---------- */
function bw_side($im,$pid,$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),$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;
}
function bw_img_block($id,$alt,$cap=''){
	$url=wp_get_attachment_image_url($id,'large');
	$f=($cap!=='')?'<figcaption class="wp-element-caption">'.esc_html($cap).'</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.'"/>'.$f.'</figure><!-- /wp:image -->';
}

/* ---------- run ---------- */
global $wpdb;
$done=0; $skip=0; $imgs=0; $i=0; $total=count($blogs);
foreach($blogs as $b){
	$i++;
	$existing=$wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_bw_src_blog' AND meta_value=%s LIMIT 1",(string)$b['laravel_blog_id']));
	if($existing){
		if(get_post_meta($existing,'_bw_done',true)){ $skip++; continue; }       // already finished
		foreach(get_attached_media('',$existing) as $a) wp_delete_post($a->ID,true);
		wp_delete_post($existing,true);                                          // partial -> redo
	}
	$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);

	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=$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);

	$content='';
	foreach($b['blocks'] as $blk){
		if($blk['type']==='text'){ $content.=bw_text_to_blocks($blk['html']); }
		else { $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)));
	update_post_meta($pid,'_bw_done',1);
	$done++;
	if($done%100===0){ echo "[".date('H:i:s')."] progress: $i/$total (done=$done skip=$skip imgs=$imgs)\n"; wp_cache_flush(); }
}
echo "DONE full blog import: imported=$done skipped=$skip images=$imgs total_seen=$i\n";
