# PowerShell script to fix MySQL authentication plugin issue
Write-Host "=== MySQL Authentication Plugin Fix ===" -ForegroundColor Cyan
Write-Host ""

# Step 1: Stop MySQL
Write-Host "[1/5] Stopping MySQL..." -ForegroundColor Yellow
Stop-Process -Name "mysqld" -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3

# Step 2: Start MySQL in safe mode with native password plugin
Write-Host "[2/5] Starting MySQL in safe mode..." -ForegroundColor Yellow
$safeMode = Start-Process -FilePath "C:\xampp\mysql\bin\mysqld.exe" `
    -ArgumentList "--skip-grant-tables", "--skip-networking", "--default-authentication-plugin=mysql_native_password" `
    -PassThru -WindowStyle Hidden

Start-Sleep -Seconds 8

if (Get-Process -Id $safeMode.Id -ErrorAction SilentlyContinue) {
    Write-Host "  ✓ MySQL started in safe mode (PID: $($safeMode.Id))" -ForegroundColor Green
    
    # Step 3: Fix authentication using PHP (since mysql.exe has plugin issues)
    Write-Host "[3/5] Fixing authentication..." -ForegroundColor Yellow
    
    $fixScript = @"
<?php
try {
    `$pdo = new PDO('mysql:host=127.0.0.1;port=3306', 'root', '');
    `$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "  ✓ Connected to MySQL\n";
    
    `$pdo->exec("FLUSH PRIVILEGES");
    echo "  ✓ Flushed privileges\n";
    
    `$pdo->exec("ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ''");
    echo "  ✓ Updated root@localhost\n";
    
    `$pdo->exec("ALTER USER 'root'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY ''");
    echo "  ✓ Updated root@127.0.0.1\n";
    
    `$pdo->exec("FLUSH PRIVILEGES");
    echo "  ✓ Applied changes\n";
    
    exit(0);
} catch (PDOException `$e) {
    echo "  ✗ Error: " . `$e->getMessage() . "\n";
    exit(1);
}
"@
    
    $fixScript | Out-File -FilePath "fix_auth_temp.php" -Encoding UTF8
    php fix_auth_temp.php
    Remove-Item "fix_auth_temp.php" -ErrorAction SilentlyContinue
    
} else {
    Write-Host "  ✗ Failed to start MySQL in safe mode" -ForegroundColor Red
}

# Step 4: Stop safe mode
Write-Host "[4/5] Stopping safe mode..." -ForegroundColor Yellow
Stop-Process -Id $safeMode.Id -Force -ErrorAction SilentlyContinue
Stop-Process -Name "mysqld" -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3

# Step 5: Start MySQL normally
Write-Host "[5/5] Starting MySQL normally..." -ForegroundColor Yellow
Start-Process -FilePath "C:\xampp\mysql\bin\mysqld.exe" -WindowStyle Hidden
Start-Sleep -Seconds 5

# Test connection
Write-Host ""
Write-Host "=== Testing Connection ===" -ForegroundColor Cyan
php test_blank_password.php

Write-Host ""
Write-Host "=== Done ===" -ForegroundColor Cyan
