<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfset payload = {
	"OK": false,
	"ERROR": "",
	"HAS_UPDATE": false,
	"ORDER_STATUS": {},
	"MESSAGE": ""
}>

<cftry>
	<!--- Parse request body --->
	<cfset requestBody = toString(getHttpRequestData().content)>
	<cfset params = deserializeJSON(requestBody)>

	<!--- Validate required parameters --->
	<cfif not structKeyExists(params, "OrderID")>
		<cfset payload.ERROR = "OrderID is required">
		<cfabort>
	</cfif>

	<cfif not structKeyExists(params, "LastKnownStatusID")>
		<cfset payload.ERROR = "LastKnownStatusID is required">
		<cfabort>
	</cfif>

	<cfset OrderID = params.OrderID>
	<cfset LastKnownStatusID = params.LastKnownStatusID>

	<!--- Query current order status --->
	<cfquery name="qOrder" datasource="payfrit">
		SELECT
			ID,
			StatusID,
			LastEditedOn,
			ServicePointID,
			BusinessID,
			UserID
		FROM Orders
		WHERE ID = <cfqueryparam value="#OrderID#" cfsqltype="cf_sql_integer">
		  AND StatusID != <cfqueryparam value="7" cfsqltype="cf_sql_integer">
	</cfquery>

	<cfif qOrder.recordCount EQ 0>
		<cfset payload.ERROR = "Order not found or deleted">
		<cfabort>
	</cfif>

	<!--- Check if status has changed --->
	<cfset currentStatus = qOrder.StatusID>
	<cfset hasUpdate = (currentStatus NEQ LastKnownStatusID)>

	<!--- Build response --->
	<cfset payload.OK = true>
	<cfset payload.HAS_UPDATE = hasUpdate>

	<cfif hasUpdate>
		<!--- Map status ID to human-readable message --->
		<cfswitch expression="#currentStatus#">
			<cfcase value="0">
				<cfset statusName = "Cart">
				<cfset statusMessage = "Your order is in the cart">
			</cfcase>
			<cfcase value="1">
				<cfset statusName = "Submitted">
				<cfset statusMessage = "Your order has been received and is being prepared">
			</cfcase>
			<cfcase value="2">
				<cfset statusName = "Preparing">
				<cfset statusMessage = "Your order is now being prepared">
			</cfcase>
			<cfcase value="3">
				<cfset statusName = "Ready">
				<cfset statusMessage = "Your order is ready for pickup!">
			</cfcase>
			<cfcase value="4">
				<cfset statusName = "Completed">
				<cfset statusMessage = "Thank you! Your order is complete">
			</cfcase>
			<cfdefaultcase>
				<cfset statusName = "Unknown">
				<cfset statusMessage = "Order status updated">
			</cfdefaultcase>
		</cfswitch>

		<cfset payload.ORDER_STATUS = {
			"OrderID": qOrder.ID,
			"StatusID": currentStatus,
			"StatusName": statusName,
			"Message": statusMessage,
			"LastEditedOn": dateFormat(qOrder.LastEditedOn, "yyyy-mm-dd") & " " & timeFormat(qOrder.LastEditedOn, "HH:mm:ss")
		}>

		<cfset payload.MESSAGE = statusMessage>
	<cfelse>
		<cfset payload.MESSAGE = "No status update">
	</cfif>

	<cfcatch>
		<cfset payload.ERROR = "Error checking status: " & cfcatch.message>
		<cfset payload.OK = false>
	</cfcatch>
</cftry>

<!--- Return JSON response --->
<cfcontent type="application/json" reset="true">
<cfoutput>#serializeJSON(payload)#</cfoutput>
