<?php
/**
 * apply_lecturas_wp.php — Crea las traducciones de lecturas bíblicas casadas por
 * referencia (lecturas_apply.py) y las asocia en Polylang. Idempotente.
 *
 * Ejecutar dentro del contenedor:
 *   docker cp /tmp/lecturas_creadas.json wordpress-web:/tmp/
 *   docker exec wordpress-web wp eval-file /tmp/apply_lecturas_wp.php [publish]
 */
$status = (isset($argv[1]) && $argv[1] === 'publish') ? 'publish' : 'draft';
$data = json_decode(file_get_contents('/tmp/lecturas_creadas.json'), true);
$created = 0; $posts_done = 0; $skipped = 0;
foreach ($data as $row) {
    $es_id = (int) $row['es_id'];
    $es = get_post($es_id);
    if (!$es) { $skipped++; continue; }
    $existing = function_exists('pll_get_post_translations') ? pll_get_post_translations($es_id) : ['es' => $es_id];
    $group = $existing;
    $es_cats = wp_get_post_categories($es_id);
    foreach (['en', 'fr', 'it', 'pt'] as $L) {
        if (!empty($existing[$L])) { $group[$L] = $existing[$L]; continue; }
        if (empty($row['langs'][$L])) continue;
        $id = wp_insert_post([
            'post_title'     => $es->post_title,      // referencia bíblica (igual en todos)
            'post_content'   => $row['langs'][$L],
            'post_status'    => $status,
            'post_type'      => 'post',
            'comment_status' => 'closed',
        ], true);
        if (is_wp_error($id)) continue;
        pll_set_post_language($id, $L);
        $cats = [];
        foreach ($es_cats as $c) { $t = pll_get_term($c, $L); if ($t) $cats[] = $t; }
        if ($cats) wp_set_post_categories($id, $cats);
        $group[$L] = $id;
        $created++;
    }
    if (function_exists('pll_save_post_translations')) pll_save_post_translations($group);
    $posts_done++;
}
echo "posts ES procesados: $posts_done | traducciones creadas: $created | status=$status | skip=$skipped\n";
