<?php
/** Livestream importer. Idempotent on _bw_src_livestream. */
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/livestream.json' ), true );
$created=0;$updated=0;$imgs=0;$img_fail=0;$terms_made=0;

$allc=array();
foreach($rows as $r){ foreach($r['categories'] as $c){ $allc[$c]=1; } }
foreach(array_keys($allc) as $c){ if(!term_exists($c,'livestream_category')){ wp_insert_term($c,'livestream_category'); $terms_made++; } }

foreach($rows as $r){
	$existing = get_posts(array('post_type'=>'livestream','post_status'=>'any','numberposts'=>1,
		'meta_key'=>'_bw_src_livestream','meta_value'=>(string)$r['src'],'fields'=>'ids'));
	$postarr=array('post_type'=>'livestream','post_title'=>$r['title'],'post_content'=>$r['description'],
		'post_status'=>'publish','post_name'=>$r['slug']);
	if(!empty($r['start'])){ $postarr['post_date']=$r['start']; $postarr['post_date_gmt']=get_gmt_from_date($r['start']); }
	if($existing){ $postarr['ID']=$existing[0]; $pid=wp_update_post($postarr); $updated++; }
	else { $pid=wp_insert_post($postarr); add_post_meta($pid,'_bw_src_livestream',(string)$r['src'],true); $created++; }
	if(is_wp_error($pid)||!$pid){ continue; }

	// Upcoming (future-dated) livestreams must stay visible, not scheduled.
	if(get_post_status($pid)==='future'){ global $wpdb; $wpdb->update($wpdb->posts,array('post_status'=>'publish'),array('ID'=>$pid)); wp_clear_scheduled_hook('publish_future_post',array((int)$pid)); clean_post_cache($pid); }

	update_field('field_bwm_ls_youtube',  $r['youtube'], $pid);
	update_field('field_bwm_ls_start',    $r['start'] ?: '', $pid);
	if($r['length']!=='') update_field('field_bwm_ls_length', intval($r['length']), $pid);
	update_field('field_bwm_ls_unlisted', $r['unlisted']?1:0, $pid);

	if(!empty($r['categories'])) wp_set_object_terms($pid, $r['categories'], 'livestream_category', false);

	if(!empty($r['img']) && !has_post_thumbnail($pid) && file_exists($r['img'])){
		$tmp=wp_tempnam(basename($r['img']));
		if(copy($r['img'],$tmp)){
			$fa=array('name'=>basename($r['img']),'tmp_name'=>$tmp);
			$att=media_handle_sideload($fa,$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']?:$r['title']); $imgs++; }
		} else { @unlink($tmp); $img_fail++; }
	}
}
echo "LIVESTREAM: created=$created updated=$updated term_new=$terms_made images=$imgs image_fail=$img_fail\n";
