[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 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 Cancel-Order {
    param(
        [Microsoft.PowerShell.Commands.WebRequestSession]$Session,
        [string]$BaseUrl,
        [int]$OrderId,
        [string]$ReturnTo,
        [string]$Reason
    )

    if ($OrderId -le 0) {
        return ''
    }

    $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'
    $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 = $OrderId
        cancellation_reason = $Reason
        return_to = $ReturnTo
    }

    return Get-FlashText -Html $cancelResult.Content
}

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$stamp = Get-Date -Format 'yyyyMMddHHmmss'
$phone = '087' + $stamp.Substring($stamp.Length - 7)
$plate = 'QM' + $stamp.Substring($stamp.Length - 6)
$results = [ordered]@{}
$bookingOrderId = 0
$quickOrderId = 0
$cancelledQueueReturnTo = 'queue.php?status=cancelled'

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'
    $bookingBranch = Get-FirstSelectValue -Html $bookingPage.Content -Name 'branch_name'
    $bookingServiceId = 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 = "QS Matched $stamp"
        phone = $phone
        plate_number = $plate
        province = 'Bangkok'
        vehicle_type = ''
        brand = 'Toyota'
        model = 'Yaris'
        color = 'Silver'
        branch_name = $bookingBranch
        'service_ids[]' = $bookingServiceId
        total_price = ''
        notes = 'smoke quick service matched seed'
    }
    $bookingOrderId = Get-OrderIdFromResponse -Response $bookingResult
    $results['seed_booking_order_id'] = $bookingOrderId

    $searchResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/search_customer.php?q=$([uri]::EscapeDataString($phone))"
    $searchPayload = $searchResult.Content | ConvertFrom-Json
    Assert-True -Condition ([bool]$searchPayload.success) -Message 'Matched customer search did not return success.'
    Assert-True -Condition (($searchPayload.matches | Measure-Object).Count -gt 0) -Message 'Matched customer search returned no matches.'

    $matchedRecord = $searchPayload.matches | Where-Object { $_.phone -eq $phone } | Select-Object -First 1
    if (-not $matchedRecord) {
        $matchedRecord = $searchPayload.matches | Select-Object -First 1
    }

    Assert-True -Condition ($null -ne $matchedRecord) -Message 'Matched customer record was not found.'
    $results['matched_customer_id'] = $matchedRecord.customerId
    $results['matched_car_id'] = $matchedRecord.carId

    $quickPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/quick_service.php"
    $quickForm = Get-FormState -Html $quickPage.Content -ActionContains '../process/save_quick_service.php'
    $quickBranch = Get-FirstSelectValue -Html $quickPage.Content -Name 'branch_name'
    $quickServiceId = Get-FirstServiceId -Html $quickPage.Content

    $quickResult = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/save_quick_service.php" -Method 'POST' -Body @{
        csrf_token = $quickForm['csrf_token']
        customer_mode = 'matched'
        customer_id = [string]$matchedRecord.customerId
        car_id = [string]$matchedRecord.carId
        customer_name = [string]$matchedRecord.customerName
        phone = [string]$matchedRecord.phone
        plate_number = [string]$matchedRecord.plateNumber
        province = [string]$matchedRecord.province
        brand = [string]$matchedRecord.brand
        model = [string]$matchedRecord.model
        color = [string]$matchedRecord.color
        branch_name = $quickBranch
        'service_ids[]' = $quickServiceId
        total_price = ''
        payment_method = 'cash'
        received_amount = ''
        notes = 'smoke quick service matched flow'
        submit_action = 'hold'
    }
    $quickOrderId = Get-OrderIdFromResponse -Response $quickResult
    $results['matched_hold_flash'] = Get-FlashText -Html $quickResult.Content
    Assert-NotBlank -Value $results['matched_hold_flash'] -Label 'Matched hold'

    $resumeForm = Get-FormState -Html $quickResult.Content -ActionContains '../process/save_quick_service.php' -RequiredHidden @{
        quick_order_id = $quickOrderId
    }
    Assert-True -Condition ($resumeForm['customer_id'] -eq [string]$matchedRecord.customerId) -Message 'Matched customer_id did not persist into Quick Service form.'
    Assert-True -Condition ($resumeForm['car_id'] -eq [string]$matchedRecord.carId) -Message 'Matched car_id did not persist into Quick Service form.'
    $results['resume_status'] = [int]$quickResult.StatusCode
    $results['quick_order_id'] = $quickOrderId

    if (-not $KeepTestData) {
        $results['quick_cleanup_flash'] = Cancel-Order -Session $session -BaseUrl $BaseUrl -OrderId $quickOrderId -ReturnTo 'quick_service.php' -Reason 'smoke quick service matched cleanup'
        Assert-NotBlank -Value $results['quick_cleanup_flash'] -Label 'Quick cleanup'
        $results['seed_cleanup_flash'] = Cancel-Order -Session $session -BaseUrl $BaseUrl -OrderId $bookingOrderId -ReturnTo $cancelledQueueReturnTo -Reason 'smoke quick service matched seed cleanup'
        Assert-NotBlank -Value $results['seed_cleanup_flash'] -Label 'Seed cleanup'
    }

    $results.GetEnumerator() | ForEach-Object {
        "{0}: {1}" -f $_.Key, $_.Value
    }
} catch {
    if (-not $KeepTestData) {
        try {
            if ($quickOrderId -gt 0) {
                $null = Cancel-Order -Session $session -BaseUrl $BaseUrl -OrderId $quickOrderId -ReturnTo 'quick_service.php' -Reason 'smoke quick service matched cleanup'
            }
        } catch {
        }

        try {
            if ($bookingOrderId -gt 0) {
                $null = Cancel-Order -Session $session -BaseUrl $BaseUrl -OrderId $bookingOrderId -ReturnTo $cancelledQueueReturnTo -Reason 'smoke quick service matched seed cleanup'
            }
        } catch {
        }
    }

    throw
}
