# CCLS Games CLI Tool
# Simplified Version focusing on authentication

# Configuration
$baseUrl = "https://games.ccls.icu"
$cliApiUrl = "$baseUrl/CLI"
$settingsFolder = ".\settings"
$credentialsFile = "$settingsFolder\credentials.dat"
$settingsFile = "$settingsFolder\settings.json" # Using JSON instead of INI for simplicity

# Ensure settings directory exists
if (-not (Test-Path $settingsFolder)) {
    New-Item -Path $settingsFolder -ItemType Directory | Out-Null
}

# Initialize or load settings
function Initialize-Settings {
    if (-not (Test-Path $settingsFile)) {
        # Create default settings file
        $defaultSettings = @{
            RememberLogin = $false
            DownloadPath = ".\downloads"
        }
        $defaultSettings | ConvertTo-Json | Set-Content -Path $settingsFile
    }
    
    # Load settings
    $settings = Get-Content -Path $settingsFile | ConvertFrom-Json
    return $settings
}

# Save settings
function Save-Settings($settings) {
    $settings | ConvertTo-Json | Set-Content -Path $settingsFile
}

# Store credentials securely
function Save-Credentials($username, $password) {
    $credentials = @{
        Username = $username
        Password = $password
    } | ConvertTo-Json
    
    # Simple encryption (replace with more secure method if needed)
    $securePassword = ConvertTo-SecureString -String $credentials -AsPlainText -Force
    $encryptedText = ConvertFrom-SecureString -SecureString $securePassword
    
    # Save to file
    $encryptedText | Set-Content -Path $credentialsFile
}

# Load stored credentials
function Get-StoredCredentials {
    if (Test-Path $credentialsFile) {
        try {
            $encryptedText = Get-Content -Path $credentialsFile
            $securePassword = ConvertTo-SecureString -String $encryptedText
            $credentials = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
                [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
            )
            return $credentials | ConvertFrom-Json
        }
        catch {
            Write-Host "Error reading credentials: $($_.Exception.Message)" -ForegroundColor Red
            return $null
        }
    }
    return $null
}

