# Reset password for notifications@dataforth.com in on-premises AD
# For hybrid environments with Azure AD Connect password sync

param(
    [string]$DomainController = "192.168.0.27",  # AD1 (primary DC)
    [string]$NewPassword = "%5cfI:G71)}=g4ZS"
)

Write-Host "[OK] Resetting password in on-premises Active Directory..." -ForegroundColor Green
Write-Host "    Domain Controller: $DomainController (AD1)" -ForegroundColor Cyan
Write-Host ""

# Credentials for remote connection
$AdminUser = "INTRANET\sysadmin"
$AdminPassword = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($AdminUser, $AdminPassword)

Write-Host "[OK] Connecting to $DomainController via PowerShell remoting..." -ForegroundColor Green

try {
    # Execute on remote DC
    Invoke-Command -ComputerName $DomainController -Credential $Credential -ScriptBlock {
        param($NewPass, $UserName)

        Import-Module ActiveDirectory

        # Find the user account
        Write-Host "[OK] Searching for user in Active Directory..."
        $User = Get-ADUser -Filter "UserPrincipalName -eq '$UserName'" -Properties PasswordNeverExpires, PasswordLastSet

        if (-not $User) {
            Write-Host "[ERROR] User not found in Active Directory!" -ForegroundColor Red
            return
        }

        Write-Host "[OK] Found user: $($User.Name) ($($User.UserPrincipalName))"
        Write-Host "    Current PasswordNeverExpires: $($User.PasswordNeverExpires)"
        Write-Host "    Last Password Set: $($User.PasswordLastSet)"
        Write-Host ""

        # Reset password
        Write-Host "[OK] Resetting password..." -ForegroundColor Green
        $SecurePassword = ConvertTo-SecureString $NewPass -AsPlainText -Force
        Set-ADAccountPassword -Identity $User.SamAccountName -NewPassword $SecurePassword -Reset

        Write-Host "[SUCCESS] Password reset successfully!" -ForegroundColor Green

        # Set password to never expire
        Write-Host "[OK] Setting password to never expire..." -ForegroundColor Green
        Set-ADUser -Identity $User.SamAccountName -PasswordNeverExpires $true -ChangePasswordAtLogon $false

        Write-Host "[SUCCESS] Password set to never expire!" -ForegroundColor Green

        # Verify
        $UpdatedUser = Get-ADUser -Identity $User.SamAccountName -Properties PasswordNeverExpires, PasswordLastSet
        Write-Host ""
        Write-Host "[OK] Verification:"
        Write-Host "    PasswordNeverExpires: $($UpdatedUser.PasswordNeverExpires)"
        Write-Host "    PasswordLastSet: $($UpdatedUser.PasswordLastSet)"

        # Force Azure AD Connect sync (if available)
        Write-Host ""
        Write-Host "[OK] Checking for Azure AD Connect..." -ForegroundColor Green
        if (Get-Command Start-ADSyncSyncCycle -ErrorAction SilentlyContinue) {
            Write-Host "[OK] Triggering Azure AD Connect sync..." -ForegroundColor Green
            Start-ADSyncSyncCycle -PolicyType Delta
            Write-Host "[OK] Sync triggered - password will sync to Azure AD in ~3 minutes" -ForegroundColor Green
        } else {
            Write-Host "[WARNING] Azure AD Connect not found on this server" -ForegroundColor Yellow
            Write-Host "          Password will sync automatically within 30 minutes" -ForegroundColor Yellow
            Write-Host "          Or manually trigger sync on AAD Connect server" -ForegroundColor Yellow
        }

    } -ArgumentList $NewPassword, "notifications@dataforth.com"

    Write-Host ""
    Write-Host "================================================================"
    Write-Host "PASSWORD RESET COMPLETE"
    Write-Host "================================================================"
    Write-Host "New Password: $NewPassword" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "[OK] Password policy: NEVER EXPIRES (set in AD)" -ForegroundColor Green
    Write-Host "[OK] Azure AD Connect will sync this change automatically" -ForegroundColor Green
    Write-Host ""
    Write-Host "================================================================"
    Write-Host "NEXT STEPS"
    Write-Host "================================================================"
    Write-Host "1. Wait 3-5 minutes for Azure AD Connect to sync" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "2. Update website SMTP configuration:" -ForegroundColor Cyan
    Write-Host "   - Username: notifications@dataforth.com"
    Write-Host "   - Password: $NewPassword" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "3. Test SMTP authentication:" -ForegroundColor Cyan
    Write-Host "   D:\ClaudeTools\Test-DataforthSMTP.ps1"
    Write-Host ""
    Write-Host "4. Verify authentication succeeds:" -ForegroundColor Cyan
    Write-Host "   D:\ClaudeTools\Get-DataforthEmailLogs.ps1"
    Write-Host ""

    # Save credentials
    $CredPath = "D:\ClaudeTools\dataforth-notifications-FINAL-PASSWORD.txt"
    @"
Dataforth Notifications Account - PASSWORD RESET (HYBRID AD)
Reset Date: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")

Username: notifications@dataforth.com
Password: $NewPassword

Password Policy:
- Set in: On-Premises Active Directory (INTRANET domain)
- Never Expires: YES
- Synced to Azure AD: Via Azure AD Connect

SMTP Configuration for Website:
- Server: smtp.office365.com
- Port: 587
- TLS: Yes
- Username: notifications@dataforth.com
- Password: $NewPassword

Note: Allow 3-5 minutes for password to sync to Azure AD before testing.

DO NOT COMMIT TO GIT OR SHARE PUBLICLY
"@ | Out-File -FilePath $CredPath -Encoding UTF8

    Write-Host "[OK] Credentials saved to: $CredPath" -ForegroundColor Green

} catch {
    Write-Host "[ERROR] Failed to reset password: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host ""
    Write-Host "Troubleshooting:" -ForegroundColor Yellow
    Write-Host "- Ensure you're on the Dataforth VPN or network" -ForegroundColor Yellow
    Write-Host "- Verify AD1 (192.168.0.27) is accessible" -ForegroundColor Yellow
    Write-Host "- Check WinRM is enabled on AD1" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Alternative: RDP to AD1 and run locally:" -ForegroundColor Cyan
    Write-Host "  Set-ADAccountPassword -Identity notifications -Reset -NewPassword (ConvertTo-SecureString '$NewPassword' -AsPlainText -Force)" -ForegroundColor Gray
    Write-Host "  Set-ADUser -Identity notifications -PasswordNeverExpires `$true -ChangePasswordAtLogon `$false" -ForegroundColor Gray
}
