<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
/**
 * Portal Dashboard Stats
 * POST: { BusinessID: int }
 * Returns: { OK: true, STATS: { ordersToday, revenueToday, pendingOrders, menuItems } }
 */

response = { "OK": false };

try {
    // Get request data
    requestBody = toString(getHttpRequestData().content);

    if (len(requestBody) == 0) {
        response["ERROR"] = "Request body is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    requestData = deserializeJSON(requestBody);
    businessID = val(requestData.BusinessID ?: 0);

    if (businessID == 0) {
        response["ERROR"] = "BusinessID is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    // Get today's date boundaries as strings for MySQL
    todayStart = dateFormat(now(), "yyyy-mm-dd") & " 00:00:00";
    todayEnd = dateFormat(now(), "yyyy-mm-dd") & " 23:59:59";

    // Orders today count
    qOrdersToday = queryExecute("
        SELECT COUNT(*) as cnt
        FROM Orders
        WHERE BusinessID = :businessID
          AND SubmittedOn >= :todayStart
          AND SubmittedOn <= :todayEnd
    ", {
        businessID: businessID,
        todayStart: { value: todayStart, cfsqltype: "cf_sql_varchar" },
        todayEnd: { value: todayEnd, cfsqltype: "cf_sql_varchar" }
    });

    // Revenue today (sum of line items)
    qRevenueToday = queryExecute("
        SELECT COALESCE(SUM(li.Quantity * li.Price), 0) as total
        FROM Orders o
        JOIN OrderLineItems li ON li.OrderID = o.ID
        WHERE o.BusinessID = :businessID
          AND o.SubmittedOn >= :todayStart
          AND o.SubmittedOn <= :todayEnd
          AND o.StatusID >= 1
    ", {
        businessID: businessID,
        todayStart: { value: todayStart, cfsqltype: "cf_sql_varchar" },
        todayEnd: { value: todayEnd, cfsqltype: "cf_sql_varchar" }
    });

    // Pending orders (status 1 = submitted, 2 = preparing)
    qPendingOrders = queryExecute("
        SELECT COUNT(*) as cnt
        FROM Orders
        WHERE BusinessID = :businessID
          AND StatusID IN (1, 2)
    ", { businessID: businessID });

    // Menu items count (active items that have a parent category, excluding categories themselves)
    // Categories are items with ParentItemID = 0 and IsCollapsible = 0
    qMenuItems = queryExecute("
        SELECT COUNT(*) as cnt
        FROM Items
        WHERE BusinessID = :businessID
          AND IsActive = 1
          AND ParentItemID > 0
    ", { businessID: businessID });

    response["OK"] = true;
    response["STATS"] = {
        "ordersToday": qOrdersToday.cnt,
        "revenueToday": qRevenueToday.total,
        "pendingOrders": qPendingOrders.cnt,
        "menuItems": qMenuItems.cnt
    };

} catch (any e) {
    response["ERROR"] = e.message;
}

try{logPerf(0);}catch(any e){}
writeOutput(serializeJSON(response));
</cfscript>
