# Convert tất cả .doc trong FORM/ sang .docx qua Word COM automation.
# Yêu cầu: Microsoft Word đã cài trên máy.
# Usage: .\scripts\convert-doc-to-docx.ps1

$ErrorActionPreference = 'Stop'

$src = 'D:\Dropbox\CONG_VIEC\SOLUTION\FORM'
$out = Join-Path $PSScriptRoot '..\src\Backend\SolutionErp.Api\wwwroot\templates'

if (-not (Test-Path $out)) { New-Item -ItemType Directory -Force -Path $out | Out-Null }

$docs = Get-ChildItem -Path $src -Filter '*.doc' -File
if ($docs.Count -eq 0) {
    Write-Host "Khong co file .doc can convert."
    exit 0
}

Write-Host "Opening Word COM..."
$word = $null
try {
    $word = New-Object -ComObject Word.Application
} catch {
    Write-Error "Microsoft Word chua cai. Cai Word hoac dung LibreOffice fallback."
    exit 1
}
$word.Visible = $false
$word.DisplayAlerts = 0

foreach ($f in $docs) {
    $inPath = $f.FullName
    $outPath = Join-Path $out ($f.BaseName + '.docx')

    Write-Host "Convert: $($f.Name) -> $(Split-Path $outPath -Leaf)"
    $doc = $word.Documents.Open($inPath, $false, $true)
    # 16 = wdFormatDocumentDefault (.docx)
    $doc.SaveAs2($outPath, 16)
    $doc.Close($false)
}

$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[System.GC]::Collect()

Write-Host "Done. Output: $out"
