<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 Settings
 * Returns settings for the currently selected business
 *
 * Requires: request.BusinessID (set by auth middleware)
 */

function apiAbort(obj) {
    writeOutput(serializeJSON(obj));
    abort;
}

if (!structKeyExists(request, "BusinessID") || !isNumeric(request.BusinessID) || request.BusinessID LTE 0) {
    apiAbort({ OK: false, ERROR: "no_business_selected" });
}

try {
    q = queryExecute("
        SELECT
            b.ID,
            b.Name,
            b.TaxRate,
            b.Phone
        FROM Businesses b
        WHERE b.ID = :businessId
        LIMIT 1
    ", { businessId: request.BusinessID }, { datasource: "payfrit" });

    if (q.recordCount == 0) {
        apiAbort({ OK: false, ERROR: "business_not_found" });
    }

    // Get address from Addresses table
    qAddr = queryExecute("
        SELECT a.Line1, a.Line2, a.City, a.ZIPCode, s.Abbreviation AS State
        FROM Addresses a
        LEFT JOIN tt_States s ON s.ID = a.StateID
        WHERE (a.BusinessID = :businessId OR a.ID = (SELECT AddressID FROM Businesses WHERE ID = :businessId))
          AND a.IsDeleted = 0
        LIMIT 1
    ", { businessId: request.BusinessID }, { datasource: "payfrit" });

    addressStr = "";
    addrCity = "";
    addrState = "";
    addrZip = "";
    if (qAddr.recordCount > 0) {
        addressStr = qAddr.Line1 ?: "";
        addrCity = qAddr.City ?: "";
        addrState = qAddr.State ?: "";
        addrZip = qAddr.ZIPCode ?: "";
    }

    // Get owner email from Users table
    qUser = queryExecute("
        SELECT ContactNumber, EmailAddress
        FROM Users
        WHERE ID = (SELECT UserID FROM Businesses WHERE ID = :businessId)
        LIMIT 1
    ", { businessId: request.BusinessID }, { datasource: "payfrit" });

    // Format tax rate as percentage for display (0.0825 -> 8.25)
    taxRateRaw = isNumeric(q.TaxRate) ? q.TaxRate : 0;
    taxRatePercent = taxRateRaw * 100;

    writeOutput(serializeJSON({
        "OK": true,
        "SETTINGS": {
            "BusinessID": q.ID,
            "Name": q.Name,
            "TaxRate": taxRateRaw,
            "TaxRatePercent": taxRatePercent,
            "Address": addressStr,
            "City": addrCity,
            "State": addrState,
            "Zip": addrZip,
            "Phone": q.Phone ?: "",
            "Email": qUser.recordCount > 0 ? (qUser.EmailAddress ?: "") : ""
        }
    }));

} catch (any e) {
    apiAbort({ OK: false, ERROR: "server_error", MESSAGE: e.message });
}
</cfscript>
