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

<cfscript>
function apiAbort(required struct payload) {
  writeOutput(serializeJSON(payload));
  abort;
}

function getHeader(name) {
  try {
    req = getPageContext().getRequest();
    val = req.getHeader(arguments.name);
    if (!isNull(val)) return trim(val);
  } catch (any e) {
    k = "HTTP_" & ucase(reReplace(arguments.name, "[^A-Za-z0-9]", "_", "all"));
    if (structKeyExists(cgi, k)) return trim(cgi[k]);
  }
  return "";
}

// Get authenticated user
userId = 0;
if (structKeyExists(request, "UserID") && isNumeric(request.UserID) && request.UserID > 0) {
  userId = request.UserID;
} else {
  userToken = getHeader("X-User-Token");
  if (len(userToken)) {
    try {
      qTok = queryTimed(
        "SELECT UserID FROM UserTokens WHERE Token = ? LIMIT 1",
        [{ value = userToken, cfsqltype = "cf_sql_varchar" }],
        { datasource = "payfrit" }
      );
      if (qTok.recordCount EQ 1) {
        userId = qTok.UserID;
      }
    } catch (any e) {}
  }
}

if (userId <= 0) {
  apiAbort({ "OK": false, "ERROR": "not_logged_in", "MESSAGE": "Authentication required" });
}

try {
  // Get user's delivery addresses
  qAddresses = queryTimed("
    SELECT
      a.ID,
      a.IsDefaultDelivery,
      a.Line1,
      a.Line2,
      a.City,
      a.StateID,
      s.Abbreviation as StateAbbreviation,
      s.Name as StateName,
      a.ZIPCode
    FROM Addresses a
    LEFT JOIN tt_States s ON a.StateID = s.ID
    WHERE a.UserID = :userId
      AND (a.BusinessID = 0 OR a.BusinessID IS NULL)
      AND a.AddressTypeID = 2
      AND a.IsDeleted = 0
    ORDER BY a.IsDefaultDelivery DESC, a.ID DESC
  ", {
    userId: { value = userId, cfsqltype = "cf_sql_integer" }
  }, { datasource: "payfrit" });

  addresses = [];
  for (row in qAddresses) {
    arrayAppend(addresses, {
      "AddressID": row.ID,
      "IsDefault": row.IsDefaultDelivery == 1,
      "Line1": row.Line1,
      "Line2": row.Line2 ?: "",
      "City": row.City,
      "StateID": row.StateID,
      "StateAbbr": row.StateAbbreviation ?: "",
      "ZIPCode": row.ZIPCode,
      "DisplayText": row.Line1 & (len(row.Line2) ? ", " & row.Line2 : "") & ", " & row.City & ", " & (row.StateAbbreviation ?: "") & " " & row.ZIPCode
    });
  }

  writeOutput(serializeJSON({
    "OK": true,
    "ADDRESSES": addresses
  }));

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