<?php
require_once __DIR__ . '/../config/database.php';

try {
    $db = getDB();

    // Get all researchers without profile pictures
    $stmt = $db->prepare("
        SELECT u.id, u.first_name, u.last_name, rp.photo
        FROM users u
        JOIN researcher_profiles rp ON u.id = rp.user_id
        WHERE u.role_id = (SELECT id FROM roles WHERE name = 'researcher' LIMIT 1)
        AND (rp.photo IS NULL OR rp.photo = '')
    ");
    $stmt->execute();
    $researchers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "Found " . count($researchers) . " researchers without profile pictures\n";

    $uploadsDir = __DIR__ . '/../assets/uploads/profile_pictures/';
    if (!is_dir($uploadsDir)) {
        mkdir($uploadsDir, 0755, true);
    }

    $updated = 0;
    foreach ($researchers as $index => $researcher) {
        $imageId = $researcher['id']; // Use user ID for unique image
        $imageUrl = "https://picsum.photos/300/300?random={$imageId}";
        $imagePath = $uploadsDir . "researcher_{$imageId}.jpg";

        $imageData = file_get_contents($imageUrl);
        if ($imageData !== false) {
            $bytesWritten = file_put_contents($imagePath, $imageData);
            if ($bytesWritten !== false && $bytesWritten > 0) {
                $photoPath = "assets/uploads/profile_pictures/researcher_{$imageId}.jpg";

                // Update the database
                $updateStmt = $db->prepare("UPDATE researcher_profiles SET photo = ? WHERE user_id = ?");
                $updateStmt->execute([$photoPath, $researcher['id']]);

                $updated++;
                echo "✓ Updated profile picture for {$researcher['first_name']} {$researcher['last_name']}\n";
            }
        }
    }

    echo "\nUpdated $updated profile pictures\n";

} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}
?>