<?php
/**
 * Attach Agent Images
 *
 * Run with: wp --allow-root eval-file attach-images.php
 */

$images_dir = dirname(__FILE__) . '/images';

// Map image filenames to agent names
$agent_images = [
    'anna.webp' => 'Anna Rahn',
    'davy.webp' => 'Davy Villarreal',
    'jordan.webp' => 'Jordan Mullenbach',
    'lily.webp' => 'Lily Dulitz',
];

echo "Attaching agent images...\n\n";

foreach ($agent_images as $filename => $agent_name) {
    $image_path = $images_dir . '/' . $filename;

    if (!file_exists($image_path)) {
        echo "Image not found: $filename\n";
        continue;
    }

    // Find the agent post
    $agents = get_posts([
        'post_type' => 'agent',
        'title' => $agent_name,
        'post_status' => 'publish',
        'numberposts' => 1,
    ]);

    if (empty($agents)) {
        echo "Agent not found: $agent_name\n";
        continue;
    }

    $agent_id = $agents[0]->ID;
    echo "Processing: $agent_name (ID: $agent_id)\n";

    // Check if already has featured image
    if (has_post_thumbnail($agent_id)) {
        echo "  - Already has featured image, skipping...\n\n";
        continue;
    }

    // Copy to temp location
    $tmp_path = '/tmp/' . $filename;
    copy($image_path, $tmp_path);

    $file_array = [
        'name' => $filename,
        'tmp_name' => $tmp_path,
    ];

    // Upload the image
    $attachment_id = media_handle_sideload($file_array, $agent_id);

    if (is_wp_error($attachment_id)) {
        echo "  - ERROR uploading: " . $attachment_id->get_error_message() . "\n\n";
        continue;
    }

    // Set as featured image
    set_post_thumbnail($agent_id, $attachment_id);

    echo "  - Uploaded and set as featured image (Attachment ID: $attachment_id)\n";
    echo "  - DONE\n\n";
}

echo "Complete!\n";
