<?php
/** Pages + Landing importer. Builds the page hierarchy from full paths.
 *  Idempotent on _bw_src_page (path) / _bw_src_landing (leaf). No body content. */
if ( ! defined('ABSPATH') ) { exit; }
$data = json_decode( file_get_contents( WP_CONTENT_DIR . '/_imp_pages/pages.json' ), true );

$TITLE_META = '_bw_dev_title_override';
$by_path = array();   // path => post_id
$created=0; $updated=0; $stubs=0; $overrides=0; $home_id=0;

function bwm_find( $type, $key, $val ) {
	$p = get_posts(array('post_type'=>$type,'post_status'=>'any','numberposts'=>1,
		'meta_key'=>$key,'meta_value'=>$val,'fields'=>'ids'));
	return $p ? $p[0] : 0;
}
function bwm_set_seo_and_h1( $pid, $rec, $title_meta, &$overrides ) {
	if ( !empty($rec['title']) ) update_post_meta($pid,'_yoast_wpseo_title',$rec['title']);
	if ( !empty($rec['desc']) )  update_post_meta($pid,'_yoast_wpseo_metadesc',$rec['desc']);
	$h1 = isset($rec['h1']) ? trim($rec['h1']) : '';
	$name = isset($rec['name']) ? trim($rec['name']) : '';
	if ( $h1 !== '' && $h1 !== $name ) { update_post_meta($pid,$title_meta,$h1); $overrides++; }
	else { delete_post_meta($pid,$title_meta); }
}

// ---- internal pages: sort by depth so parents exist first ----
$internal = $data['internal'];
usort($internal, function($a,$b){ return substr_count($a['path'],'/') <=> substr_count($b['path'],'/'); });

// helper to ensure a parent path exists (auto-stub) — returns post_id (0 for root)
$ensure_parent = function($path) use (&$by_path,&$stubs) {
	if ($path==='') return 0;
	if (isset($by_path[$path])) return $by_path[$path];
	// create stub draft page chain
	$parts = explode('/',$path); $accum=''; $parent=0;
	foreach ($parts as $seg) {
		$accum = $accum==='' ? $seg : "$accum/$seg";
		if (isset($by_path[$accum])) { $parent=$by_path[$accum]; continue; }
		$pid = wp_insert_post(array('post_type'=>'page','post_title'=>ucwords(str_replace('-',' ',$seg)),
			'post_name'=>$seg,'post_status'=>'draft','post_parent'=>$parent));
		add_post_meta($pid,'_bw_src_page',$accum,true);
		add_post_meta($pid,'_bw_stub',1,true);
		$by_path[$accum]=$pid; $parent=$pid; $stubs++;
	}
	return $parent;
};

foreach ($internal as $rec) {
	$path = $rec['path'];
	if ($path==='') {  // HOME
		$leaf='home'; $parent=0;
	} else {
		$parts = explode('/',$path); $leaf=end($parts);
		$parent = $ensure_parent( implode('/', array_slice($parts,0,-1)) );
	}
	$pid = bwm_find('page','_bw_src_page',$path);
	$arr = array('post_type'=>'page','post_title'=>$rec['name'] ?: ucwords(str_replace('-',' ',$leaf)),
		'post_status'=>'publish','post_name'=>$leaf,'post_parent'=>$parent,'post_content'=>'');
	if ($pid) { $arr['ID']=$pid; wp_update_post($arr); $updated++; }
	else { $pid=wp_insert_post($arr); add_post_meta($pid,'_bw_src_page',$path,true); $created++; }
	delete_post_meta($pid,'_bw_stub');  // it's a real page now
	$by_path[$path]=$pid;
	bwm_set_seo_and_h1($pid,$rec,$TITLE_META,$overrides);
	if ($path==='') $home_id=$pid;
}

// set Home as the static front page
if ($home_id) { update_option('show_on_front','page'); update_option('page_on_front',$home_id); }

// ---- landing CPT ----
$l_created=0; $l_updated=0;
foreach ($data['landing'] as $rec) {
	$leaf = $rec['leaf'];
	$pid = bwm_find('landing','_bw_src_landing',$leaf);
	$arr = array('post_type'=>'landing','post_title'=>$rec['name'] ?: $leaf,
		'post_status'=>'publish','post_name'=>$leaf,'post_content'=>'');
	if ($pid) { $arr['ID']=$pid; wp_update_post($arr); $l_updated++; }
	else { $pid=wp_insert_post($arr); add_post_meta($pid,'_bw_src_landing',$leaf,true); $l_created++; }
	bwm_set_seo_and_h1($pid,$rec,$TITLE_META,$overrides);
}

echo "PAGES: created=$created updated=$updated stubs=$stubs h1_overrides=$overrides front_page=$home_id\n";
echo "LANDING: created=$l_created updated=$l_updated\n";
echo "EXTERNAL (skipped, logged): ".count($data['external'])."\n";
