$RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$directory_SubSite = $RootPath + "\AnywhereNow\Pages"

function CreateTemplateSite
{
    switch ($language) 
	{ 
        Danish { $lcid = 1030 } 
        Dutch { $lcid = 1043 } 
        English { $lcid = 1033 } 
        French { $lcid = 1036 } 
        German { $lcid = 1031 } 
        Italian { $lcid = 1040 }
        Norwegian { $lcid = 1044 }
        Portuguese { $lcid = 2070 }
        Spanish { $lcid = 3082 }
        Swedish { $lcid = 1053 }
        default { $lcid = 1033 }
    }

    switch ($timeZone) 
	{ 
        "(UTC-12:00) International Date Line West" { $timeZoneId = 39 } 
        "(UTC-11:00) Coordinated Universal Time-11" { $timeZoneId = 95  } 
        "(UTC-10:00) Hawaii" { $timeZoneId = 15 } 
        "(UTC-09:00) Alaska" { $timeZoneId = 14 } 
        "(UTC-08:00) Baja California" { $timeZoneId = 78 } 
        "(UTC-08:00) Pacific Time (US and Canada)" { $timeZoneId = 13 } 
        "(UTC-07:00) Arizona" { $timeZoneId = 38 } 
        "(UTC-07:00) Chihuahua, La Paz, Mazatlan" { $timeZoneId = 77 } 
        "(UTC-07:00) Mountain Time (US and Canada)" { $timeZoneId = 12 } 
        "(UTC-06:00) Central America" { $timeZoneId = 55 } 
        "(UTC-06:00) Central Time (US and Canada)" { $timeZoneId = 11 } 
        "(UTC-06:00) Guadalajara, Mexico City, Monterrey" { $timeZoneId = 37 } 
        "(UTC-06:00) Saskatchewan" { $timeZoneId = 36 } 
        "(UTC-05:00) Bogota, Lima, Quito" { $timeZoneId = 35 } 
        "(UTC-05:00) Eastern Time (US and Canada)" { $timeZoneId = 10 } 
        "(UTC-05:00) Indiana (East)" { $timeZoneId = 34 } 
        "(UTC-04:30) Caracas" { $timeZoneId = 88 } 
        "(UTC-04:00) Asuncion" { $timeZoneId = 91 } 
        "(UTC-04:00) Atlantic Time (Canada)" { $timeZoneId = 9 } 
        "(UTC-04:00) Cuiaba" { $timeZoneId = 81 } 
        "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan" { $timeZoneId = 33 } 
        "(UTC-03:30) Newfoundland" { $timeZoneId = 28 } 
        "(UTC-03:00) Brasilia" { $timeZoneId = 8 } 
        "(UTC-03:00) Buenos Aires" { $timeZoneId = 85 } 
        "(UTC-03:00) Cayenne, Fortaleza" { $timeZoneId = 32 } 
        "(UTC-03:00) Greenland" { $timeZoneId = 60 } 
        "(UTC-03:00) Montevideo" { $timeZoneId = 90 } 
        "(UTC-03:00) Salvador" { $timeZoneId = 103 } 
        "(UTC-03:00) Santiago" { $timeZoneId = 65 } 
        "(UTC-02:00) Coordinated Universal Time-02" { $timeZoneId = 96 } 
        "(UTC-02:00) Mid-Atlantic" { $timeZoneId = 30 } 
        "(UTC-01:00) Azores" { $timeZoneId = 29 } 
        "(UTC-01:00) Cabo Verde" { $timeZoneId = 53 } 
        "(UTC) Casablanca" { $timeZoneId = 86 } 
        "(UTC) Coordinated Universal Time" { $timeZoneId = 93 } 
        "(UTC) Dublin, Edinburgh, Lisbon, London" { $timeZoneId = 2 } 
        "(UTC) Monrovia, Reykjavik" { $timeZoneId = 31 } 
        "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna" { $timeZoneId = 4 } 
        "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague" { $timeZoneId = 6 } 
        "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris" { $timeZoneId = 3 }
        "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb" { $timeZoneId = 57 } 
        "(UTC+01:00) West Central Africa" { $timeZoneId = 69 } 
        "(UTC+01:00) Windhoek" { $timeZoneId = 83 } 
        "(UTC+02:00) Amman" { $timeZoneId = 79 } 
        "(UTC+02:00) Athens, Bucharest" { $timeZoneId = 5 } 
        "(UTC+02:00) Beirut" { $timeZoneId = 80 } 
        "(UTC+02:00) Cairo" { $timeZoneId = 49 } 
        "(UTC+02:00) Damascus" { $timeZoneId = 98 } 
        "(UTC+02:00) Harare, Pretoria" { $timeZoneId = 50 } 
        "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius" { $timeZoneId = 59 } 
        "(UTC+02:00) Jerusalem" { $timeZoneId = 27 } 
        "(UTC+02:00) Minsk (old)" { $timeZoneId = 7 } 
        "(UTC+02:00) E. Europe" { $timeZoneId = 104 } 
        "(UTC+02:00) Kaliningrad" { $timeZoneId = 100 } 
        "(UTC+03:00) Baghdad" { $timeZoneId = 26 } 
        "(UTC+03:00) Istanbul" { $timeZoneId = 101 } 
        "(UTC+03:00) Kuwait, Riyadh" { $timeZoneId = 74 } 
        "(UTC+03:00) Minsk" { $timeZoneId = 109 } 
        "(UTC+03:00) Moscow, St. Petersburg, Volgograd" { $timeZoneId = 51 } 
        "(UTC+03:00) Nairobi" { $timeZoneId = 56 } 
        "(UTC+03:30) Tehran" { $timeZoneId = 25 } 
        "(UTC+04:00) Abu Dhabi, Muscat" { $timeZoneId = 24 } 
        "(UTC+04:00) Astrakhan, Ulyanovsk" { $timeZoneId = 110 } 
        "(UTC+04:00) Baku" { $timeZoneId = 54 } 
        "(UTC+04:00) Izhevsk, Samara" { $timeZoneId = 106 } 
        "(UTC+04:00) Port Louis" { $timeZoneId = 89 } 
        "(UTC+04:00) Tbilisi" { $timeZoneId = 82 } 
        "(UTC+04:00) Yerevan" { $timeZoneId = 84 } 
        "(UTC+04:30) Kabul" { $timeZoneId = 48 } 
        "(UTC+05:00) Ekaterinburg" { $timeZoneId = 58 } 
        "(UTC+05:00) Islamabad, Karachi" { $timeZoneId = 87 } 
        "(UTC+05:00) Tashkent" { $timeZoneId = 47 } 
        "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi" { $timeZoneId = 23 } 
        "(UTC+05:30) Sri Jayawardenepura" { $timeZoneId = 66 } 
        "(UTC+05:45) Kathmandu" { $timeZoneId = 62 } 
        "(UTC+06:00) Astana" { $timeZoneId = 71 } 
        "(UTC+06:00) Dhaka" { $timeZoneId = 102 } 
        "(UTC+06:00) Omsk" { $timeZoneId = 115 } 
        "(UTC+06:30) Yangon (Rangoon)" { $timeZoneId = 61 } 
        "(UTC+07:00) Bangkok, Hanoi, Jakarta" { $timeZoneId = 22 } 
        "(UTC+07:00) Barnaul, Gorno-Altaysk" { $timeZoneId = 111 } 
        "(UTC+07:00) Krasnoyarsk" { $timeZoneId = 64 } 
        "(UTC+07:00) Novosibirsk" { $timeZoneId = 46 } 
        "(UTC+07:00) Tomsk" { $timeZoneId = 112 } 
        "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi" { $timeZoneId = 45 } 
        "(UTC+08:00) Irkutsk" { $timeZoneId = 63 } 
        "(UTC+08:00) Kuala Lumpur, Singapore" { $timeZoneId = 21 } 
        "(UTC+08:00) Perth" { $timeZoneId = 73 } 
        "(UTC+08:00) Taipei" { $timeZoneId = 75 } 
        "(UTC+08:00) Ulaanbaatar" { $timeZoneId = 94 } 
        "(UTC+09:00) Osaka, Sapporo, Tokyo" { $timeZoneId = 20 } 
        "(UTC+09:00) Seoul" { $timeZoneId = 72 } 
        "(UTC+09:00) Yakutsk" { $timeZoneId = 70 } 
        "(UTC+09:30) Adelaide" { $timeZoneId = 19 } 
        "(UTC+09:30) Darwin" { $timeZoneId = 44 } 
        "(UTC+10:00) Brisbane" { $timeZoneId = 18 } 
        "(UTC+10:00) Canberra, Melbourne, Sydney" { $timeZoneId = 76 } 
        "(UTC+10:00) Guam, Port Moresby" { $timeZoneId = 43 } 
        "(UTC+10:00) Hobart" { $timeZoneId = 42 } 
        "(UTC+10:00) Magadan" { $timeZoneId = 99 } 
        "(UTC+10:00) Vladivostok" { $timeZoneId = 68 } 
        "(UTC+11:00) Chokurdakh" { $timeZoneId = 107 } 
        "(UTC+11:00) Sakhalin" { $timeZoneId = 114 } 
        "(UTC+11:00) Solomon Is., New Caledonia" { $timeZoneId = 41 } 
        "(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky" { $timeZoneId = 108 } 
        "(UTC+12:00) Auckland, Wellington" { $timeZoneId = 17 } 
        "(UTC+12:00) Coordinated Universal Time+12" { $timeZoneId = 97 } 
        "(UTC+12:00) Fiji" { $timeZoneId = 40 } 
        "(UTC+12:00) Petropavlovsk-Kamchatsky - Old" { $timeZoneId = 92 } 
        "(UTC+13:00) Nuku'alofa" { $timeZoneId = 67 } 
        "(UTC+13:00) Samoa" { $timeZoneId = 16 } 
    }
	
	# Deploy based on mode
	if ($useSubSites)
	{
		# ---------------------------------------------------------------------------
		# Subsite mode: create UCC site as a subsite under $parentSiteUrl (or $scurl)
		# ---------------------------------------------------------------------------

		# $parentSiteUrl is set by GetSubSiteUrl (from A365_ParentSite field or URL parsing).
		# Fall back to $scurl (site collection root) if not set.
		$effectiveParentUrl = if (-not [string]::IsNullOrEmpty($parentSiteUrl)) { $parentSiteUrl } else { $scurl }

		$connectedToParent = Connect -Url $effectiveParentUrl
		if (-not $connectedToParent)
		{
			Start-Sleep -s 10
			$connectedToParent = Connect -Url $effectiveParentUrl
			if (-not $connectedToParent)
			{
				Error "Cannot connect to parent site: $effectiveParentUrl"
				UpdateStatus $siteItem["ID"] "Error: Cannot connect to parent site"
				exit
			}
		}

		# Log parent site type for informational purposes
		try
		{
			$parentWeb = Get-PnPWeb -ErrorAction SilentlyContinue
			if ($parentWeb)
			{
				$parentTemplate = $parentWeb.WebTemplate
				switch -Wildcard ($parentTemplate)
				{
					"SITEPAGEPUBLISHING*" { Info "Parent site type: Communication Site" }
					"GROUP*"              { Info "Parent site type: Group-connected Team Site" }
					default               { Info "Parent site type: Classic ($parentTemplate)" }
				}
			}
		}
		catch { }

		# Check if subsite already exists to prevent duplicates
		$subsiteName = $siteUrl.TrimEnd('/').Split('/')[-1]
		$existingSubsite = Get-PnPSubWeb -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Url -like "*/$subsiteName" }
		if ($existingSubsite)
		{
			Warn "Subsite already exists: $siteUrl — skipping creation"
		}
		else
		{
			Info "Creating subsite: $siteUrl (template: STS#0, lcid: $lcid)"
			New-PnPWeb -Url $subsiteName -Title $uccTitle -Template "STS#0" -Locale $lcid -ErrorAction Stop | Out-Null
			Info "Subsite created. Waiting for provisioning..."
			Start-Sleep -Seconds 10
		}

		# Connect to the new subsite
		$connectedToSubsite = Connect -Url $siteUrl
		if (-not $connectedToSubsite)
		{
			Start-Sleep -s 10
			$connectedToSubsite = Connect -Url $siteUrl
			if (-not $connectedToSubsite)
			{
				Error "Cannot connect to new subsite: $siteUrl"
				UpdateStatus $siteItem["ID"] "Error: Cannot connect to subsite"
				exit
			}
		}

		$ctx_newSite = Get-PnPContext

		# Set timezone via CSOM RegionalSettings
		if ($timeZoneId -ne $null)
		{
			$ctx_newSite.Load($ctx_newSite.Web)
			$ctx_newSite.Load($ctx_newSite.Web.RegionalSettings.TimeZone)
			$ctx_newSite.Load($ctx_newSite.Web.RegionalSettings.TimeZones)
			$ctx_newSite.ExecuteQuery()
			$ctx_newSite.Web.RegionalSettings.TimeZone = $ctx_newSite.Web.RegionalSettings.TimeZones.GetbyID($timeZoneId)
			$ctx_newSite.Web.Update()
			$ctx_newSite.ExecuteQuery()
		}

		# Enable Team Collaboration Lists feature
		EnableTeamCollaborationListsFeature
	}
	else
	{
		# ---------------------------------------------------------------------------
		# Root mode (original behaviour): deploy to site collection root
		# ---------------------------------------------------------------------------
		$connected = Connect -Url $siteUrl
		if (-not $connected)
		{
			Start-Sleep -s 10
			$connected = Connect -Url $siteUrl
			if (-not $connected)
			{
				Error "Cannot connect to site"
				UpdateStatus $siteItem["ID"] "Error: Cannot connect"
				exit
			}
		}

		$ctx_newSite = Get-PnPContext

		$web = Get-PnPWeb
		$relativeURL = $web.ServerRelativeUrl
		$pagesLibrary = GetPagesLibrary($lcid)

		# SharePoint Online - upload pages
		AddPnPFile "$directory_SubSite\portal.aspx" $pagesLibrary "$relativeURL/$pagesLibrary/portal.aspx"
		SetPnPHomePage "$pagesLibrary/portal.aspx"

		# Timezone
		if ($timeZoneId -ne $null)
		{
			$ctx_newSite.Load($ctx_newSite.Web)
			$ctx_newSite.Load($ctx_newSite.Web.RegionalSettings.TimeZone)
			$ctx_newSite.Load($ctx_newSite.Web.RegionalSettings.TimeZones)
			$ctx_newSite.ExecuteQuery()
			$ctx_newSite.Web.RegionalSettings.TimeZone = $ctx_newSite.Web.RegionalSettings.TimeZones.GetbyID($timeZoneId)
			$ctx_newSite.Web.Update()
			$ctx_newSite.ExecuteQuery()
		}

		# Team Collaboration Lists feature
		EnableTeamCollaborationListsFeature
	}
}
