<?php
/**
 * Page-hero importer (run via wp-cli eval-file). Consumes the staged
 * _imp_heroes/import.json, sideloads each title-area media file from the
 * staging dir, and sets the Page Hero ACF fields per hero_type:
 *   image    -> featured image (the image hero renders the thumbnail)
 *   carousel -> hero_gallery [ids]
 *   dual     -> hero_gallery [ids] (first two)
 *   video    -> hero_video (attachment id)
 * Idempotent: attachments reused by _bw_hero_src marker; pages marked with
 * _bw_src_page_hero. Pass "all" or a single slug as the positional arg.
 */
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';

$only  = isset( $args[0] ) ? trim( (string) $args[0] ) : 'all';
$dir   = get_stylesheet_directory() . '/_imp_heroes';
$items = json_decode( file_get_contents( $dir . '/import.json' ), true );

$F_TYPE = 'field_bwm_page_hero_type';
$F_GAL  = 'field_bwm_page_hero_gallery';
$F_VID  = 'field_bwm_page_hero_video';

function bw_hero_find( $src ) {
	$q = get_posts( array( 'post_type'=>'attachment','numberposts'=>1,'fields'=>'ids',
		'meta_key'=>'_bw_hero_src','meta_value'=>$src ) );
	return $q ? (int) $q[0] : 0;
}
function bw_hero_sideload( $dir, $file, $src, $pid ) {
	$existing = bw_hero_find( $src );
	if ( $existing ) return $existing;
	$path = $dir . '/' . $file;
	if ( ! file_exists( $path ) ) return 0;
	$tmp = wp_tempnam( $file );
	copy( $path, $tmp );
	$att = media_handle_sideload( array( 'name'=>$file, 'tmp_name'=>$tmp ), $pid, null );
	if ( is_wp_error( $att ) ) { @unlink( $tmp ); return 0; }
	update_post_meta( $att, '_bw_hero_src', $src );
	return (int) $att;
}

$done=$skip=$fail=0;
foreach ( $items as $it ) {
	if ( 'all' !== $only && $it['slug'] !== $only ) continue;
	$path = trim( $it['slug'], '/' );
	$pid  = ( '' === $path ) ? (int) get_option('page_on_front') : ( get_page_by_path($path)->ID ?? 0 );
	if ( ! $pid ) { echo "MISS {$it['slug']} (no page)\n"; $fail++; continue; }

	$ids = array();
	foreach ( $it['files'] as $i => $file ) {
		$a = bw_hero_sideload( $dir, $file, $it['source_rel'][$i], $pid );
		if ( $a ) $ids[] = $a;
	}
	if ( ! $ids ) { echo "FAIL {$it['slug']} (no media sideloaded)\n"; $fail++; continue; }

	$type = $it['hero_type'];
	update_field( $F_TYPE, $type, $pid );
	if ( 'image' === $type ) {
		set_post_thumbnail( $pid, $ids[0] );
	} elseif ( in_array( $type, array('carousel','dual'), true ) ) {
		update_field( $F_GAL, $ids, $pid );
	} elseif ( 'video' === $type ) {
		update_field( $F_VID, $ids[0], $pid );
	}
	update_post_meta( $pid, '_bw_src_page_hero', $it['hero_type'] );
	echo "SET  {$it['slug']} #{$pid} {$type} <- " . implode(',', $ids) . "\n";
	$done++;
}
echo "\ndone=$done skip=$skip fail=$fail\n";
