<?php
// PHP script to fix MySQL authentication in safe mode
echo "=== MySQL Authentication Fix ===\n\n";

try {
    // Connect to MySQL (should work in safe mode with --skip-grant-tables)
    $pdo = new PDO('mysql:host=127.0.0.1;port=3306', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "[1/5] ✓ Connected to MySQL in safe mode\n";
    
    // Flush privileges to enable privilege system
    $pdo->exec("FLUSH PRIVILEGES");
    echo "[2/5] ✓ Flushed privileges\n";
    
    // Change authentication plugin to mysql_native_password with empty password
    $pdo->exec("ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ''");
    echo "[3/5] ✓ Updated root@localhost to use mysql_native_password\n";
    
    $pdo->exec("ALTER USER 'root'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY ''");
    echo "[4/5] ✓ Updated root@127.0.0.1 to use mysql_native_password\n";
    
    // Apply changes
    $pdo->exec("FLUSH PRIVILEGES");
    echo "[5/5] ✓ Applied all changes\n";
    
    echo "\n✓✓✓ SUCCESS! MySQL authentication has been fixed.\n";
    echo "Now restart MySQL normally and test the connection.\n";
    
} catch (PDOException $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
    echo "\nThis script must be run while MySQL is in safe mode.\n";
    echo "Start MySQL with: mysqld --skip-grant-tables --skip-networking\n";
    exit(1);
}
