<?php
// Importa avatares col_*.png de uploads/autores/joomla/ como attachments WP
// y asigna foto_perfil al user_id correspondiente.
//
// Uso: docker exec wordpress-web php /tmp/import_avatars.php [--dry-run]

require '/var/www/html/wp-load.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

$dry = in_array('--dry-run', $argv ?? [], true);
$tsv = '/tmp/avatar_assignments.tsv';

$uploads     = wp_upload_dir();
$avatars_dir = $uploads['basedir'] . '/autores/joomla';
$avatars_url = $uploads['baseurl'] . '/autores/joomla';

$lines = file($tsv, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
array_shift($lines); // header

$stats = ['ok' => 0, 'reused' => 0, 'missing_file' => 0, 'missing_user' => 0, 'assigned' => 0, 'already' => 0];
$samples_ok = [];

global $wpdb;
$attach_by_file = [];

foreach ($lines as $line) {
    [$aid, $login, $posts, $source, $filename] = explode("\t", $line);
    $aid = (int) $aid;
    $abs = $avatars_dir . '/' . $filename;
    if (!is_file($abs)) { $stats['missing_file']++; continue; }
    if (!get_userdata($aid)) { $stats['missing_user']++; continue; }

    // Si ya tiene foto_perfil, no tocar (preservar manual assignments)
    if (get_user_meta($aid, 'foto_perfil', true)) { $stats['already']++; continue; }

    // ¿Ya existe attachment para este fichero? (reutilizar)
    if (!isset($attach_by_file[$filename])) {
        $url = $avatars_url . '/' . $filename;
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_type='attachment' AND guid=%s LIMIT 1",
            $url
        ));
        if ($existing) {
            $attach_by_file[$filename] = (int) $existing;
            $stats['reused']++;
        } else {
            if ($dry) {
                $attach_by_file[$filename] = -1; // marcador dry
            } else {
                $attach_id = wp_insert_attachment([
                    'guid'           => $url,
                    'post_mime_type' => wp_check_filetype($abs)['type'] ?: 'image/png',
                    'post_title'     => pathinfo($filename, PATHINFO_FILENAME),
                    'post_content'   => '',
                    'post_status'    => 'inherit',
                ], $abs);
                if (is_wp_error($attach_id) || !$attach_id) {
                    error_log("[import_avatars] insert FAIL para $filename: " . (is_wp_error($attach_id) ? $attach_id->get_error_message() : 'unknown'));
                    continue;
                }
                $meta = wp_generate_attachment_metadata($attach_id, $abs);
                wp_update_attachment_metadata($attach_id, $meta);
                $attach_by_file[$filename] = $attach_id;
                $stats['ok']++;
            }
        }
    }

    $attach_id = $attach_by_file[$filename];
    if ($attach_id !== 0) {
        if (!$dry && $attach_id > 0) update_user_meta($aid, 'foto_perfil', (string) $attach_id);
        $stats['assigned']++;
        if (count($samples_ok) < 5) {
            $samples_ok[] = "user $aid ($login) → attach " . ($attach_id > 0 ? $attach_id : 'NEW') . " ($filename)";
        }
    }
}

echo ($dry ? '[DRY] ' : '') . "Stats:\n";
foreach ($stats as $k => $v) echo "  $k: $v\n";
echo "\nSamples:\n";
foreach ($samples_ok as $s) echo "  $s\n";
