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

$CARTA = (int)(getenv("CARTA") ?: 46956);
$ids = array_values(pll_get_post_translations($CARTA)) ?: [$CARTA];

// k2_id -> ES post
function es_post_by_k2($k2){ global $wpdb; return (int)$wpdb->get_var($wpdb->prepare(
  "SELECT post_id FROM wp_postmeta WHERE meta_key='_fgj2wp_old_k2_id' AND meta_value=%s LIMIT 1",$k2)); }
// slug -> ES post
function es_post_by_slug($slug){ global $wpdb; return (int)$wpdb->get_var($wpdb->prepare(
  "SELECT ID FROM wp_posts WHERE post_name=%s AND post_type='post' AND post_status IN('publish','draft','future') LIMIT 1",$slug)); }

$tot=0;
foreach($ids as $pid){
  $post=get_post($pid); if(!$post) continue;
  $lang=pll_get_post_language($pid) ?: 'es';
  $chg=0; $miss=[];
  $new=preg_replace_callback('~href="([^"]+)"~i', function($m) use($lang,&$chg,&$miss){
    $href=html_entity_decode(trim($m[1]));
    if(stripos($href,'.html')===false) return $m[0];            // solo legacy joomla .html
    if(stripos($href,'feadulta.com')!==false) return $m[0];     // dominio viejo absoluto -> dejar
    $es=0;
    if(preg_match('~/item/(\d+)-~',$href,$mm)) $es=es_post_by_k2($mm[1]);
    if(!$es && preg_match('~/?([a-z0-9-]+)\.html$~i',$href,$mm)) $es=es_post_by_slug($mm[1]);
    if(!$es){ $miss[]=$href; return $m[0]; }
    $t=pll_get_post($es,$lang) ?: $es;
    $url=get_permalink($t);
    if(!$url) return $m[0];
    $chg++;
    return 'href="'.esc_url($url).'"';
  }, $post->post_content);
  echo sprintf("#%d [%s] «%s» — %d reescritos%s\n",$pid,$lang,mb_substr($post->post_title,0,30),$chg,
       $miss?("  | sin mapear: ".implode(", ",array_slice($miss,0,4))):"");
  $tot+=$chg;
  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 "\n".($APPLY?"APLICADO":"DRY-RUN").": $tot enlaces.\n";
