<?php

require_once __DIR__ . '/../src/Utils/Env.php';
require_once __DIR__ . '/../src/Config/Database.php';

use App\Utils\Env;
use App\Config\Database;

// Load Env
Env::load(__DIR__ . '/../../.env');

echo "Starting Character Set Fix...\n";
echo "<pre>";

try {
    $db = Database::getInstance()->getConnection();
    $dbName = Env::get('DB_NAME', 'messrypt_nons');

    // 1. Fix Database Default
    echo "1. Altering Database Default Charset...\n";
    $db->exec("ALTER DATABASE `$dbName` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci");
    echo "   OK.\n";

    // 2. Fix Tables
    $tables = [
        'users',
        'stories',
        'story_comments',
        'messages',
        'conversations',
        'anonymous_sessions',
        'blocked_users',
        'reports',
        'device_players'
    ];

    foreach ($tables as $table) {
        echo "2. Fixing Table '$table'...\n";
        try {
            $db->exec("ALTER TABLE `$table` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            echo "   OK.\n";
        } catch (PDOException $e) {
            echo "   ERROR: " . $e->getMessage() . "\n";
        }
    }

    echo "\nSUCCESS: All operations completed.\n";
    echo "Please delete this file after execution for security.\n";

} catch (Exception $e) {
    echo "FATAL ERROR: " . $e->getMessage() . "\n";
}

echo "</pre>";
