<?php
require getenv('FEA_WP_LOAD') ?: '/var/www/html/wp-load.php';
global $wpdb;
$APPLY = getenv("APPLY")==="1";
$CARTA = (int)(getenv("CARTA") ?: 46956);
$BAK="/tmp/repoint_bak"; if($APPLY) @mkdir($BAK,0777,true);

function resolve_post($href){
    // ?p=ID
    if (preg_match('~[?&]p=(\d+)~',$href,$m)) return (int)$m[1];
    $path = preg_replace('~^https?://[^/]+~i','',$href);
    $path = preg_replace('~[?#].*$~','',$path);
    $path = preg_replace('~^/fea~','',$path);
    $path = preg_replace('~^/(en|fr|it|pt|es)(/|$)~','/',$path);
    $segs = array_values(array_filter(explode('/',$path),'strlen'));
    if (count($segs)!==1) return 0;
    $p = get_page_by_path($segs[0], OBJECT, 'post');
    return $p ? $p->ID : 0;
}

foreach (array_values(pll_get_post_translations($CARTA)) as $pid) {
    $post=get_post($pid); if(!$post) continue;
    $lang=pll_get_post_language($pid) ?: 'es';
    $chg=0;
    $new=preg_replace_callback('~href="([^"]+)"~i', function($m) use($lang,&$chg){
        $href=$m[1];
        if (stripos($href,'.html')!==false) return $m[0];      // legacy lo maneja el otro script
        $tid=resolve_post($href);
        if(!$tid) return $m[0];
        $plang=pll_get_post_language($tid);
        if(!$plang || $plang===$lang) return $m[0];            // ya está en el idioma correcto
        $t=pll_get_post($tid,$lang);
        if(!$t || $t==$tid) return $m[0];                      // no hay traducción -> dejar
        $url=get_permalink($t); if(!$url) return $m[0];
        $chg++; return 'href="'.esc_url($url).'"';
    }, $post->post_content);
    echo "#$pid [$lang] — $chg repuntado(s)\n";
    if($APPLY && $chg){ file_put_contents("$BAK/$pid.html",$post->post_content);
        $wpdb->update($wpdb->posts,['post_content'=>$new],['ID'=>$pid]); clean_post_cache($pid); }
}
echo $APPLY?"APLICADO\n":"DRY-RUN\n";
