<?php
require getenv('FEA_WP_LOAD') ?: '/var/www/html/wp-load.php';
$ES = (int)(getenv('ES_ID') ?: 2682);          // MATEO 10, 26-33 (es)
$src = get_post($ES);
$tr_html = json_decode(file_get_contents(getenv('LECTURAS_JSON') ?: '/tmp/lecturas_mateo.json'), true);
$BOOK = ['en'=>'MATTHEW','fr'=>'MATTHIEU','it'=>'MATTEO','pt'=>'MATEUS'];
$VER  = ['en'=>'Douay-Rheims Bible','fr'=>'Bible du Semeur 2015','it'=>'Nuova Riveduta 2006','pt'=>'Bíblia CNBB 2002'];
$REST = getenv('LECTURA_TITULO_ES') ?: 'MATEO 10, 26-33'; // título es
$tail = preg_replace('~^MATEO~','',$REST); // " 10, 26-33"
$es_cats = wp_get_post_categories($ES);
$target_ids = array_values(array_filter(array_map('intval', explode(',', getenv('TARGET_IDS') ?: ''))));
$target_map = [];
foreach (['en','fr','it','pt'] as $idx => $lang0) {
    if (!empty($target_ids[$idx])) $target_map[$lang0] = (int)$target_ids[$idx];
}

$grp = pll_get_post_translations($ES); if(!$grp) $grp=['es'=>$ES];
foreach (['en','fr','it','pt'] as $lang) {
    $exist = (int)pll_get_post($ES,$lang);
    if ($exist && get_post($exist)) { echo "$lang ya existe #$exist — saltado\n"; $grp[$lang]=$exist; continue; }
    $title = $BOOK[$lang].$tail;
    $postarr = [
        'post_title'=>$title,'post_content'=>$tr_html[$lang],'post_status'=>'publish',
        'post_type'=>'post','post_author'=>(int)$src->post_author,'post_date'=>$src->post_date,
    ];
    $target = (int)($target_map[$lang] ?? 0);
    if ($target && get_post($target)) {
        $postarr['ID'] = $target;
    } elseif ($target) {
        $postarr['import_id'] = $target;
    }
    $id = wp_insert_post($postarr, true);
    if (is_wp_error($id)) { echo "$lang ERROR ".$id->get_error_message()."\n"; continue; }
    if ($target && (int)$id !== $target) { echo "$lang ERROR id esperado $target creado $id\n"; continue; }
    pll_set_post_language($id,$lang);
    $mapped=[]; foreach($es_cats as $c){ $tc=(int)pll_get_term($c,$lang); $mapped[]=$tc?:$c; }
    wp_set_post_categories($id, array_values(array_unique($mapped)));
    $grp[$lang]=$id; pll_save_post_translations($grp);
    update_post_meta($id,'lectura_fuente',$VER[$lang]);
    update_post_meta($id,'traduccion_origen',$ES);
    echo "$lang creado #$id «$title» [".$VER[$lang]."]\n";
}
echo "Grupo final: ".json_encode(pll_get_post_translations($ES))."\n";
