$ErrorActionPreference = "Continue"
$workspace = "c:\xampp\htdocs\yt1"
$publicDir = Join-Path $workspace "public"

Write-Host "Updating includes paths in public/*.php"
$topLevelFiles = Get-ChildItem -Path $publicDir -Filter "*.php" -File
foreach ($file in $topLevelFiles) {
    try {
        $content = Get-Content $file.FullName -Raw
        $newContent = $content -replace "__DIR__ \. '/includes/", "__DIR__ . '/../includes/"
        if ($content -cne $newContent) {
            Set-Content -Path $file.FullName -Value $newContent -NoNewline
            Write-Host "Updated includes in public/$($file.Name)"
        }
    } catch {
        Write-Host "Failed to update public/$($file.Name): $($_.Exception.Message)"
    }
}

Write-Host "Updating includes paths in public/admin/*.php and public/api/*.php"
$subDirs = @("admin", "api")
foreach ($subDir in $subDirs) {
    $subDirPath = Join-Path $publicDir $subDir
    if (Test-Path $subDirPath) {
        $subFiles = Get-ChildItem -Path $subDirPath -Filter "*.php" -File
        foreach ($file in $subFiles) {
            try {
                $content = Get-Content $file.FullName -Raw
                $newContent = $content -replace "__DIR__ \. '/\.\./includes/", "__DIR__ . '/../../includes/"
                if ($content -cne $newContent) {
                    Set-Content -Path $file.FullName -Value $newContent -NoNewline
                    Write-Host "Updated includes in public/$subDir/$($file.Name)"
                }
            } catch {
                Write-Host "Failed to update public/$subDir/$($file.Name): $($_.Exception.Message)"
            }
        }
    }
}

Write-Host "Creating root .htaccess..."
$rootHtaccess = @"
RewriteEngine on
# Do not rewrite if the request is already for public/
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ public/`$1 [L,NC]
"@
Set-Content -Path (Join-Path $workspace ".htaccess") -Value $rootHtaccess

Write-Host "Migration part 2 complete!"
