[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-FirstQuickServiceItem {
    param([string]$Html)

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

    $serviceId = $match.Groups[1].Value
    $priceText = [System.Net.WebUtility]::HtmlDecode($match.Groups[2].Value)
    $price = 0.0
    if (-not [double]::TryParse($priceText, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$price)) {
        throw "Service price is invalid: $priceText"
    }

    return @{
        ServiceId = $serviceId
        Price = $price
    }
}

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 Get-RecordedPaymentCount {
    param([string]$Html)

    $match = [regex]::Match($Html, '(\d+)\s+record\(s\)\s+on this held bill', 'IgnoreCase')
    if (-not $match.Success) {
        return 0
    }

    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-Contains {
    param(
        [string]$Html,
        [string]$Needle,
        [string]$Label
    )

    if ($Html -notmatch [regex]::Escape($Needle)) {
        throw "$Label did not contain expected text: $Needle"
    }
}

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$stamp = Get-Date -Format 'yyyyMMddHHmmss'
$guestName = "QS Smoke $stamp"
$plate = 'QS' + $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'
    }

    $quickPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/quick_service.php"
    $quickForm = Get-FormState -Html $quickPage.Content -ActionContains '../process/save_quick_service.php'
    $branchName = Get-FirstSelectValue -Html $quickPage.Content -Name 'branch_name'
    $serviceItem = Get-FirstQuickServiceItem -Html $quickPage.Content
    $serviceId = [string]$serviceItem['ServiceId']
    $servicePrice = [double]$serviceItem['Price']
    $billTotal = if ($servicePrice -gt 1.0) { [math]::Round($servicePrice, 2) } else { 50.0 }
    $partialPayment = [math]::Round([math]::Min([math]::Max(($billTotal / 2.0), 1.0), ($billTotal - 0.01)), 2)
    if ($partialPayment -le 0) {
        throw "Partial payment amount was invalid for bill total $billTotal"
    }

    $holdResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/save_quick_service.php" -Method 'POST' -Body @{
        csrf_token = $quickForm['csrf_token']
        customer_mode = 'guest'
        customer_id = ''
        car_id = ''
        customer_name = $guestName
        phone = ''
        plate_number = $plate
        province = 'Bangkok'
        brand = 'Mazda'
        model = '3'
        color = 'White'
        branch_name = $branchName
        'service_ids[]' = $serviceId
        total_price = ('{0:F2}' -f $billTotal)
        payment_method = 'cash'
        received_amount = ''
        notes = 'smoke quick service flow'
        submit_action = 'hold'
    }
    $createdOrderId = Get-OrderIdFromResponse -Response $holdResult
    $results['hold_flash'] = Get-FlashText -Html $holdResult.Content
    Assert-NotBlank -Value $results['hold_flash'] -Label 'Hold'

    $resumePage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/quick_service.php?id=$createdOrderId"
    $results['resume_status'] = [int]$resumePage.StatusCode
    $paymentForm = Get-FormState -Html $resumePage.Content -ActionContains '../process/save_quick_service.php' -RequiredHidden @{
        quick_order_id = $createdOrderId
    }
    $results['resume_order_id'] = $paymentForm['quick_order_id']
    $partialPaymentResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/save_quick_service.php" -Method 'POST' -Body @{
        csrf_token = $paymentForm['csrf_token']
        quick_order_id = $createdOrderId
        customer_mode = 'guest'
        customer_id = ''
        car_id = ''
        customer_name = $guestName
        phone = ''
        plate_number = $plate
        province = 'Bangkok'
        brand = 'Mazda'
        model = '3'
        color = 'White'
        branch_name = $branchName
        'service_ids[]' = $serviceId
        total_price = ('{0:F2}' -f $billTotal)
        payment_method = 'cash'
        received_amount = ('{0:F2}' -f $partialPayment)
        notes = 'smoke quick service flow'
        submit_action = 'pay'
    }
    $results['partial_payment_flash'] = Get-FlashText -Html $partialPaymentResult.Content
    Assert-NotBlank -Value $results['partial_payment_flash'] -Label 'Partial payment'
    $results['partial_payment_amount'] = ('{0:F2}' -f $partialPayment)
    $results['recorded_payment_count'] = Get-RecordedPaymentCount -Html $partialPaymentResult.Content

    $finalPaymentPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/quick_service.php?id=$createdOrderId"
    $finalPaymentForm = Get-FormState -Html $finalPaymentPage.Content -ActionContains '../process/save_quick_service.php'
    $finalPaymentResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/save_quick_service.php" -Method 'POST' -Body @{
        csrf_token = $finalPaymentForm['csrf_token']
        quick_order_id = $createdOrderId
        customer_mode = 'guest'
        customer_id = ''
        car_id = ''
        customer_name = $guestName
        phone = ''
        plate_number = $plate
        province = 'Bangkok'
        brand = 'Mazda'
        model = '3'
        color = 'White'
        branch_name = $branchName
        'service_ids[]' = $serviceId
        total_price = ('{0:F2}' -f $billTotal)
        payment_method = 'cash'
        received_amount = '99999'
        notes = 'smoke quick service flow'
        submit_action = 'pay'
    }
    $results['completion_flash'] = Get-FlashText -Html $finalPaymentResult.Content
    $receiptUri = $finalPaymentResult.BaseResponse.ResponseUri.AbsoluteUri
    $results['receipt_uri'] = $receiptUri
    if ($receiptUri -notmatch 'quick_receipt\.php\?id=\d+') {
        throw "Quick Service payment did not redirect to receipt page: $receiptUri"
    }
    $results['receipt_order_id'] = Get-OrderIdFromResponse -Response $finalPaymentResult
    Assert-Contains -Html $finalPaymentResult.Content -Needle 'receipt-paper' -Label 'Receipt page'
    $results['receipt_status'] = [int]$finalPaymentResult.StatusCode
    if ([string]::IsNullOrWhiteSpace([string]$results['completion_flash'])) {
        $results['completion_flash'] = '[blank-on-receipt]'
    }

    if (-not $KeepTestData -and $createdOrderId -gt 0) {
        $cancelPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/cancel_bill.php?id=$createdOrderId&return_to=$([uri]::EscapeDataString('quick_service.php'))"
        $cancelForm = Get-FormState -Html $cancelPage.Content -ActionContains '../process/cancel_bill.php'
        $cancelResult = 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 = $createdOrderId
            cancellation_reason = 'smoke quick service flow cleanup'
            return_to = 'quick_service.php'
        }
        $results['cleanup_flash'] = Get-FlashText -Html $cancelResult.Content
        Assert-NotBlank -Value $results['cleanup_flash'] -Label 'Cleanup'
    }

    $results['created_order_id'] = $createdOrderId
    $results.GetEnumerator() | ForEach-Object {
        "{0}: {1}" -f $_.Key, $_.Value
    }
} catch {
    if (-not $KeepTestData -and $createdOrderId -gt 0) {
        try {
            $cancelPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/cancel_bill.php?id=$createdOrderId&return_to=$([uri]::EscapeDataString('quick_service.php'))"
            $cancelForm = Get-FormState -Html $cancelPage.Content -ActionContains '../process/cancel_bill.php'
            $null = 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 = $createdOrderId
                cancellation_reason = 'smoke quick service flow cleanup'
                return_to = 'quick_service.php'
            }
        } catch {
        }
    }

    throw
}
