<#
.SYNOPSIS
    Adds new Active Directory users from a CSV file.
.DESCRIPTION
    Reads a CSV with user details and creates corresponding AD accounts.
.NOTES
    Requires RSAT / ActiveDirectory module.
#>

$base = "DC=Fonteyn,DC=local"
# Path to CSV file
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$csvPath = Join-Path $scriptPath "users.csv"

# Try to import Active Directory module
try {
    Import-Module ActiveDirectory -ErrorAction Stop
} catch {
    Write-Error "Failed to import Active Directory module. Please ensure RSAT tools are installed and you have administrative privileges."
    Write-Error "Error: $_"
    exit 1
}

# Import from CSV
Write-Host "Reading users from: $csvPath"
try {
    $users = Import-Csv -Path $csvPath
    Write-Host "Successfully loaded $($users.Count) users from CSV"
} catch {
    Write-Error "Failed to read CSV file: $_"
    exit 1
}

# Make sure Employees OU exists
if (-not (Get-ADOrganizationalUnit -Filter {DistinguishedName -eq "OU=Employees,$base"} -ErrorAction SilentlyContinue)) {
    try {
        New-ADOrganizationalUnit -Name "Employees" -Path $base
        Write-Host "Created base Employees OU" -ForegroundColor Green
    } catch {
        Write-Error "Failed to create Employees OU: $_"
        exit 1
    }
}

# Get unique OUs from CSV file
$requiredOUs = $users | Select-Object -ExpandProperty OU -Unique

# Create each required OU if it doesn't exist
foreach ($ou in $requiredOUs) {
    $ouPath = "OU=$ou,OU=Employees,$base"
    if (-not (Get-ADOrganizationalUnit -Filter {DistinguishedName -eq $ouPath} -ErrorAction SilentlyContinue)) {
        try {
            New-ADOrganizationalUnit -Name $ou -Path "OU=Employees,$base"
            Write-Host "Created OU: $ou under Employees" -ForegroundColor Green
        } catch {
            Write-Warning "Failed to create OU: $ou - $_"
        }
    } else {
        Write-Host "OU already exists: $ou" -ForegroundColor Cyan
    }
}

foreach ($user in $users) {
    $FirstName  = $user.FirstName
    $LastName   = $user.LastName
    $Username   = $user.Username
    $OU         = $user.OU
    $Password   = (ConvertTo-SecureString $user.Password -AsPlainText -Force)
    $Department = $user.Department
    $Title      = $user.Title
    $DisplayName = "$FirstName $LastName"
    $Email = "$Username@example.com"

    # Check if user already exists
    if (Get-ADUser -Filter {SamAccountName -eq $Username}) {
        Write-Host "User $Username already exists, skipping..." -ForegroundColor Yellow
        continue
    }

    # Create the user
    try {
        $ouPath = "OU=$OU,OU=Employees,$base"
        Write-Host "Attempting to create user: $Username in OU: $ouPath" -ForegroundColor Cyan
        
        # Verify OU exists first
        if (-not (Get-ADOrganizationalUnit -Filter {DistinguishedName -eq $ouPath} -ErrorAction SilentlyContinue)) {
            Write-Host "Error: OU '$ouPath' does not exist!" -ForegroundColor Red
            continue
        }

        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName $Email `
            -Name $DisplayName `
            -GivenName $FirstName `
            -Surname $LastName `
            -DisplayName $DisplayName `
            -Path $ouPath `
            -Department $Department `
            -Title $Title `
            -AccountPassword $Password `
            -Enabled $true `
            -ChangePasswordAtLogon $true `
            -ErrorAction Stop

        Write-Host "Successfully created user: $DisplayName ($Username)" -ForegroundColor Green
    }
    catch {
        Write-Host "Failed to create user $Username" -ForegroundColor Red
        Write-Host "Error details: $_" -ForegroundColor Red
        Write-Host "Stack trace: $($_.ScriptStackTrace)" -ForegroundColor Red
    }
}

Write-Host "User import complete."