<?php
/**
 * assign_polylang_languages.php
 *
 * Asigna idioma Polylang a cada post de WordPress basándose en el campo
 * "Idioma" (extra_field id=16) de K2 Joomla, cruzando por _fgj2wp_old_k2_id.
 *
 * Mapa K2 → Polylang:
 *   1 = Español  → es
 *   2 = Inglés   → en
 *   3 = Francés  → fr
 *   4 = Italiano → it
 *   5 = Portugués → pt
 *
 * Requisitos:
 *   - Polylang instalado y activado
 *   - Los 5 idiomas creados en Polylang (es, en, fr, it, pt)
 *   - DB Joomla accesible (ajustar credenciales abajo si hace falta)
 *
 * Uso: wp eval-file assign_polylang_languages.php
 *   o copiarlo a /wp-content/mu-plugins/ y acceder via navegador con ?run_assign_lang=1
 */

if ( ! defined('ABSPATH') ) {
    // Ejecución directa via navegador
    define('RUN_VIA_BROWSER', true);
    $_SERVER['HTTP_HOST'] = 'localhost';
    require_once dirname(__FILE__) . '/../../wp-load.php';
}

if ( defined('RUN_VIA_BROWSER') && ! isset($_GET['run_assign_lang']) ) {
    echo 'Añade ?run_assign_lang=1 a la URL para ejecutar.';
    exit;
}

if ( ! function_exists('pll_set_post_language') ) {
    echo "ERROR: Polylang no está activo.\n";
    exit(1);
}

// ── Configuración Joomla DB ───────────────────────────────────────────────────
$joomla_host = defined('RUN_VIA_BROWSER') ? '127.0.0.1' : 'joomla-mysql';
$joomla_db   = 'joomla_db';
$joomla_user = 'joomla_user';
$joomla_pass = 'joomla_pass';

$jdb = new mysqli($joomla_host, $joomla_user, $joomla_pass, $joomla_db);
if ( $jdb->connect_error ) {
    echo "ERROR conectando a Joomla DB: " . $jdb->connect_error . "\n";
    exit(1);
}
$jdb->set_charset('utf8mb4');

// ── Mapa de idiomas K2 → código Polylang ─────────────────────────────────────
$lang_map = [
    '1' => 'es',
    '2' => 'en',
    '3' => 'fr',
    '4' => 'it',
    '5' => 'pt',
];

// ── Obtener idiomas disponibles en Polylang ───────────────────────────────────
$pll_languages = pll_languages_list(['fields' => 'slug']);
echo "Idiomas disponibles en Polylang: " . implode(', ', $pll_languages) . "\n";

$missing_langs = array_diff(array_values($lang_map), $pll_languages);
if ( ! empty($missing_langs) ) {
    echo "AVISO: Faltan idiomas en Polylang: " . implode(', ', $missing_langs) . "\n";
    echo "Créalos en Ajustes → Languages antes de continuar.\n";
    exit(1);
}

