<?php
/** Blog PILOT importer (10 posts, full fidelity). Native posts at /blogs/{slug}.
 *  Re-runnable: deletes the 10 pilot posts + their attachments, then recreates. */
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';

$DIR  = WP_CONTENT_DIR . '/_imp_blog';
$cats = json_decode( file_get_contents( "$DIR/blog-categories.json" ), true );
$blogs= json_decode( file_get_contents( "$DIR/blog-pilot.json" ), true );

/* ---- category hierarchy (2 passes: parents then children) ---- */
$tmade = 0;
$mkcat = function( $name, $parent_id ) use ( &$tmade ) {
	$existing = term_exists( $name, 'category', $parent_id ?: 0 );
	if ( $existing ) return (int) ( is_array($existing) ? $existing['term_id'] : $existing );
	$r = wp_insert_term( $name, 'category', array( 'parent' => $parent_id ?: 0 ) );
	if ( is_wp_error($r) ) return 0;
	$tmade++; return (int) $r['term_id'];
};
$catid = array();
foreach ( $cats as $c ) { if ( $c['parent'] === '' ) $catid[$c['name']] = $mkcat( $c['name'], 0 ); }
foreach ( $cats as $c ) { if ( $c['parent'] !== '' ) {
	$pid = $catid[ $c['parent'] ] ?? $mkcat( $c['parent'], 0 );
	$catid[ $c['name'] ] = $mkcat( $c['name'], $pid );
} }

/* ---- helper: sideload a staged file, return [attach_id, url] ---- */
function bw_sideload( $path, $post_id, $alt, $title ) {
	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 ( $alt ) update_post_meta( $att, '_wp_attachment_image_alt', $alt );
	return array( $att, wp_get_attachment_url($att) );
}

$created = 0; $imgs = 0;
foreach ( $blogs as $b ) {
	// delete prior pilot post + its attachments (clean re-run)
	$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 );
		$kids = get_children( array('post_parent'=>$old[0]) );
		foreach ( $kids as $k ) wp_delete_post( $k->ID, true );
		wp_delete_post( $old[0], true );
	}

	$postarr = array('post_type'=>'post','post_status'=>'publish','post_title'=>$b['name'],
		'post_name'=>$b['slug'],'post_content'=>'');
	if ( ! empty($b['date']) ) { $postarr['post_date']=$b['date']; $postarr['post_date_gmt']=get_gmt_from_date($b['date']); }
	$pid = wp_insert_post( $postarr );
	if ( is_wp_error($pid) || ! $pid ) continue;
	add_post_meta( $pid, '_bw_src_blog', (string)$b['laravel_blog_id'], true );
	if ( get_post_status($pid)==='future' ) { global $wpdb; $wpdb->update($wpdb->posts,array('post_status'=>'publish'),array('ID'=>$pid)); clean_post_cache($pid); }
	$created++;

	// author + yoast
	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']);

	// categories
	$tids = array();
	foreach ( $b['categories'] as $cn ) { if ( isset($catid[$cn]) ) $tids[] = $catid[$cn]; }
	if ( $tids ) wp_set_object_terms( $pid, $tids, 'category', false );

	// featured image
	if ( ! empty($b['featured']) ) {
		$f = bw_sideload( $b['featured'], $pid, $b['name'], $b['name'] );
		if ( $f ) { set_post_thumbnail( $pid, $f[0] ); $imgs++; }
	}

	// body: assemble blocks in order
	$content = '';
	foreach ( $b['blocks'] as $blk ) {
		if ( $blk['type']==='text' ) {
			$content .= "<!-- wp:html -->\n".$blk['html']."\n<!-- /wp:html -->\n\n";
		} else { // image
			$im = bw_sideload( $blk['file'], $pid, $blk['alt'], $b['name'] );
			if ( $im ) {
				$imgs++;
				$alt = esc_attr( $blk['alt'] );
				$content .= '<!-- wp:image {"id":'.$im[0].',"sizeSlug":"large","linkDestination":"none"} -->'
				 . '<figure class="wp-block-image size-large"><img src="'.esc_url($im[1]).'" alt="'.$alt.'" class="wp-image-'.$im[0].'"/></figure>'
				 . "<!-- /wp:image -->\n\n";
			}
		}
	}
	wp_update_post( array('ID'=>$pid,'post_content'=>$content) );
}
echo "BLOG PILOT: posts=$created images=$imgs new_category_terms=$tmade\n";
