<?php
$DEF = [
  408 => ['en'=>'New Testament','fr'=>'Nouveau Testament','it'=>'Nuovo Testamento','pt'=>'Novo Testamento'],
  409 => ['en'=>'Old Testament','fr'=>'Ancien Testament','it'=>'Antico Testamento','pt'=>'Antigo Testamento'],
];
$LOGIN = [408=>'nt', 409=>'at'];
// 1) crear/asegurar usuarios por idioma
$uid_map = []; // [es_author][lang] => uid
foreach ($DEF as $es_author => $names) {
  foreach ($names as $L => $dn) {
    $login = $LOGIN[$es_author].'-'.$L;
    $u = get_user_by('login', $login);
    if (!$u) {
      $id = wp_insert_user(['user_login'=>$login,'user_pass'=>wp_generate_password(20),
        'user_email'=>$login.'@feadulta.local','display_name'=>$dn,'role'=>'author','first_name'=>$dn]);
      if (is_wp_error($id)) { echo "ERROR user $login: ".$id->get_error_message()."\n"; continue; }
      echo "creado usuario $login (#$id) = $dn\n";
    } else { $id = $u->ID; wp_update_user(['ID'=>$id,'display_name'=>$dn]); echo "existe $login (#$id)\n"; }
    $uid_map[$es_author][$L] = $id;
  }
}
// 2) reasignar autor de las traducciones según el autor del ES original
$reasig = 0;
foreach ([408,409] as $es_author) {
  $posts = get_posts(['author'=>$es_author,'post_type'=>'post','post_status'=>['publish','draft'],
    'posts_per_page'=>-1,'fields'=>'ids','lang'=>'es','no_found_rows'=>true]);
  foreach ($posts as $es_id) {
    $tr = pll_get_post_translations($es_id);
    foreach (['en','fr','it','pt'] as $L) {
      if (empty($tr[$L]) || empty($uid_map[$es_author][$L])) continue;
      $p = get_post($tr[$L]);
      if ($p && (int)$p->post_author !== (int)$uid_map[$es_author][$L]) {
        wp_update_post(['ID'=>$tr[$L],'post_author'=>$uid_map[$es_author][$L]]);
        $reasig++;
      }
    }
  }
  echo "ES autor $es_author: ".count($posts)." posts ES procesados\n";
}
// 2ª pasada: cualquier post no-ES que aún tenga el autor bíblico ES → autor del idioma
$reasig2 = 0;
foreach ([408,409] as $es_author) {
  foreach (['en','fr','it','pt'] as $L) {
    if (empty($uid_map[$es_author][$L])) continue;
    $ids = get_posts(['author'=>$es_author,'lang'=>$L,'post_type'=>'post',
      'post_status'=>['publish','draft'],'fields'=>'ids','posts_per_page'=>-1,'no_found_rows'=>true]);
    foreach ($ids as $id) { wp_update_post(['ID'=>$id,'post_author'=>$uid_map[$es_author][$L]]); $reasig2++; }
  }
}
echo "traducciones reasignadas de autor: $reasig (1ª) + $reasig2 (2ª directa)\n";