# Validate username against server
function Test-Username($username) {
    $params = @{
        Uri = "$cliApiUrl/username_check.php"
        Method = "POST"
        Headers = @{
            "User-Agent" = "CCLS-CLI/1.0"
        }
        Body = @{
            username = $username
        }
    }
    
    try {
        $response = Invoke-RestMethod @params
        return $response.exists
    }
    catch {
        Write-Host "Error connecting to the server: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Validate password against server
function Test-Password($username, $password) {
    $params = @{
        Uri = "$cliApiUrl/password_check.php"
        Method = "POST"
        Headers = @{
            "User-Agent" = "CCLS-CLI/1.0"
        }
        Body = @{
            username = $username
            password = $password
        }
    }
    
    try {
        $response = Invoke-RestMethod @params
        return $response.success
    }
    catch {
        Write-Host "Error connecting to the server: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Try auto-login with stored credentials
function Start-AutoLogin {
    $credentials = Get-StoredCredentials
    if ($credentials -ne $null) {
        Write-Host "Attempting to login with stored credentials..." -ForegroundColor Gray
        
        if (Test-Password -username $credentials.Username -password $credentials.Password) {
            Write-Host "Auto-login successful!" -ForegroundColor Green
            return @{
                Success = $true
                Username = $credentials.Username
            }
        }
        else {
            Write-Host "Stored credentials are no longer valid." -ForegroundColor Yellow
            # Remove invalid credentials
            if (Test-Path $credentialsFile) {
                Remove-Item -Path $credentialsFile -Force
            }
        }
    }
    
    return @{
        Success = $false
    }
}

# Manual login process
function Start-ManualLogin {
    $maxAttempts = 3
    $attempts = 0
    
    while ($attempts -lt $maxAttempts) {
        Write-Host "`nUsername: " -ForegroundColor Cyan -NoNewline
        $username = Read-Host
        
        # Check if username exists
        Write-Host "Checking username..." -ForegroundColor Gray
        if (Test-Username -username $username) {
            Write-Host "Username found!" -ForegroundColor Green
            
            Write-Host "Password: " -ForegroundColor Cyan -NoNewline
            $password = Read-Host -AsSecureString
            $passwordPlain = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
                [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
            )
            
            Write-Host "Validating password..." -ForegroundColor Gray
            if (Test-Password -username $username -password $passwordPlain) {
                Write-Host "Login successful!" -ForegroundColor Green
                
                # Ask if user wants to save credentials
                Write-Host "`nDo you want to remember your login info for next time? (Y/N)" -ForegroundColor Yellow
                $rememberLogin = Read-Host
                
                if ($rememberLogin.ToLower() -eq "y") {
                    Save-Credentials -username $username -password $passwordPlain
                    $settings = Initialize-Settings
                    $settings.RememberLogin = $true
                    Save-Settings -settings $settings
                    Write-Host "Login information saved." -ForegroundColor Green
                }
                
                return @{
                    Success = $true
                    Username = $username
                }
            }
            else {
                Write-Host "Incorrect password, please try again." -ForegroundColor Red
                $attempts++
            }
        }
        else {
            Write-Host "Username not found, please try again." -ForegroundColor Red
            $attempts++
        }
    }
    
    Write-Host "Too many failed login attempts. Please try again later." -ForegroundColor Red
    return @{
        Success = $false
    }
}

# Main CLI interface
function Start-MainInterface($username) {
    Clear-Host
    Write-Host "Welcome to CCLS Games CLI Tool, $username!" -ForegroundColor Green
    Write-Host "Type 'help' for a list of available commands.`n" -ForegroundColor Cyan
    
    $running = $true
    while ($running) {
        Write-Host "CCLS>" -ForegroundColor Yellow -NoNewline
        $command = Read-Host
        
        switch -Regex ($command.ToLower()) {
            "^exit|^quit" {
                $running = $false
                Write-Host "Thank you for using the CCLS Games CLI Tool. Goodbye!" -ForegroundColor Cyan
            }
            "^help" {
                Write-Host "`nAvailable Commands:" -ForegroundColor Green
                Write-Host "  help         - Show this help message"
                Write-Host "  exit, quit   - Exit the application"
                Write-Host "  logout       - Log out and exit"
                Write-Host "  forget       - Remove stored credentials"
                Write-Host ""
            }
            "^logout" {
                $running = $false
                Write-Host "Logging out..." -ForegroundColor Cyan
                # Clear the current session but keep credentials if they exist
            }
            "^forget" {
                if (Test-Path $credentialsFile) {
                    Remove-Item -Path $credentialsFile -Force
                    $settings = Initialize-Settings
                    $settings.RememberLogin = $false
                    Save-Settings -settings $settings
                    Write-Host "Stored credentials have been removed." -ForegroundColor Green
                }
                else {
                    Write-Host "No stored credentials found." -ForegroundColor Yellow
                }
            }
            default {
                Write-Host "Unknown command. Type 'help' for a list of available commands." -ForegroundColor Red
            }
        }
    }
}

# Main application flow
function Start-CclsCliTool {
    Clear-Host
    Write-Host "Hello and welcome to the CCLS Games CLI Tool" -ForegroundColor Green
    Write-Host "Before proceeding to using this software you will need to sign in."
    Write-Host "If you do not have an account already please go to $baseUrl/login.php?signup to register a new account.`n" -ForegroundColor Cyan
    
    $settings = Initialize-Settings
    
    # Try auto-login if remember login is enabled
    $loginResult = @{ Success = $false }
    if ($settings.RememberLogin) {
        $loginResult = Start-AutoLogin
    }
    
    # If auto-login failed or is disabled, do manual login
    if (-not $loginResult.Success) {
        $loginResult = Start-ManualLogin
    }
    
    # If login succeeded, show main interface
    if ($loginResult.Success) {
        Start-MainInterface -username $loginResult.Username
    }
    else {
        Write-Host "Login failed. Press any key to exit..." -ForegroundColor Red
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

# Start the application
Start-CclsCliTool