[CmdletBinding()]
param(
    [string]$BaseUrl = 'http://127.0.0.1/CCW',
    [string]$Username = 'admin',
    [string]$Password = 'admin123',
    [switch]$KeepTestData
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

function Get-FlashText {
    param([string]$Html)

    $match = [regex]::Match($Html, '<div class="flash[^"]*">\s*(.*?)\s*</div>', 'IgnoreCase, Singleline')
    if (-not $match.Success) {
        return ''
    }

    $text = [regex]::Replace($match.Groups[1].Value, '<[^>]+>', '')
    return [System.Net.WebUtility]::HtmlDecode($text).Trim()
}

function Get-FormState {
    param(
        [string]$Html,
        [string]$ActionContains,
        [hashtable]$RequiredHidden = @{}
    )

    $forms = [regex]::Matches($Html, '<form\b[^>]*action="([^"]*)"[^>]*>(.*?)</form>', 'IgnoreCase, Singleline')
    foreach ($form in $forms) {
        $action = [System.Net.WebUtility]::HtmlDecode($form.Groups[1].Value)
        $body = $form.Groups[2].Value
        if (-not $action.Contains($ActionContains)) {
            continue
        }

        $matchesRequired = $true
        foreach ($key in $RequiredHidden.Keys) {
            $pattern = '<input\b[^>]*name="' + [regex]::Escape([string]$key) + '"[^>]*value="' + [regex]::Escape([string]$RequiredHidden[$key]) + '"[^>]*>'
            if (-not [regex]::IsMatch($body, $pattern, 'IgnoreCase')) {
                $matchesRequired = $false
                break
            }
        }

        if (-not $matchesRequired) {
            continue
        }

        $state = @{}
        $hiddenInputs = [regex]::Matches($body, '<input\b[^>]*type="hidden"[^>]*name="([^"]+)"[^>]*value="([^"]*)"', 'IgnoreCase')
        foreach ($input in $hiddenInputs) {
            $name = [System.Net.WebUtility]::HtmlDecode($input.Groups[1].Value)
            $value = [System.Net.WebUtility]::HtmlDecode($input.Groups[2].Value)
            $state[$name] = $value
        }

        return $state
    }

    throw "Form not found for action: $ActionContains"
}

function Get-FirstSelectValue {
    param(
        [string]$Html,
        [string]$Name
    )

    $selectPattern = '<select\b[^>]*name="' + [regex]::Escape($Name) + '"[^>]*>(.*?)</select>'
    $selectMatch = [regex]::Match($Html, $selectPattern, 'IgnoreCase, Singleline')
    if (-not $selectMatch.Success) {
        throw "Select not found: $Name"
    }

    $optionMatches = [regex]::Matches($selectMatch.Groups[1].Value, '<option\b[^>]*value="([^"]*)"[^>]*>', 'IgnoreCase')
    foreach ($option in $optionMatches) {
        $value = [System.Net.WebUtility]::HtmlDecode($option.Groups[1].Value).Trim()
        if ($value -ne '') {
            return $value
        }
    }

    throw "No non-empty option found for select: $Name"
}

function Get-FirstServiceId {
    param([string]$Html)

    $match = [regex]::Match($Html, 'name="service_ids\[\]"[^>]*value="(\d+)"', 'IgnoreCase')
    if (-not $match.Success) {
        throw 'No service id found on booking page.'
    }

    return $match.Groups[1].Value
}

function Get-OrderIdFromResponse {
    param($Response)

    $uri = $Response.BaseResponse.ResponseUri.AbsoluteUri
    $match = [regex]::Match($uri, '[?&]id=(\d+)')
    if (-not $match.Success) {
        throw "Order id not found in redirect URL: $uri"
    }

    return [int]$match.Groups[1].Value
}

function Invoke-FlowRequest {
    param(
        [Microsoft.PowerShell.Commands.WebRequestSession]$Session,
        [string]$Uri,
        [string]$Method = 'GET',
        [hashtable]$Body = @{}
    )

    $params = @{
        Uri = $Uri
        Method = $Method
        WebSession = $Session
        UseBasicParsing = $true
    }

    if ($Method -eq 'POST') {
        $params.Body = $Body
    }

    return Invoke-WebRequest @params
}

function Assert-NotBlank {
    param(
        [string]$Value,
        [string]$Label
    )

    if ([string]::IsNullOrWhiteSpace($Value)) {
        throw "$Label flash was blank."
    }
}

function Assert-True {
    param(
        [bool]$Condition,
        [string]$Message
    )

    if (-not $Condition) {
        throw $Message
    }
}

function Get-DepositPage {
    param(
        [Microsoft.PowerShell.Commands.WebRequestSession]$Session,
        [string]$BaseUrl,
        [int]$OrderId
    )

    return Invoke-FlowRequest -Session $Session -Uri "$BaseUrl/pages/job_details.php?id=$OrderId&open_deposit=1#deposit-management"
}

function Get-DepositForm {
    param(
        [string]$Html,
        [string]$Scope,
        [int]$OrderId
    )

    return Get-FormState -Html $Html -ActionContains '../process/update_booking_deposit.php' -RequiredHidden @{
        order_id = [string]$OrderId
        deposit_scope = $Scope
    }
}

function Invoke-CancelCleanup {
    param(
        [Microsoft.PowerShell.Commands.WebRequestSession]$Session,
        [string]$BaseUrl,
        [int]$OrderId,
        [string]$Reason
    )

    $returnTo = 'queue.php?status=cancelled'
    $cancelPage = Invoke-FlowRequest -Session $Session -Uri "$BaseUrl/pages/cancel_bill.php?id=$OrderId&return_to=$([uri]::EscapeDataString($returnTo))"
    $cancelForm = Get-FormState -Html $cancelPage.Content -ActionContains '../process/cancel_bill.php'
    return Invoke-FlowRequest -Session $Session -Uri "$BaseUrl/process/cancel_bill.php" -Method 'POST' -Body @{
        csrf_token = $cancelForm['csrf_token']
        submission_token = $cancelForm['submission_token']
        order_id = $OrderId
        cancellation_reason = $Reason
        return_to = $returnTo
    }
}

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$stamp = Get-Date -Format 'yyyyMMddHHmmss'
$phone = '098' + $stamp.Substring($stamp.Length - 7)
$plate = 'DP' + $stamp.Substring($stamp.Length - 6)
$results = [ordered]@{}
$createdOrderId = 0

try {
    $loginPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/login.php"
    $loginForm = Get-FormState -Html $loginPage.Content -ActionContains '../process/login.php'
    $null = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/login.php" -Method 'POST' -Body @{
        csrf_token = $loginForm['csrf_token']
        username = $Username
        password = $Password
        display_mode = 'app'
    }

    $bookingPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/booking.php"
    $bookingForm = Get-FormState -Html $bookingPage.Content -ActionContains '../process/save_booking.php'
    $branchName = Get-FirstSelectValue -Html $bookingPage.Content -Name 'branch_name'
    $serviceId = Get-FirstServiceId -Html $bookingPage.Content

    $bookingResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/save_booking.php" -Method 'POST' -Body @{
        csrf_token = $bookingForm['csrf_token']
        customer_name = "Smoke Deposit $stamp"
        phone = $phone
        plate_number = $plate
        province = 'Bangkok'
        vehicle_type = ''
        brand = 'Honda'
        model = 'Civic'
        color = 'Black'
        branch_name = $branchName
        'service_ids[]' = $serviceId
        total_price = ''
        admin_deposit_amount = '120.00'
        admin_deposit_method = 'cash'
        notes = 'smoke booking deposit flow'
    }
    $createdOrderId = Get-OrderIdFromResponse -Response $bookingResult
    $results['booking_flash'] = Get-FlashText -Html $bookingResult.Content
    Assert-NotBlank -Value $results['booking_flash'] -Label 'Booking'

    $depositPage = Get-DepositPage -Session $session -BaseUrl $BaseUrl -OrderId $createdOrderId
    $adminDepositForm = Get-DepositForm -Html $depositPage.Content -Scope 'admin' -OrderId $createdOrderId
    $branchDepositForm = Get-DepositForm -Html $depositPage.Content -Scope 'branch' -OrderId $createdOrderId

    $adminPaymentId = [int]$adminDepositForm['payment_id']
    Assert-True -Condition ($adminPaymentId -gt 0) -Message 'Admin deposit payment id was not created at booking.'
    Assert-True -Condition ([int]$branchDepositForm['payment_id'] -eq 0) -Message 'Branch deposit should not exist before add flow.'

    $adminUpdateResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/update_booking_deposit.php" -Method 'POST' -Body @{
        csrf_token = $adminDepositForm['csrf_token']
        order_id = $adminDepositForm['order_id']
        payment_id = $adminDepositForm['payment_id']
        deposit_scope = $adminDepositForm['deposit_scope']
        return_to = $adminDepositForm['return_to']
        deposit_edit_amount = '150.00'
        deposit_edit_method = 'cash'
    }
    $results['admin_update_flash'] = Get-FlashText -Html $adminUpdateResult.Content
    Assert-NotBlank -Value $results['admin_update_flash'] -Label 'Admin deposit update'

    $adminUpdatedForm = Get-DepositForm -Html $adminUpdateResult.Content -Scope 'admin' -OrderId $createdOrderId
    $adminPaymentId = [int]$adminUpdatedForm['payment_id']
    Assert-True -Condition ($adminPaymentId -gt 0) -Message 'Admin deposit payment id disappeared after update.'

    $branchDepositForm = Get-DepositForm -Html $adminUpdateResult.Content -Scope 'branch' -OrderId $createdOrderId
    $branchAddResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/update_booking_deposit.php" -Method 'POST' -Body @{
        csrf_token = $branchDepositForm['csrf_token']
        order_id = $branchDepositForm['order_id']
        payment_id = $branchDepositForm['payment_id']
        deposit_scope = $branchDepositForm['deposit_scope']
        return_to = $branchDepositForm['return_to']
        deposit_edit_amount = '75.00'
        deposit_edit_method = 'cash'
    }
    $results['branch_add_flash'] = Get-FlashText -Html $branchAddResult.Content
    Assert-NotBlank -Value $results['branch_add_flash'] -Label 'Branch deposit add'

    $branchAddedForm = Get-DepositForm -Html $branchAddResult.Content -Scope 'branch' -OrderId $createdOrderId
    $branchPaymentId = [int]$branchAddedForm['payment_id']
    Assert-True -Condition ($branchPaymentId -gt 0) -Message 'Branch deposit payment id was not created.'

    $branchDeleteResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/delete_booking_deposit.php" -Method 'POST' -Body @{
        csrf_token = $branchAddedForm['csrf_token']
        order_id = $branchAddedForm['order_id']
        payment_id = $branchAddedForm['payment_id']
        deposit_scope = $branchAddedForm['deposit_scope']
        return_to = $branchAddedForm['return_to']
    }
    $results['branch_delete_flash'] = Get-FlashText -Html $branchDeleteResult.Content
    Assert-NotBlank -Value $results['branch_delete_flash'] -Label 'Branch deposit delete'

    $depositPageAfterBranchDelete = Get-DepositPage -Session $session -BaseUrl $BaseUrl -OrderId $createdOrderId
    $branchDeletedForm = Get-DepositForm -Html $depositPageAfterBranchDelete.Content -Scope 'branch' -OrderId $createdOrderId
    Assert-True -Condition ([int]$branchDeletedForm['payment_id'] -eq 0) -Message 'Branch deposit payment id still exists after delete.'

    $adminDeleteForm = Get-FormState -Html $depositPageAfterBranchDelete.Content -ActionContains '../process/delete_booking_deposit.php' -RequiredHidden @{
        order_id = [string]$createdOrderId
        payment_id = [string]$adminPaymentId
    }
    $adminDeleteResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/delete_booking_deposit.php" -Method 'POST' -Body @{
        csrf_token = $adminDeleteForm['csrf_token']
        order_id = $adminDeleteForm['order_id']
        payment_id = $adminDeleteForm['payment_id']
        return_to = $adminDeleteForm['return_to']
    }
    $results['admin_delete_flash'] = Get-FlashText -Html $adminDeleteResult.Content
    Assert-NotBlank -Value $results['admin_delete_flash'] -Label 'Admin deposit delete'

    $depositPageAfterAdminDelete = Get-DepositPage -Session $session -BaseUrl $BaseUrl -OrderId $createdOrderId
    $adminDeletedForm = Get-DepositForm -Html $depositPageAfterAdminDelete.Content -Scope 'admin' -OrderId $createdOrderId
    Assert-True -Condition ([int]$adminDeletedForm['payment_id'] -eq 0) -Message 'Admin deposit payment id still exists after delete.'

    $results['created_order_id'] = $createdOrderId
    $results['admin_payment_id'] = $adminPaymentId
    $results['branch_payment_id'] = $branchPaymentId

    if (-not $KeepTestData -and $createdOrderId -gt 0) {
        $cleanupResult = Invoke-CancelCleanup -Session $session -BaseUrl $BaseUrl -OrderId $createdOrderId -Reason 'smoke booking deposit cleanup'
        $results['cleanup_flash'] = Get-FlashText -Html $cleanupResult.Content
        Assert-NotBlank -Value $results['cleanup_flash'] -Label 'Cleanup cancel'
    }

    $results.GetEnumerator() | ForEach-Object {
        "{0}: {1}" -f $_.Key, $_.Value
    }
} catch {
    if (-not $KeepTestData -and $createdOrderId -gt 0) {
        try {
            $null = Invoke-CancelCleanup -Session $session -BaseUrl $BaseUrl -OrderId $createdOrderId -Reason 'smoke booking deposit cleanup'
        } catch {
        }
    }

    throw
}
