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

# 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
# We use Start-Process to run mysqld in the background
$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

Write-Host "      Waiting for MySQL to initialize..."
Start-Sleep -Seconds 10

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
    Write-Host "[3/5] Fixing authentication..." -ForegroundColor Yellow
    
    if (Test-Path "fix_auth_safemode.php") {
        php fix_auth_safemode.php
    } else {
        Write-Host "  ✗ fix_auth_safemode.php not found!" -ForegroundColor Red
    }
    
} else {
    Write-Host "  ✗ Failed to start MySQL in safe mode" -ForegroundColor Red
    # Try to see if it's already running under another PID
    $proc = Get-Process -Name "mysqld" -ErrorAction SilentlyContinue
    if ($proc) {
         Write-Host "  ⚠ MySQL is running with PID $($proc.Id). Attempting fix anyway..." -ForegroundColor Yellow
         php fix_auth_safemode.php
    }
}

# Step 4: Stop safe mode
Write-Host "[4/5] Stopping safe mode..." -ForegroundColor Yellow
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
