
# Get all PHP files
$files = Get-ChildItem -Path "d:\ab_erp_wrex" -Recurse -Filter *.php

foreach ($file in $files) {
    $content = Get-Content $file.FullName -Raw
    
    # Backup original (optional but good for safety, loop might be slow if many files)
    # Copy-Item $file.FullName "$($file.FullName).bak"
    
    # 1. mysql_query($sql, $conn) -> $conn->query($sql)
    # Using generic variable capture
    $content = $content -replace 'mysql_query\s*\(\s*(.+?)\s*,\s*\$([a-zA-Z0-9_]+)\s*\)', '$$$2->query($1)'
    
    # 2. mysql_query($sql) -> $dbinv->query($sql)
    # Assumes implicit connection is $dbinv
    $content = $content -replace 'mysql_query\s*\(\s*(.+?)\s*\)', '$dbinv->query($1)'
    
    # 3. mysql_fetch_array($res) -> $res->fetch()
    $content = $content -replace 'mysql_fetch_array\s*\(\s*\$([a-zA-Z0-9_]+)\s*\)', '$$$1->fetch()'
    
    # 4. mysql_num_rows($res) -> $res->rowCount()
    $content = $content -replace 'mysql_num_rows\s*\(\s*\$([a-zA-Z0-9_]+)\s*\)', '$$$1->rowCount()'
    
    # 5. mysql_insert_id($conn) -> $conn->lastInsertId()
    $content = $content -replace 'mysql_insert_id\s*\(\s*\$([a-zA-Z0-9_]+)\s*\)', '$$$1->lastInsertId()'
    
    # 6. mysql_insert_id() -> $dbinv->lastInsertId()
    $content = $content -replace 'mysql_insert_id\s*\(\s*\)', '$dbinv->lastInsertId()'
    
    # 7. mysql_close -> comment out
    $content = $content -replace 'mysql_close\s*\(.*\)', '// connection closed'
    
    # 8. mysql_select_db -> comment out
    $content = $content -replace 'mysql_select_db\s*\(.*\)', '// database selection removed'
    
    # 9. mysql_error -> comment out
    $content = $content -replace 'mysql_error\s*\(.*\)', '"Error"' 
    # Replacing with string "Error" to avoid syntax errors in concatenation like "Error: ".mysql_error()
    
    # 10. CLEANUP: or die(...) 
    # This is tricky regex. matches "or die(...)" where ... can contain anything (balanced parens is hard in regex).
    # Simple approach: remove "or die(mysql_error())" specifically
    $content = $content -replace 'or\s*die\s*\(\s*mysql_error\s*\(\s*\)\s*\)', ''
    $content = $content -replace 'or\s*die\s*\(\s*\$dbinv->error\s*\)', ''

    Set-Content $file.FullName $content
}

Write-Host "Global Refactor Complete"
