<%
' Auto-generated Controller: OrderApi
' Generated on 7/28/2026 2:56:29 PM
' Generator: generateController.vbs v1.0
'
' Remember to:
'   1. Add to app/controllers/autoload_controllers.asp
'   2. Register in core/lib.ControllerRegistry.asp
'   3. Add routes in public/Default.asp


Class OrderApiController_Class
    Private m_useLayout
    Private m_title

    Private Sub Class_Initialize()
        m_useLayout = False ' this controller returns JSON only, never the shared HTML layout
        m_title = "OrderApi"
    End Sub

    Public Property Get useLayout
        useLayout = m_useLayout
    End Property

    Public Property Let useLayout(v)
        m_useLayout = v
    End Property

    Public Property Get Title
        Title = m_title
    End Property

    Public Property Let Title(v)
        m_title = v
    End Property

    '-------------------------------------------------------------------------------------------------------------------
    ' POST: accept the completed SurveyJS order-details form (as JSON) for the order matching ?token=
    '-------------------------------------------------------------------------------------------------------------------
    Public Sub SubmitOrderDetails()
        Response.ContentType = "application/json"

        If Request.ServerVariables("REQUEST_METHOD") <> "POST" Then
            WriteJsonError "405 Method Not Allowed", "This endpoint only accepts POST."
            Exit Sub
        End If

        Dim token, order
        token = Trim(Request.QueryString("token"))
        Set order = Nothing
        If Len(token) > 0 Then Set order = OrdersRepository().FindByToken(token)

        If order Is Nothing Then
            WriteJsonError "404 Not Found", "Order not found."
            Exit Sub
        End If

        If order("TokenExpiresAt") < Now() Then
            WriteJsonError "410 Gone", "This order link has expired. Please request a new one."
            Exit Sub
        End If


        Dim csrfToken : csrfToken = Request.ServerVariables("HTTP_X_CSRF_TOKEN")
        If Not HTMLSecurity().IsValidAntiCSRFToken("Order.Continue", csrfToken) Then
            WriteJsonError "403 Forbidden", "Your form session expired. Please refresh the page and try again."
            Exit Sub
        End If

        Dim turnstileToken : turnstileToken = Request.ServerVariables("HTTP_X_TURNSTILE_TOKEN")
        If Not VerifyTurnstileToken(turnstileToken, Request.ServerVariables("REMOTE_ADDR")) Then
            WriteJsonError "403 Forbidden", "Verification challenge failed. Please refresh the page and try again."
            Exit Sub
        End If

        Dim answers
        On Error Resume Next
        json().loadJSON GetRawJsonFromRequest()
        If Err.Number <> 0 Then
            Err.Clear
            On Error GoTo 0
            WriteJsonError "400 Bad Request", "Could not read the submitted form data."
            Exit Sub
        End If
        On Error GoTo 0
        Set answers = json().data

        Dim validationError : validationError = ValidateOrderDetailsAnswers(answers)
        If Len(validationError) > 0 Then
            WriteJsonError "400 Bad Request", validationError
            Exit Sub
        End If

        Dim model : Set model = New POBO_OrderDetails

        On Error Resume Next
        MapOrderDetailsAnswers model, answers
        model.SubmittedAt = Now()
        If Err.Number <> 0 Then
            Err.Clear
            On Error GoTo 0
            WriteJsonError "400 Bad Request", "The submitted data could not be processed. Please check your entries and try again."
            Exit Sub
        End If
        On Error GoTo 0

        On Error Resume Next
        OrderDetailsRepository().SaveForOrder order("OrderID"), model
        If Err.Number <> 0 Then
            Err.Clear
            On Error GoTo 0
            WriteJsonError "500 Internal Server Error", "Could not save your order details. Please try again."
            Exit Sub
        End If
        On Error GoTo 0


        ' Best-effort: the order is already safely persisted at this point, so an SMTP hiccup
        ' should not turn a successful submission into a failed one.
        OrderMailer().SendOrderDetailsEmail order, model

        Flash().Success = "Your order has been submitted. We'll be in touch with your quote soon."
        Response.Write "{""success"":true}"
    End Sub

End Class

' Singleton instance
Dim OrderApiController_Class__Singleton
Function OrderApiController()
    If IsEmpty(OrderApiController_Class__Singleton) Then
        Set OrderApiController_Class__Singleton = New OrderApiController_Class
    End If
    Set OrderApiController = OrderApiController_Class__Singleton
End Function
%>






