<?php
/**
 * Ciclo carta nueva — sincroniza "esta semana", "semana pasada" y "otras semanas"
 * en TODOS los idiomas (ES + EN/FR/IT/PT).
 *
 * Deriva los términos por Polylang desde los términos ES base:
 *   cartasemana = term 6 | otras semanas = term 21 | semana pasada = term 22
 *
 * Uso:  CARTA=<es_id> php demote_old_cartasemana.php        (dry-run)
 *       APPLY=1 CARTA=<es_id> php demote_old_cartasemana.php
 */
require getenv('FEA_WP_LOAD') ?: '/var/www/html/wp-load.php';
$APPLY = getenv('APPLY') === '1';
$CARTA = (int)(getenv('CARTA') ?: 0);
if (!$CARTA) { fwrite(STDERR,"Falta CARTA=<es_id>\n"); exit(1); }

$cs_terms    = pll_get_term_translations(6);   // cartasemana por idioma
$otras_terms = pll_get_term_translations(21);  // cartas de otras semanas por idioma
$last_terms  = pll_get_term_translations(22);  // carta semana pasada por idioma
$carta_tr    = pll_get_post_translations($CARTA);
$last_es_posts = get_posts([
    'post_type'        => 'post',
    'numberposts'      => 1,
    'post_status'      => 'publish',
    'fields'           => 'ids',
    'cat'              => 22,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'suppress_filters' => true,
]);
$last_es = (int) ($last_es_posts[0] ?? 0);
$last_tr = $last_es ? pll_get_post_translations($last_es) : [];

foreach ($cs_terms as $lang=>$cs) {
    $keep  = $carta_tr[$lang] ?? 0;
    $otras = $otras_terms[$lang] ?? 0;
    $last  = $last_terms[$lang] ?? 0;
    $keep_last = $last_tr[$lang] ?? 0;
    $posts = get_posts(['post_type'=>'post','numberposts'=>-1,'post_status'=>'any','fields'=>'ids',
        'tax_query'=>[['taxonomy'=>'category','field'=>'term_id','terms'=>$cs]]]);
    $moved=0;
    foreach ($posts as $pid) {
        if ($pid == $keep) continue;
        if ($APPLY) {
            if ($otras) wp_set_object_terms($pid,[(int)$otras],'category',true); // append a otras
            wp_remove_object_terms($pid,[(int)$cs],'category');
        }
        $moved++;
    }
    $last_posts = $last ? get_posts([
        'post_type'=>'post','numberposts'=>-1,'post_status'=>'any','fields'=>'ids',
        'tax_query'=>[['taxonomy'=>'category','field'=>'term_id','terms'=>$last]],
    ]) : [];
    $last_removed = 0;
    foreach ($last_posts as $pid) {
        if ($pid == $keep_last) continue;
        if ($APPLY) wp_remove_object_terms($pid, [(int)$last], 'category');
        $last_removed++;
    }
    if ($APPLY && $last && $keep_last) {
        wp_set_object_terms($keep_last, [(int)$last], 'category', true);
    }
    if ($APPLY) clean_term_cache(array_filter([$cs,$otras,$last]),'category');
    $t=get_term($cs);
    echo sprintf("%s: %s %d de actual | anterior=#%d (limpia %d) | '%s' keep=#%d\n",
        strtoupper($lang), $APPLY?"movidas":"se moverían", $moved,
        $keep_last, $last_removed, $t->slug, $keep);
}
echo $APPLY ? "APLICADO\n" : "DRY-RUN (APPLY=1 para aplicar)\n";
