<?php
/**
 * Staff importer — run with:  wp eval-file wp-content/_import/import-staff.php
 * Idempotent: keyed on meta _bw_src_staff.
 */
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';

$rows = json_decode( file_get_contents( WP_CONTENT_DIR . '/_import/staff.json' ), true );
$created = 0; $updated = 0; $imgs = 0; $img_fail = 0; $terms_made = 0;

// Ensure department terms exist (collect distinct first).
$all_deps = array();
foreach ( $rows as $r ) { foreach ( $r['departments'] as $d ) { $all_deps[$d] = 1; } }
foreach ( array_keys($all_deps) as $d ) {
	if ( ! term_exists( $d, 'department' ) ) { wp_insert_term( $d, 'department' ); $terms_made++; }
}

foreach ( $rows as $r ) {
	// find existing
	$existing = get_posts( array(
		'post_type'   => 'staff', 'post_status' => 'any', 'numberposts' => 1,
		'meta_key'    => '_bw_src_staff', 'meta_value' => (string) $r['src'], 'fields' => 'ids',
	) );

	$postarr = array(
		'post_type'    => 'staff',
		'post_title'   => $r['title'],
		'post_content' => $r['bio'],
		'post_status'  => $r['state'],
	);
	if ( ! empty($r['date']) ) {
		$d = strlen($r['date']) <= 10 ? $r['date'].' 00:00:00' : $r['date'];
		$postarr['post_date'] = $d;
		$postarr['post_date_gmt'] = get_gmt_from_date( $d );
	}

	if ( $existing ) {
		$postarr['ID'] = $existing[0];
		$pid = wp_update_post( $postarr );
		$updated++;
	} else {
		$pid = wp_insert_post( $postarr );
		add_post_meta( $pid, '_bw_src_staff', (string) $r['src'], true );
		$created++;
	}
	if ( is_wp_error($pid) || ! $pid ) { continue; }

	// ACF fields
	update_field( 'field_bwm_staff_position',    $r['position'],    $pid );
	update_field( 'field_bwm_staff_credentials', $r['credentials'], $pid );

	// departments
	if ( ! empty($r['departments']) ) {
		wp_set_object_terms( $pid, $r['departments'], 'department', false );
	}

	// featured image
	if ( ! empty($r['img']) && ! has_post_thumbnail($pid) && file_exists($r['img']) ) {
		$tmp = wp_tempnam( basename($r['img']) );
		if ( copy( $r['img'], $tmp ) ) {
			$file_array = array( 'name' => basename($r['img']), 'tmp_name' => $tmp );
			$att = media_handle_sideload( $file_array, $pid, $r['title'] );
			if ( is_wp_error($att) ) { @unlink($tmp); $img_fail++; }
			else {
				set_post_thumbnail( $pid, $att );
				update_post_meta( $att, '_wp_attachment_image_alt', $r['alt'] );
				$imgs++;
			}
		} else { @unlink($tmp); $img_fail++; }
	}
}
echo "STAFF: created=$created updated=$updated term_new=$terms_made images=$imgs image_fail=$img_fail\n";
