param (
    [switch]$DevTesting,    # optional flag; present = \$true, absent = \$false

    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()] 
    [string]$OutputDir
)


$esc = [char]27

# URL of the file to interact with
$url = "https://new.anvil.nz/dir/CustomerInfo.csv"
$templatePath = Join-Path $PSScriptRoot "template.xml"

function authenticate($defaultUser) {
    Write-Host "Please authenticate using the credentials popup to continue"
    $authenticationResult = $null; #Clear out any previous runs
    $authenticationResult = $host.UI.PromptForCredential("Server Authentication: anvil.nz", "Please enter your username and password for anvil.nz:", "$defaultUser", "")
    if ($null -eq $authenticationResult) {
        Write-Host "Authentication Failed/Cancelled"
        exit 1
    } 
    return $authenticationResult
}

if (-not (Test-Path -Path $templatePath)) {
    Write-Error "XML template not found: $templatePath"
    exit 1
}

Write-Debug "Current PS Root: $PSScriptRoot"



# Use Invoke-WebRequest to download the file with basic auth
$cred = authenticate "spark"
$response = Invoke-WebRequest -Uri $url -Credential $cred
$csv = $response.Content | ConvertFrom-Csv

if ($null -eq $csv -or $csv.Count -eq 0) {
    Write-Error "No rows returned from CSV."
    exit 1
}


Write-Host "`n     $esc[7m     Available rows:      $esc[0m"
for ($i = 0; $i -lt $csv.Count; $i++) {
    $row = $csv[$i]
    Write-Host "            [$($i + 1)] - $($row.EMAIL)"
}

$choice = Read-Host "`n     Enter the number of the record to use, or 0 to cancel"

if ($choice -eq '0') {
    Write-Host "Selection cancelled."
    exit 1
}

if (-not ($choice -as [int]) -or $choice -lt 1 -or $choice -gt $csv.Count) {
    Write-Error "Invalid selection."
    exit 1
}

$target = $csv[[int]$choice - 1]

[xml]$xmlTemplate = Get-Content -Path $templatePath

$xmlTemplate.SkypeSettings.UserAccount.SkypeSignInAddress = $target.EMAIL
$xmlTemplate.SkypeSettings.UserAccount.Password = $target.PASSWORD
$xmlTemplate.SkypeSettings.DualScreenMode = $target.DUALSCREEN.ToLower()
$xmlTemplate.SkypeSettings.SendLogs.SendLogsAndFeedback = $target.SENDLOGS.ToLower()
$xmlTemplate.SkypeSettings.BluetoothAdvertisementEnabled = $target.BLUBEACON.ToLower()
$xmlTemplate.SkypeSettings.AutoAcceptProximateMeetingInvitations = $target.BLUACCEPT.ToLower()
# $xmlTemplate.SkypeSettings.WebExMeetingsEnabled = $target.CISCO.ToLower()
# $xmlTemplate.SkypeSettings.ZoomMeetingsEnabled = $target.ZOOM.ToLower()
# $xmlTemplate.SkypeSettings.BlueJeansMeetingsEnabled = $target.BJEANS.ToLower()

$outputPath = Join-Path $OutputDir "SkypeSettings.xml"
$xmlTemplate.Save($outputPath)

if (-not $DevTesting) {
    if ($target.HOSTNAME) {
        Rename-Computer -NewName $target.HOSTNAME #-Force -ErrorAction SilentlyContinue
    }

    if ($target.ADMINPW) {
        $securePassword = ConvertTo-SecureString $target.ADMINPW -AsPlainText -Force
        $userAccount = Get-LocalUser -Name "admin" -ErrorAction SilentlyContinue
        if ($null -ne $userAccount) {
            $userAccount | Set-LocalUser -Password $securePassword
        }
    }
}
Clear-Host
Write-Output "`n`n
          XML Generated with account: $esc[7m $($target.EMAIL) $esc[0m.
          Please restart the Teams Room System to apply.`n`n"