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

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
    )

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

        $state = @{}
        $hiddenInputs = [regex]::Matches($form.Groups[2].Value, '<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-True {
    param(
        [bool]$Condition,
        [string]$Message
    )

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

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$stamp = Get-Date -Format 'yyyyMMddHHmmss'
$phone = '088' + $stamp.Substring($stamp.Length - 7)
$plate = 'SC' + $stamp.Substring($stamp.Length - 6)
$createdOrderId = 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'
    $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 Search $stamp"
        phone = $phone
        plate_number = $plate
        province = 'Bangkok'
        vehicle_type = ''
        brand = 'Toyota'
        model = 'Yaris'
        color = 'Silver'
        branch_name = $branchName
        'service_ids[]' = $serviceId
        total_price = ''
        notes = 'smoke customer search'
    }
    $createdOrderId = Get-OrderIdFromResponse -Response $bookingResult

    $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 'Customer search did not return success.'
    Assert-True -Condition (($searchPayload.matches | Measure-Object).Count -gt 0) -Message 'Customer search returned no matches.'

    $firstMatch = $searchPayload.matches[0]
    $propertyNames = @($firstMatch.PSObject.Properties.Name)
    Assert-True -Condition ($propertyNames -contains 'availablePackages') -Message 'Customer search payload did not include availablePackages.'

    $cancelPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/cancel_bill.php?id=$createdOrderId&return_to=$([uri]::EscapeDataString($cancelledQueueReturnTo))"
    $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 customer search cleanup'
        return_to = $cancelledQueueReturnTo
    }

    "search_success: $($searchPayload.success)"
    "match_count: $(($searchPayload.matches | Measure-Object).Count)"
    "first_match_customer_id: $($firstMatch.customerId)"
    "first_match_packages: $(($firstMatch.availablePackages | Measure-Object).Count)"
    "cleanup_flash: $(Get-FlashText -Html $cancelResult.Content)"
} catch {
    if ($createdOrderId -gt 0) {
        try {
            $cleanupCancelPage = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/pages/cancel_bill.php?id=$createdOrderId&return_to=$([uri]::EscapeDataString($cancelledQueueReturnTo))"
            $cleanupForm = Get-FormState -Html $cleanupCancelPage.Content -ActionContains '../process/cancel_bill.php'
            $null = Invoke-FlowRequest -Session $session -Uri "$BaseUrl/process/cancel_bill.php" -Method 'POST' -Body @{
                csrf_token = $cleanupForm['csrf_token']
                submission_token = $cleanupForm['submission_token']
                order_id = $createdOrderId
                cancellation_reason = 'smoke customer search cleanup'
                return_to = $cancelledQueueReturnTo
            }
        } catch {
        }
    }

    throw
}
