$httpdPath = "C:\laragon\bin\apache\httpd-2.4.54-win64-VS16\conf\httpd.conf"
$erpVhostPath = "C:\laragon\etc\apache2\sites-enabled\erp.almanara.serveirc.com.conf"

# 1. Enable Proxy Modules in httpd.conf
try {
    $httpdContent = Get-Content -Path $httpdPath -Raw
    $modified = $false
    
    if ($httpdContent -match "#LoadModule proxy_module") {
        $httpdContent = $httpdContent -replace "#LoadModule proxy_module", "LoadModule proxy_module"
        $modified = $true
        Write-Host "Enabled proxy_module"
    }
    if ($httpdContent -match "#LoadModule proxy_http_module") {
        $httpdContent = $httpdContent -replace "#LoadModule proxy_http_module", "LoadModule proxy_http_module"
        $modified = $true
        Write-Host "Enabled proxy_http_module"
    }
    
    if ($modified) {
        Set-Content -Path $httpdPath -Value $httpdContent -Encoding UTF8
        Write-Host "Updated httpd.conf"
    } else {
        Write-Host "Proxy modules already enabled or not found commented out."
    }
} catch {
    Write-Error "Failed to update httpd.conf: $_"
}

# 2. Create VHost file for ERPNext Subdomain
$vhostContent = @"
<VirtualHost *:8333>
    ServerName erp.almanara.serveirc.com
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8091/
    ProxyPassReverse / http://127.0.0.1:8091/
</VirtualHost>

<VirtualHost *:443>
    ServerName erp.almanara.serveirc.com
    SSLEngine on
    SSLCertificateFile "C:/laragon/etc/ssl/almanara_serveirc_com.pem"
    SSLCertificateKeyFile "C:/laragon/etc/ssl/private.key"
    
    ProxyPreserveHost On
    RequestHeader set X-Forwarded-Proto https
    ProxyPass / http://127.0.0.1:8091/
    ProxyPassReverse / http://127.0.0.1:8091/
</VirtualHost>
"@

try {
    Set-Content -Path $erpVhostPath -Value $vhostContent -Encoding UTF8
    Write-Host "Created $erpVhostPath"
} catch {
    Write-Error "Failed to create vhost file: $_"
}

# 3. Restart Apache
try {
    & "C:\laragon\bin\apache\httpd-2.4.54-win64-VS16\bin\httpd.exe" -k restart
    Write-Host "Apache restarted"
} catch {
    Write-Error "Failed to restart Apache: $_"
}
