
# 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
    
    # Replace assignment
    # Using specific variable name $db to avoid messing up other instantiations if any (e.g. $db2)
    # But majority uses $db based on grep
    if ($content -match '\$db\s*=\s*new\s*DBConnector\(\)\s*;') {
        $content = $content -replace '(\$db\s*=\s*new\s*DBConnector\(\)\s*;)', '$1 $dbinv = $db->GetConnection();'
        
        # Deduplicate if already present
        $content = $content -replace '(\$dbinv\s*=\s*\$db->GetConnection\(\);\s*){2,}', '$dbinv = $db->GetConnection();'
        
        Set-Content $file.FullName $content
        Write-Host "Patched $($file.Name)"
    }
}

Write-Host "DBInst Refactor Complete"