// ── Leer idiomas de K2 ────────────────────────────────────────────────────────
$result = $jdb->query("
    SELECT id as k2_id,
        CASE
            WHEN extra_fields LIKE '%\"id\":\"16\",\"value\":\"1\"%' THEN '1'
            WHEN extra_fields LIKE '%\"id\":\"16\",\"value\":\"2\"%' THEN '2'
            WHEN extra_fields LIKE '%\"id\":\"16\",\"value\":\"3\"%' THEN '3'
            WHEN extra_fields LIKE '%\"id\":\"16\",\"value\":\"4\"%' THEN '4'
            WHEN extra_fields LIKE '%\"id\":\"16\",\"value\":\"5\"%' THEN '5'
            ELSE '1'
        END as lang_value
    FROM ew4r_k2_items
    WHERE published = 1
");

$k2_langs = [];
while ( $row = $result->fetch_assoc() ) {
    $k2_langs[(int)$row['k2_id']] = $lang_map[$row['lang_value']] ?? 'es';
}
$jdb->close();

echo "K2 items con idioma: " . count($k2_langs) . "\n";

// ── Asignar idioma en WordPress ───────────────────────────────────────────────
global $wpdb;

$counts = array_fill_keys(array_values($lang_map), 0);
$counts['sin_k2_id'] = 0;
$counts['ya_asignado'] = 0;
$processed = 0;

// Obtener todos los posts con su k2_id de una vez
$rows = $wpdb->get_results("
    SELECT p.ID as wp_id, pm.meta_value as k2_id
    FROM {$wpdb->posts} p
    JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
    WHERE pm.meta_key = '_fgj2wp_old_k2_id'
      AND p.post_type = 'post'
      AND p.post_status IN ('publish', 'draft', 'private')
");

$total = count($rows);
echo "Posts WP con _fgj2wp_old_k2_id: {$total}\n";
echo "Procesando...\n";

foreach ( $rows as $row ) {
    $wp_id = (int) $row->wp_id;
    $k2_id = (int) $row->k2_id;

    if ( ! isset($k2_langs[$k2_id]) ) {
        $counts['sin_k2_id']++;
        // Sin datos en K2 → asumir español
        pll_set_post_language($wp_id, 'es');
        continue;
    }

    $lang = $k2_langs[$k2_id];
    pll_set_post_language($wp_id, $lang);
    $counts[$lang]++;
    $processed++;

    if ( $processed % 500 === 0 ) {
        echo "  {$processed}/{$total}...\n";
        if (ob_get_level()) ob_flush();
        flush();
    }
}

// ── Asignar español a posts sin k2_id (cartas, EFFA, etc.) ───────────────────
$posts_sin_k2 = $wpdb->get_col("
    SELECT p.ID FROM {$wpdb->posts} p
    LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_fgj2wp_old_k2_id'
    WHERE pm.post_id IS NULL
      AND p.post_type = 'post'
      AND p.post_status IN ('publish', 'draft', 'private')
");

echo "Posts sin _fgj2wp_old_k2_id (cartas EFFA etc): " . count($posts_sin_k2) . "\n";
foreach ( $posts_sin_k2 as $wp_id ) {
    pll_set_post_language((int)$wp_id, 'es');
}

// ── Eliminar tag "English" falso ──────────────────────────────────────────────
$english_tag = get_term_by('slug', 'english', 'post_tag');
if ( $english_tag ) {
    $tag_posts = get_posts(['tag_id' => $english_tag->term_id, 'numberposts' => 1]);
    if ( empty($tag_posts) || $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->term_relationships} WHERE term_taxonomy_id=%d", $english_tag->term_taxonomy_id)) < 100 ) {
        wp_delete_term($english_tag->term_id, 'post_tag');
        echo "Tag 'English' falso eliminado.\n";
    } else {
        // Desasociar masivamente antes de borrar
        $wpdb->delete($wpdb->term_relationships, [
            'term_taxonomy_id' => $english_tag->term_taxonomy_id
        ]);
        wp_update_term_count($english_tag->term_id, 'post_tag');
        wp_delete_term($english_tag->term_id, 'post_tag');
        echo "Tag 'English' falso eliminado (12845 asociaciones borradas).\n";
    }
}

// ── Resumen ───────────────────────────────────────────────────────────────────
echo "\n=== RESULTADO ===\n";
foreach ( $lang_map as $val => $slug ) {
    $names = ['1'=>'Español','2'=>'Inglés','3'=>'Francés','4'=>'Italiano','5'=>'Portugués'];
    echo "  {$names[$val]} ({$slug}): " . ($counts[$slug] ?? 0) . " posts\n";
}
echo "  Sin k2_id (→es): " . $counts['sin_k2_id'] . "\n";
echo "  Posts sin k2_id (cartas/EFFA): " . count($posts_sin_k2) . "\n";
echo "\nListo.\n";
