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

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

<cfscript>
/**
 * Get Business Details
 * POST: { BusinessID: int }
 * Returns: { OK: true, BUSINESS: {...} } or { OK: false, ERROR: string }
 */

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 business details
    q = queryExecute("
        SELECT
            BusinessID,
            BusinessName,
            BusinessPhone,
            BusinessStripeAccountID,
            BusinessStripeOnboardingComplete,
            BusinessIsHiring
        FROM Businesses
        WHERE BusinessID = :businessID
    ", { businessID: businessID }, { datasource: "payfrit" });

    if (q.recordCount == 0) {
        response["ERROR"] = "Business not found";
        writeOutput(serializeJSON(response));
        abort;
    }

    // Get address from Addresses table
    qAddr = queryExecute("
        SELECT a.AddressLine1, a.AddressLine2, a.AddressCity, a.AddressZIPCode, s.tt_StateAbbreviation
        FROM Addresses a
        LEFT JOIN tt_States s ON s.tt_StateID = a.AddressStateID
        WHERE a.AddressBusinessID = :businessID AND a.AddressUserID = 0 AND a.AddressIsDeleted = 0
        LIMIT 1
    ", { businessID: businessID }, { datasource: "payfrit" });

    addressStr = "";
    if (qAddr.recordCount > 0) {
        addressParts = [];
        if (len(qAddr.AddressLine1)) arrayAppend(addressParts, qAddr.AddressLine1);
        if (len(qAddr.AddressLine2)) arrayAppend(addressParts, qAddr.AddressLine2);
        cityStateZip = [];
        if (len(qAddr.AddressCity)) arrayAppend(cityStateZip, qAddr.AddressCity);
        if (len(qAddr.tt_StateAbbreviation)) arrayAppend(cityStateZip, qAddr.tt_StateAbbreviation);
        if (len(qAddr.AddressZIPCode)) arrayAppend(cityStateZip, qAddr.AddressZIPCode);
        if (arrayLen(cityStateZip) > 0) arrayAppend(addressParts, arrayToList(cityStateZip, ", "));
        addressStr = arrayToList(addressParts, ", ");
    }

    // Get hours from Hours table
    qHours = queryExecute("
        SELECT h.HoursDayID, h.HoursOpenTime, h.HoursClosingTime, d.tt_DayAbbrev
        FROM Hours h
        JOIN tt_Days d ON d.tt_DayID = h.HoursDayID
        WHERE h.HoursBusinessID = :businessID
        ORDER BY h.HoursDayID
    ", { businessID: businessID }, { datasource: "payfrit" });

    hoursArr = [];
    hoursStr = "";
    if (qHours.recordCount > 0) {
        for (h in qHours) {
            arrayAppend(hoursArr, {
                "day": h.tt_DayAbbrev,
                "dayId": h.HoursDayID,
                "open": timeFormat(h.HoursOpenTime, "h:mm tt"),
                "close": timeFormat(h.HoursClosingTime, "h:mm tt")
            });
        }
        // Build readable hours string (group similar days)
        // Mon-Thu: 11am-10pm, Fri-Sat: 11am-11pm, Sun: 11am-10pm
        hourGroups = {};
        for (h in hoursArr) {
            key = h.open & "-" & h.close;
            if (!structKeyExists(hourGroups, key)) {
                hourGroups[key] = [];
            }
            arrayAppend(hourGroups[key], h.day);
        }
        hourStrParts = [];
        for (key in hourGroups) {
            days = hourGroups[key];
            arrayAppend(hourStrParts, arrayToList(days, ",") & ": " & key);
        }
        hoursStr = arrayToList(hourStrParts, ", ");
    }

    // Build business object
    business = {
        "BusinessID": q.BusinessID,
        "BusinessName": q.BusinessName,
        "BusinessAddress": addressStr,
        "BusinessPhone": q.BusinessPhone,
        "BusinessHours": hoursStr,
        "BusinessHoursDetail": hoursArr,
        "StripeConnected": (len(q.BusinessStripeAccountID) > 0 && q.BusinessStripeOnboardingComplete == 1),
        "IsHiring": q.BusinessIsHiring == 1
    };

    response["OK"] = true;
    response["BUSINESS"] = business;

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

writeOutput(serializeJSON(response));
</cfscript>
