<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$db = getDB();
try {
    $db->exec("ALTER TABLE users MODIFY avatar MEDIUMTEXT");
    echo "Column type updated to MEDIUMTEXT.<br>";
} catch (\Exception $e) {
    echo "Error updating column type: " . $e->getMessage() . "<br>";
}

$users = getAllUsers();
$updated = 0;

foreach ($users as $user) {
    if (empty($user['avatar']) || strlen($user['avatar']) < 2000 || strpos(base64_decode(substr($user['avatar'], 22)), '<html') !== false) {
        $hash = md5(strtolower(trim($user['email'])));
        $monsterUrl = "https://www.gravatar.com/avatar/{$hash}?d=monsterid&s=150";
        
        $ctx = stream_context_create([
            'http' => [
                'timeout' => 5,
                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"
            ]
        ]);
        $imgData = @file_get_contents($monsterUrl, false, $ctx);
        if ($imgData !== false && strlen($imgData) > 500) {
            $user['avatar'] = 'data:image/png;base64,' . base64_encode($imgData);
            saveUser($user);
            $updated++;
            echo "Updated avatar for: " . htmlspecialchars($user['email']) . "<br>";
        }
    }
}

echo "Migration complete. Updated $updated users.";
