param(
    [string]$paramUccName,
    [string]$paramUccTitle,
    [string]$paramLanguage,
    [string]$paramCdrConnectionString,
    [string]$paramSiteCollectionUrl,
    [string]$paramSiteCollectionTitle,
    [string]$paramSiteOwner,
    [string]$paramCertificateAppId,
    [string]$paramCertificateTenantId,
    [string]$paramCertificatePath,
    [System.Security.SecureString]$paramCertificatePassword,
    [string]$paramInteractiveClientId,
    [switch]$paramReconnectLookupColumns,
    [switch]$resetTemplateFlag,
    [switch]$skipSiteCollectionSetup,
    [switch]$UseSubSites,
    [switch]$UseSiteCollectionAppCatalog,
    [switch]$SiteCollectionPreCreated,
    [switch]$interactive,
    [switch]$restartPowerShell,
    [switch]$ignoreRestartPowerShell
)

# Check PowerShell version - PnP.PowerShell 3.x requires PowerShell 7.4.6+
if ($PSVersionTable.PSVersion.Major -lt 7 -or 
    ($PSVersionTable.PSVersion.Major -eq 7 -and $PSVersionTable.PSVersion.Minor -lt 4)) {
    Write-Host ""
    Write-Host "ERROR: This script requires PowerShell 7.4.6 or higher." -ForegroundColor Red
    Write-Host "You are running: PowerShell $($PSVersionTable.PSVersion)" -ForegroundColor Red
    Write-Host ""
    Write-Host "Windows PowerShell 5.1 is not supported by PnP.PowerShell 3.x" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Please install PowerShell 7:" -ForegroundColor Cyan
    Write-Host "  https://aka.ms/PSWindows" -ForegroundColor White
    Write-Host ""
    Write-Host "Or run: winget install Microsoft.PowerShell" -ForegroundColor White
    Write-Host ""
    exit 1
}


# Script version
$ScriptVersion = "8.4.1.8"
# Validate authentication parameters early
# Note: As of September 9th 2024, the PnP Management Shell multi-tenant app has been deleted.
#       You must register your own Entra ID Application and provide the ClientId.
#       See: https://pnp.github.io/powershell/articles/registerapplication.html
if ($interactive -and -not $paramInteractiveClientId) {
    Write-Host "Error: paramInteractiveClientId is required for interactive authentication." -ForegroundColor Red
    Write-Host ""
    Write-Host "The PnP Management Shell multi-tenant app was deleted on September 9th, 2024." -ForegroundColor Red
    Write-Host "You must register your own Entra ID Application and provide the -paramInteractiveClientId parameter." -ForegroundColor Red
    Write-Host ""
    Write-Host "See: https://pnp.github.io/powershell/articles/registerapplication.html" -ForegroundColor Yellow
    exit 1
}

# Prompt for certificate password if using certificate auth and password not provided
if ($paramCertificatePath -and -not $interactive) {
    if ($null -eq $paramCertificatePassword) {
        Write-Host ""
        $paramCertificatePassword = Read-Host -Prompt "Enter certificate password" -AsSecureString
        Write-Host ""
    }
}

# Store the script's directory for reliable path resolution
$ScriptDir = $PSScriptRoot
if ([string]::IsNullOrEmpty($ScriptDir)) {
    $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
}
if ([string]::IsNullOrEmpty($ScriptDir)) {
    $ScriptDir = Get-Location
}

# CRITICAL: Pre-convert certificate password IMMEDIATELY, before ANYTHING else loads
# This must happen before any module imports to avoid ALC conflicts with PnP.PowerShell
if ($paramCertificatePassword -eq $null -and $global:certificatePasswordSecureConverted -ne $true) {
    $configPath = Join-Path $ScriptDir "configuration.xml"
    if (Test-Path $configPath) {
        try {
            $configXml = [xml](Get-Content -Path $configPath -Raw -Encoding UTF8)
            $certPwd = $configXml.Configuration.CertificatePassword
            $encrypted = $configXml.Configuration.CertificatePassword.encrypted
            if ($encrypted -ne $null) {
                $certPwd = $configXml.Configuration.CertificatePassword.InnerText
            }
            if (![string]::IsNullOrEmpty($certPwd)) {
                $certPwd = $certPwd.Trim()
                if ($encrypted -ne $null -and $encrypted.ToLower() -eq "true") {
                    $global:certificatePasswordSecureFromConfig = ConvertTo-SecureString -String $certPwd -Force
                } else {
                    $global:certificatePasswordSecureFromConfig = ConvertTo-SecureString -String $certPwd -AsPlainText -Force
                }
            }
            $global:certificatePasswordSecureConverted = $true
        } catch {
            Write-Host "Warning: Could not pre-convert certificate password: $($_.Exception.Message)" -ForegroundColor Yellow
            $global:certificatePasswordSecureConverted = $true
        }
    }
}

