$ErrorActionPreference = "Stop"

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

Write-Host "Creating public/ directory..."
if (-not (Test-Path $publicDir)) {
    New-Item -ItemType Directory -Path $publicDir | Out-Null
}

Write-Host "Moving directories..."
$dirsToMove = @("admin", "api", "assets", "uploads")
foreach ($dir in $dirsToMove) {
    $src = Join-Path $workspace $dir
    if (Test-Path $src) {
        Move-Item -Path $src -Destination $publicDir
        Write-Host "Moved $dir to public/"
    }
}

Write-Host "Moving files..."
if (Test-Path (Join-Path $workspace ".htaccess")) {
    Move-Item -Path (Join-Path $workspace ".htaccess") -Destination $publicDir
}

$filesToMove = Get-ChildItem -Path $workspace -Filter "*.php" -File | Where-Object { $_.Name -ne "cron_backup.php" }
foreach ($file in $filesToMove) {
    Move-Item -Path $file.FullName -Destination $publicDir
    Write-Host "Moved $($file.Name) to public/"
}

Write-Host "Updating includes paths in public/*.php"
$topLevelFiles = Get-ChildItem -Path $publicDir -Filter "*.php" -File
foreach ($file in $topLevelFiles) {
    $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)"
    }
}

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) {
            $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)"
            }
        }
    }
}

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 complete!"