# Refresh PowerShell context - restarts PowerShell to clear any cached modules/variables
# SKIP restart if SecureString password is provided OR if we successfully converted from config.xml
# (Restarting loses the converted SecureString and causes ALC conflicts in the new process)
$skipRestart = ($paramCertificatePassword -ne $null) -or ($global:certificatePasswordSecureFromConfig -ne $null)
if ($restartPowerShell -eq $false -and $ignoreRestartPowerShell -eq $false -and $skipRestart -eq $false) 
{
    Write-Host "Refreshing PowerShell context" -ForegroundColor Yellow
    # Build arguments array - much safer than string concatenation
    $scriptPath = Join-Path $ScriptDir "UCC.Site.Creator.ps1"
    $arguments = @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $scriptPath, "-RestartPowerShell")
    if (![string]::IsNullOrEmpty($paramUccName)) {
        $arguments += "-ParamUccName"
        $arguments += $paramUccName
    }
    if (![string]::IsNullOrEmpty($paramUccTitle)) {
        $arguments += "-ParamUccTitle"
        $arguments += $paramUccTitle
    }
    if (![string]::IsNullOrEmpty($paramLanguage)) {
        $arguments += "-ParamLanguage"
        $arguments += $paramLanguage
    }
    if (![string]::IsNullOrEmpty($paramCdrConnectionString)) {
        $arguments += "-ParamCdrConnectionString"
        $arguments += $paramCdrConnectionString
    }
    if (![string]::IsNullOrEmpty($paramSiteCollectionUrl)) {
        $arguments += "-ParamSiteCollectionUrl"
        $arguments += $paramSiteCollectionUrl
    }
    if (![string]::IsNullOrEmpty($paramSiteCollectionTitle)) {
        $arguments += "-ParamSiteCollectionTitle"
        $arguments += $paramSiteCollectionTitle
    }
    if ($paramReconnectLookupColumns) {
        $arguments += "-ParamReconnectLookupColumns"
    }
    if (![string]::IsNullOrEmpty($paramCertificateAppId)) {
        $arguments += "-ParamCertificateAppId"
        $arguments += $paramCertificateAppId
    }
    if (![string]::IsNullOrEmpty($paramCertificateTenantId)) {
        $arguments += "-ParamCertificateTenantId"
        $arguments += $paramCertificateTenantId
    }
    if (![string]::IsNullOrEmpty($paramCertificatePath)) {
        $arguments += "-ParamCertificatePath"
        $arguments += $paramCertificatePath
    }
    if (![string]::IsNullOrEmpty($paramInteractiveClientId)) {
        $arguments += "-ParamInteractiveClientId"
        $arguments += $paramInteractiveClientId
    }
    if ($resetTemplateFlag) {
        $arguments += "-ResetTemplateFlag"
    }
    if ($skipSiteCollectionSetup) {
        $arguments += "-SkipSiteCollectionSetup"
    }
    if ($UseSubSites) {
        $arguments += "-UseSubSites"
    }
    if ($UseSiteCollectionAppCatalog) {
        $arguments += "-UseSiteCollectionAppCatalog"
    }
    if ($SiteCollectionPreCreated) {
        $arguments += "-SiteCollectionPreCreated"
    }
    if ($skipSpfxDeploy) {
        $arguments += "-SkipSpfxDeploy"
    }
    if ($interactive) {
        $arguments += "-Interactive"
    }
    # Use Start-Process with argument array - properly handles spaces in values
    Start-Process -FilePath "powershell.exe" -ArgumentList $arguments -NoNewWindow -Wait -WorkingDirectory $ScriptDir
    return
}
else 
{
    # Always use modern mode (no Custom Script operations)
    # Classic webpart form customizations are deprecated per MC1117115
    $global:SkipCustomScriptOperations = $true
    # Make certificate parameters available to child scripts (Shared.ps1 checks for these)
    # Using global scope because dot-sourced scripts need access to these
    $global:paramCertificatePassword = $paramCertificatePassword
    $global:paramCertificateAppId = $paramCertificateAppId
    $global:paramCertificateTenantId = $paramCertificateTenantId
    $global:paramCertificatePath = $paramCertificatePath
    $global:paramSiteOwner = $paramSiteOwner
    # Expose UseSubSites switch so Shared.ps1 can apply it (parameter takes precedence over config.xml)
    if ($UseSubSites) {
        $global:paramUseSubSites = $true
    }
    if ($UseSiteCollectionAppCatalog) {
        $global:paramUseSiteCollectionAppCatalog = $true
    }
    
    # Reset Shared.ps1 init guard so re-running in the same PS session re-initializes correctly
    $global:SharedInitialized = $false
    # Reset deployed site URL tracker so stale URLs from previous runs don't pollute the dashboard loop
    $global:deployedSiteUrls = @()
    # Load site collection setup script (contains EnsureSite and related functions)
    . $PSScriptRoot\AnywhereNow\Scripts\WSP.UCC-1.SiteCollection.ps1
    # Load site creator script (contains CreateSite and related functions)  
    . $PSScriptRoot\AnywhereNow\Scripts\WSP.UCC-2.SiteCreator.ps1
    # Check vars
    $checkVars = CheckEnvironmentalVariables
    if ($checkVars -eq $false) 
    {
        Warn "Required variables not set. Use -Interactive for browser-based login, or configure certificate authentication in configuration.xml"
        return
    }
    # Extract tenant admin URL from site collection URL for site creation
    $tenantAdminUrl = $null
    if ($scurl -match "https://([^.]+)\.sharepoint\.com")
    {
        $tenantName = $matches[1]
        $tenantAdminUrl = "https://$tenantName-admin.sharepoint.com"
    }
    # Step 0: Check if site collection exists, create if needed
    # Try to connect to the site collection and verify it exists
    $siteExists = $false
    Info "Checking if site collection exists: $scurl"
    try
    {
        $connected = Connect -Url $scurl
        if ($connected)
        {
            # Connection succeeded, but we need to verify the site actually exists
            # by trying to get the web object
            try
            {
                $web = Get-PnPWeb -ErrorAction Stop
                if ($web -ne $null)
                {
                    $siteExists = $true
                    Info "Site collection exists: $($web.Title)"
                }
            }
            catch
            {
                # Site doesn't exist or we can't access it
                $siteExists = $false
                Info "Site collection does not exist (verified)"
            }
            # Disconnect since we'll reconnect later
            try { Disconnect-PnPOnline -ErrorAction SilentlyContinue } catch {}
        }
    }
    catch
    {
        $siteExists = $false
    }
    if ($siteExists -eq $false)
    {
        if ($SiteCollectionPreCreated)
        {
            Error "Site collection not found: $scurl"
            Error "The -SiteCollectionPreCreated switch was specified, indicating the site should already exist."
            Error "Ensure the SharePoint Administrator has created the site collection and granted the app access to it before running this script."
            return
        }
        Info "Site collection does not exist. Creating..."
        if ($tenantAdminUrl -eq $null)
        {
            Error "Cannot determine tenant admin URL from site collection URL: $scurl"
            return
        }
        # Connect to tenant admin
        $adminConnected = Connect -Url $tenantAdminUrl -ShowError
        if ($adminConnected -eq $false)
        {
            Error "Cannot connect to SharePoint admin center: $tenantAdminUrl"
            Error "Ensure you have SharePoint Administrator or Global Administrator permissions."
            return
        }
        # Determine site title
        $siteTitle = $paramSiteCollectionTitle
        if ([string]::IsNullOrEmpty($siteTitle))
        {
            $siteTitle = "AnywhereNow UCC"
        }
        # Create the site collection as a Communication Site
        try
        {
            Info "Creating Communication Site: $scurl"
            Info "Title: $siteTitle"
            # Determine site owner - required for App-only authentication
            $siteOwner = $paramSiteOwner
            if ([string]::IsNullOrEmpty($siteOwner)) {
                $siteOwner = $global:paramSiteOwner
            }
            if ([string]::IsNullOrEmpty($siteOwner)) {
                $siteOwner = $configurationXML.Configuration.SiteOwner
            }
            # Create Communication Site
            if (![string]::IsNullOrEmpty($siteOwner)) {
                Info "Owner: $siteOwner"
                New-PnPSite -Type CommunicationSite -Title $siteTitle -Url $scurl -Owner $siteOwner -Wait
            } else {
                # Try without owner (works for interactive auth)
                New-PnPSite -Type CommunicationSite -Title $siteTitle -Url $scurl -Wait
            }
            Info "Site collection created successfully"
            # Wait a moment for provisioning to complete
            Start-Sleep -Seconds 5
        }
        catch
        {
            Error "Failed to create site collection: $($_.Exception.Message)"
            return
        }
        Disconnect-PnPOnline
    }
    # Connect to site collection
    $connected = Connect -Url $scurl -ShowError
    if ($connected -eq $false) 
    {
        Warn "Cannot connect to sitecollection $scurl"
        return
    }
    # Info about modern mode - Custom Script is no longer required
    # per MC1117115 deprecation (March 2026)
    Info "Using modern SPFx components (MC1117115 compliant)"
    Info "Classic webpart customizations are skipped - using modern SPFx components"
    # Step 1: Check if site collection setup is needed
    $assetsVersionList = GetPnPList "AssetsVersion"
    if ($assetsVersionList -eq $null -and $skipSiteCollectionSetup -eq $false)
    {
        Info "Site collection not configured. Running site collection setup..."
        Info "Sitecollection creator started"
        Info "Connected to site collection $scurl"
        # Run site collection configuration
        ConfigureSiteCollection
        UccCreatorList
        AssetsVersionList
        AddClientSidePage
        ExecuteNewSiteCollectionUpdate
        Info "Site collection setup complete"
    }
    elseif ($skipSiteCollectionSetup)
    {
        Info "Skipping site collection setup (manual override)"
    }
    else
    {
        Info "Site collection already configured (AssetsVersion list exists)"
    }
    # Pre-load assets for Deploy-SiteDashboard
    $logoLocalPath = Join-Path $RootPath "AnywhereNow\Assets\AWN-Master-logo-Full-Colour-RGB.png"
    $schemaUpdatesPath = Join-Path $PSScriptRoot "SchemaUpdates.ps1"
    $script:schemaLoaded = $false
    if (Test-Path $schemaUpdatesPath)
    {
        try
        {
            . $schemaUpdatesPath
            $script:schemaLoaded = $true
        }
        catch { Warn "Could not pre-load SchemaUpdates.ps1: $($_.Exception.Message)" }
    }

    # =========================================================================
    # Deploy-SiteDashboard — configures Home.aspx, UCC Dashboard web part,
    # site logo, page comments, and schema updates for a single site.
    # Called once per site immediately after provisioning.
    # Based on Rhys's implementation with CanvasContent1 injection fallback
    # for STS#0 subsites where SPFx component propagation may be delayed.
    # =========================================================================
    function Deploy-SiteDashboard
    {
        param([Parameter(Mandatory=$true)][string]$SiteUrl)

        Info ""
        Info "Configuring UCC Dashboard home page for: $SiteUrl"
        try
        {
            $reconnected = Connect -Url $SiteUrl
            if (-not $reconnected)
            {
                Warn "Could not connect to site for home page configuration"
            }
            else
            {
                $homePage = $null
                $homePageRemoved = $false

                if ($useSubSites)
                {
                    # On STS#0 subsites the default Home.aspx is a wiki page.
                    # Remove-PnPPage only works for modern pages so we need a fallback.
                    # First create a temp page and set as homepage to unlock Home.aspx.
                    try
                    {
                        $tempPage = Add-PnPPage -Name "TempHomePage" -LayoutType Article -Title "Temporary" -Publish -ErrorAction SilentlyContinue
                        if ($tempPage)
                        {
                            Set-PnPHomePage -RootFolderRelativeUrl "SitePages/TempHomePage.aspx" -ErrorAction SilentlyContinue
                            Start-Sleep -Seconds 1
                        }
                    }
                    catch { }

                    try
                    {
                        Remove-PnPPage -Identity "Home" -Force -ErrorAction Stop
                        $homePageRemoved = $true
                    }
                    catch
                    {
                        try
                        {
                            $existingPage = Get-PnPListItem -List "SitePages" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Home.aspx</Value></Eq></Where></Query></View>" -ErrorAction SilentlyContinue
                            if ($existingPage)
                            {
                                Remove-PnPListItem -List "SitePages" -Identity $existingPage.Id -Force -Recycle -ErrorAction Stop | Out-Null
                                $homePageRemoved = $true
                            }
                            else { $homePageRemoved = $true }
                        }
                        catch { Warn "Could not remove existing Home.aspx: $($_.Exception.Message)" }
                    }

                    if (-not $homePageRemoved) { Warn "Home.aspx could not be removed — will attempt to update in place" }
                    Start-Sleep -Seconds 2
                }
                else
                {
                    try { $homePage = Get-PnPPage -Identity "Home" -ErrorAction SilentlyContinue } catch { }
                    if ($homePage -ne $null)
                    {
                        Info "Removing existing Home.aspx for fresh layout..."
                        try { Remove-PnPPage -Identity "Home" -Force -ErrorAction SilentlyContinue } catch { }
                        $homePage = $null
                    }
                }

                # Ensure SitePages feature is active (required for STS#0 subsites)
                try { Enable-PnPFeature -Identity "B6917CB1-93A0-4B97-A84D-7CF49975D4EC" -Scope Web -Force -ErrorAction SilentlyContinue } catch { }
                $sitePagesLib = $null
                try { $sitePagesLib = Get-PnPList -Identity "SitePages" -ErrorAction SilentlyContinue } catch { }
                if ($null -eq $sitePagesLib)
                {
                    try
                    {
                        $web = Get-PnPWeb; $ctx2 = Get-PnPContext
                        $features = $web.Features; $ctx2.Load($features); $ctx2.ExecuteQuery()
                        $features.Add([Guid]"B6917CB1-93A0-4B97-A84D-7CF49975D4EC", $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
                        $ctx2.ExecuteQuery()
                    }
                    catch { Warn "Could not activate SitePages feature: $($_.Exception.Message)" }
                }

                # Create Home.aspx
                Info "Creating Home.aspx..."
                $homePage = $null
                try { $homePage = Add-PnPPage -Name "Home" -LayoutType Home -Title "UCC Dashboard" -ErrorAction Stop }
                catch
                {
                    Info "LayoutType Home not supported — trying default layout..."
                    try { $homePage = Add-PnPPage -Name "Home" -Title "UCC Dashboard" -ErrorAction Stop }
                    catch { Warn "Could not create Home.aspx: $($_.Exception.Message)" }
                }

                $webPartAdded = $false
                if ($null -ne $homePage)
                {
                    Start-Sleep -Seconds 3

                    $componentName = "UCC Dashboard"
                    $componentId   = "12345678-1234-1234-1234-123456789abc"

                    # Wait for tenant-wide SPFx component to propagate to the new subsite
                    $componentAvailable = $false
                    if ($useSubSites)
                    {
                        $maxWaitSeconds = 120; $retryInterval = 15; $elapsed = 0
                        while ($elapsed -lt $maxWaitSeconds)
                        {
                            try
                            {
                                $available = Get-PnPPageComponent -Page $homePage -ListAvailable -ErrorAction Stop
                                $found = $available | Where-Object { $_.Name -eq $componentName -or $_.Id -eq $componentId }
                                if ($null -ne $found) { $componentAvailable = $true; Info "UCC Dashboard component available (${elapsed}s)"; break }
                            }
                            catch { }
                            $elapsed += $retryInterval
                            if ($elapsed -lt $maxWaitSeconds)
                            {
                                Info "Waiting for UCC Dashboard component propagation... (${elapsed}s / ${maxWaitSeconds}s)"
                                Start-Sleep -Seconds $retryInterval
                            }
                        }
                        if (-not $componentAvailable) { Warn "Component not found after ${maxWaitSeconds}s — falling back to direct injection" }
                    }
                    else { $componentAvailable = $true }

                    # PRIMARY: PnP Add-PnPPageWebPart
                    if ($componentAvailable)
                    {
                        try
                        {
                            Add-PnPPageSection -Page $homePage -SectionTemplate OneColumnFullWidth -Order 1 -ErrorAction Stop | Out-Null
                            Add-PnPPageWebPart -Page $homePage -Component $componentName -Section 1 -Column 1 -ErrorAction Stop | Out-Null
                            $webPartAdded = $true; Info "UCC Dashboard web part added (full-width)"
                        }
                        catch
                        {
                            try
                            {
                                Add-PnPPageWebPart -Page $homePage -Component $componentName -ErrorAction Stop | Out-Null
                                $webPartAdded = $true; Info "UCC Dashboard web part added"
                            }
                            catch { Warn "PnP web part addition failed: $($_.Exception.Message)" }
                        }
                    }

                    # FALLBACK: Direct CanvasContent1 JSON injection (subsites only)
                    if (-not $webPartAdded -and $useSubSites)
                    {
                        try
                        {
                            $pageItem = Get-PnPListItem -List "SitePages" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Home.aspx</Value></Eq></Where></Query></View>" -ErrorAction Stop
                            if ($null -ne $pageItem)
                            {
                                $instanceId = [Guid]::NewGuid().ToString()
                                $controlData = @{
                                    controlType = 3; id = $instanceId
                                    position = @{ zoneIndex = 1; sectionIndex = 1; controlIndex = 1; layoutIndex = 1 }
                                    webPartId = $componentId
                                    webPartData = @{
                                        id = $componentId; instanceId = $instanceId
                                        title = "UCC Dashboard"; description = "Unified Contact Center Dashboard"
                                        dataVersion = "1.0"; properties = @{ description = "UCC Dashboard" }
                                        serverProcessedContent = @{ htmlStrings = @{}; searchablePlainTexts = @{}; imageSources = @{}; links = @{} }
                                        dynamicDataPaths = @{}; dynamicDataValues = @{}
                                    }
                                } | ConvertTo-Json -Depth 10 -Compress
                                $webPartData = @{
                                    id = $componentId; instanceId = $instanceId
                                    title = "UCC Dashboard"; description = "Unified Contact Center Dashboard"
                                    dataVersion = "1.0"; properties = @{ description = "UCC Dashboard" }
                                    serverProcessedContent = @{ htmlStrings = @{}; searchablePlainTexts = @{}; imageSources = @{}; links = @{} }
                                    dynamicDataPaths = @{}; dynamicDataValues = @{}
                                } | ConvertTo-Json -Depth 10 -Compress
                                $cdEnc = $controlData -replace '"', '&quot;'
                                $wdEnc = $webPartData -replace '"', '&quot;'
                                $canvasHtml = "<div data-sp-canvascontrol=`"`" data-sp-canvasdataversion=`"1.0`" data-sp-controldata=`"$cdEnc`"><div data-sp-webpart=`"`" data-sp-webpartdataversion=`"1.0`" data-sp-webpartdata=`"$wdEnc`"><div data-sp-componentid=`"$componentId`"></div><div data-sp-htmlproperties=`"`"></div></div></div>"
                                $pageItem["CanvasContent1"] = $canvasHtml
                                $pageItem.Update(); Invoke-PnPQuery -ErrorAction Stop
                                $webPartAdded = $true; Info "UCC Dashboard web part added (direct injection)"
                                # Promote to full-width layout
                                try
                                {
                                    $pageItem = Get-PnPListItem -List "SitePages" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Home.aspx</Value></Eq></Where></Query></View>" -ErrorAction Stop
                                    $canvas = $pageItem.FieldValues["CanvasContent1"]
                                    if ($null -ne $canvas)
                                    {
                                        $updated = $canvas -replace '"layoutIndex":1', '"layoutIndex":2'
                                        if ($updated -ne $canvas) { $pageItem["CanvasContent1"] = $updated; $pageItem.Update(); Invoke-PnPQuery -ErrorAction SilentlyContinue }
                                    }
                                }
                                catch { }
                            }
                        }
                        catch { Warn "CanvasContent1 injection failed: $($_.Exception.Message)" }
                    }

                    if (-not $webPartAdded -and $useSubSites)
                    {
                        Warn "UCC Dashboard web part was NOT added — run: .\Modernize-UccSite.ps1 -SiteUrl '$SiteUrl' -Mode Modernize -Force"
                    }

                    # Publish and set as homepage
                    if ($webPartAdded)
                    {
                        try { Set-PnPPage -Identity $homePage -Publish -ErrorAction Stop | Out-Null; Info "Home.aspx published" }
                        catch
                        {
                            try
                            {
                                $pi = Get-PnPListItem -List "Site Pages" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Home.aspx</Value></Eq></Where></Query></View>" -ErrorAction Stop
                                if ($pi) { $pi.File.Publish("Published by UCC Site Creator"); Invoke-PnPQuery -ErrorAction Stop; Info "Home.aspx published (CSOM)" }
                            }
                            catch { Info "Home.aspx saved as draft — publish manually in SharePoint UI" }
                        }
                    }

                    try { Set-PnPHomePage -RootFolderRelativeUrl "SitePages/Home.aspx"; Info "Home page set to: SitePages/Home.aspx" }
                    catch { Warn "Could not set homepage: $($_.Exception.Message)" }

                    if ($useSubSites)
                    {
                        try { Remove-PnPPage -Identity "TempHomePage" -Force -ErrorAction SilentlyContinue } catch { }
                    }
                }
            }
        }
        catch
        {
            Warn "Home page configuration failed: $($_.Exception.Message)"
            if ($useSubSites) { Warn "To fix: .\Modernize-UccSite.ps1 -SiteUrl '$SiteUrl' -Mode Modernize -Force" }
        }

        # Set AnywhereNow site logo
        Info "Setting AnywhereNow site logo..."
        try
        {
            $reconnected = Connect -Url $SiteUrl
            if ($reconnected -and (Test-Path $logoLocalPath))
            {
                try
                {
                    Set-PnPSite -LogoFilePath $logoLocalPath -ErrorAction Stop
                    Info "Site logo set (AnywhereNow)"
                }
                catch
                {
                    try
                    {
                        $uploaded = Add-PnPFile -Path $logoLocalPath -Folder "SiteAssets" -ErrorAction Stop
                        Set-PnPWeb -SiteLogoUrl $uploaded.ServerRelativeUrl -ErrorAction Stop
                        Info "Site logo set (AnywhereNow)"
                    }
                    catch { Warn "Could not set site logo: $($_.Exception.Message)" }
                }
            }
        }
        catch { Warn "Could not set site logo: $($_.Exception.Message)" }

        # Disable page comments — site collection level only, skip for subsites
        if (-not $useSubSites)
        {
            try { Set-PnPSite -CommentsOnSitePagesDisabled:$true -ErrorAction Stop; Info "Page comments disabled" }
            catch { Warn "Could not disable page comments: $($_.Exception.Message)" }
        }
        else { Info "Page comments: skipped (subsite inherits from site collection)" }

        # Apply schema updates
        Info "Applying schema updates..."
        try
        {
            if (-not $script:schemaLoaded -and (Test-Path $schemaUpdatesPath))
            {
                . $schemaUpdatesPath; $script:schemaLoaded = $true
            }
            $schemaResult = Invoke-SchemaUpdates
            if ($schemaResult.ColumnsAdded -gt 0 -or $schemaResult.ItemsAdded -gt 0)
            {
                Info "Schema updated: $($schemaResult.ColumnsAdded) column(s), $($schemaResult.ItemsAdded) item(s)"
            }
            else { Info "Schema is up to date" }
        }
        catch { Warn "Schema update failed: $($_.Exception.Message)" }
    }

    # Step 2: Create UCC site — call Deploy-SiteDashboard per site immediately after provisioning
    Connect -Url $scurl | Out-Null
    $ctx = Get-PnPContext

    if ($useSubSites)
    {
        Info "Subsite mode: checking A365_UCC_Creator list for pending requests..."
        $siteDirectoryItems = @(GetSiteToProvision | Where-Object { $_ -ne $null })
        if ($siteDirectoryItems.Count -eq 0)
        {
            Write-Host ""
            Write-Host "  No new site requests detected." -ForegroundColor Yellow
            Write-Host "  To provision a new UCC subsite, add an entry to the A365_UCC_Creator list" -ForegroundColor Yellow
            Write-Host "  with the UCC Name, Parent Site, and Provision Status set to 'Requested'." -ForegroundColor Yellow
            Write-Host ""
        }
        else
        {
            $total = $siteDirectoryItems.Count
            $i = 0
            foreach ($siteDirectoryItem in $siteDirectoryItems)
            {
                $i++
                Info "--- Processing request $i of ${total}: $($siteDirectoryItem['Title']) ---"
                Connect -Url $scurl | Out-Null
                $ctx = Get-PnPContext
                $urlCountBefore = $global:deployedSiteUrls.Count
                ProcessSiteToProvision $siteDirectoryItem
                if ($global:deployedSiteUrls.Count -gt $urlCountBefore)
                {
                    $newSiteUrl = $global:deployedSiteUrls[$global:deployedSiteUrls.Count - 1]
                    if ($global:paramUseSiteCollectionAppCatalog)
                    {
                        Info "Installing UCC Dashboard app on subsite (site collection catalog mode)..."
                        try {
                            Connect -Url $newSiteUrl | Out-Null
                            $uccApp = Get-PnPApp -Identity "ucc-dashboard-spfx-client-side-solution" -Scope Site -ErrorAction SilentlyContinue
                            if (-not $uccApp) { $uccApp = Get-PnPApp -Identity "26A55D4E-07B7-4ADA-A0B8-0A31A8D2E3C1" -Scope Site -ErrorAction SilentlyContinue }
                            if ($uccApp) {
                                if ($uccApp.InstalledVersion) {
                                    Update-PnPApp -Identity $uccApp.Id -Scope Site -ErrorAction SilentlyContinue
                                    Info "UCC Dashboard app updated on subsite"
                                } else {
                                    Install-PnPApp -Identity $uccApp.Id -Scope Site -Wait -ErrorAction Stop
                                    Info "UCC Dashboard app installed on subsite"
                                }
                            } else {
                                Warn "UCC Dashboard app not found in site collection catalog - run Deploy-UccDashboard.ps1 -SiteCollectionAppCatalogUrl '$scurl' first"
                            }
                        }
                        catch { Warn "Could not install UCC Dashboard app: $($_.Exception.Message)" }
                    }
                    Deploy-SiteDashboard -SiteUrl $newSiteUrl
                }
            }
        }
    }
    else
    {
        if (![string]::IsNullOrEmpty($paramUccName) -and ![string]::IsNullOrEmpty($paramUccTitle))
        {
            $urlCountBefore = $global:deployedSiteUrls.Count
            ProcessSiteToProvision
            if ($global:deployedSiteUrls.Count -gt $urlCountBefore)
            {
                $newSiteUrl = $global:deployedSiteUrls[$global:deployedSiteUrls.Count - 1]
                    if ($global:paramUseSiteCollectionAppCatalog)
                    {
                        Info "Installing UCC Dashboard app on subsite (site collection catalog mode)..."
                        try {
                            Connect -Url $newSiteUrl | Out-Null
                            $uccApp = Get-PnPApp -Identity "ucc-dashboard-spfx-client-side-solution" -Scope Site -ErrorAction SilentlyContinue
                            if (-not $uccApp) { $uccApp = Get-PnPApp -Identity "26A55D4E-07B7-4ADA-A0B8-0A31A8D2E3C1" -Scope Site -ErrorAction SilentlyContinue }
                            if ($uccApp) {
                                if ($uccApp.InstalledVersion) {
                                    Update-PnPApp -Identity $uccApp.Id -Scope Site -ErrorAction SilentlyContinue
                                    Info "UCC Dashboard app updated on subsite"
                                } else {
                                    Install-PnPApp -Identity $uccApp.Id -Scope Site -Wait -ErrorAction Stop
                                    Info "UCC Dashboard app installed on subsite"
                                }
                            } else {
                                Warn "UCC Dashboard app not found in site collection catalog - run Deploy-UccDashboard.ps1 -SiteCollectionAppCatalogUrl '$scurl' first"
                            }
                        }
                        catch { Warn "Could not install UCC Dashboard app: $($_.Exception.Message)" }
                    }
                Deploy-SiteDashboard -SiteUrl $newSiteUrl
            }
        }
        else
        {
            $siteDirectoryItems = @(GetSiteToProvision | Where-Object { $_ -ne $null })
            if ($siteDirectoryItems.Count -eq 0)
            {
                Write-Host "No site requests detected" -ForegroundColor Yellow
            }
            else
            {
                $total = $siteDirectoryItems.Count
                $i = 0
                foreach ($siteDirectoryItem in $siteDirectoryItems)
                {
                    $i++
                    Info "--- Processing request $i of ${total}: $($siteDirectoryItem['Title']) ---"
                    Connect -Url $scurl | Out-Null
                    $ctx = Get-PnPContext
                    $urlCountBefore = $global:deployedSiteUrls.Count
                    ProcessSiteToProvision $siteDirectoryItem
                    if ($global:deployedSiteUrls.Count -gt $urlCountBefore)
                    {
                        $newSiteUrl = $global:deployedSiteUrls[$global:deployedSiteUrls.Count - 1]
                    if ($global:paramUseSiteCollectionAppCatalog)
                    {
                        Info "Installing UCC Dashboard app on subsite (site collection catalog mode)..."
                        try {
                            Connect -Url $newSiteUrl | Out-Null
                            $uccApp = Get-PnPApp -Identity "ucc-dashboard-spfx-client-side-solution" -Scope Site -ErrorAction SilentlyContinue
                            if (-not $uccApp) { $uccApp = Get-PnPApp -Identity "26A55D4E-07B7-4ADA-A0B8-0A31A8D2E3C1" -Scope Site -ErrorAction SilentlyContinue }
                            if ($uccApp) {
                                if ($uccApp.InstalledVersion) {
                                    Update-PnPApp -Identity $uccApp.Id -Scope Site -ErrorAction SilentlyContinue
                                    Info "UCC Dashboard app updated on subsite"
                                } else {
                                    Install-PnPApp -Identity $uccApp.Id -Scope Site -Wait -ErrorAction Stop
                                    Info "UCC Dashboard app installed on subsite"
                                }
                            } else {
                                Warn "UCC Dashboard app not found in site collection catalog - run Deploy-UccDashboard.ps1 -SiteCollectionAppCatalogUrl '$scurl' first"
                            }
                        }
                        catch { Warn "Could not install UCC Dashboard app: $($_.Exception.Message)" }
                    }
                        Deploy-SiteDashboard -SiteUrl $newSiteUrl
                    }
                }
            }
        }
    }

    Disconnect-PnPOnline

    Info ""
    Info "=========================================="
    Info "UCC Site Creator Complete"
    Info "=========================================="
    if ($global:deployedSiteUrls.Count -gt 1)
    {
        Info "Deployed sites:"
        foreach ($u in $global:deployedSiteUrls) { Info "  $u" }
    }
    elseif ($global:deployedSiteUrls.Count -eq 1)
    {
        Info "Site URL: $($global:deployedSiteUrls[0])"
    }
    else
    {
        Info "Site URL: $scurl"
    }
}
