payfrit-api/api/orders/history.php
John Mizerek 1f81d98c52 Initial PHP API migration from CFML
Complete port of all 163 API endpoints from Lucee/CFML to PHP 8.3.
Shared helpers in api/helpers.php (DB, auth, request/response, security).
PDO prepared statements throughout. Same JSON response shapes as CFML.
2026-03-14 14:26:59 -07:00

106 lines
3.3 KiB
PHP

<?php
require_once __DIR__ . '/../helpers.php';
runAuth();
/**
* Order History
* GET: ?limit=20&offset=0
* Returns completed/submitted orders for the authenticated user
*/
global $userId;
if ($userId <= 0) {
apiAbort(['OK' => false, 'ERROR' => 'not_logged_in', 'MESSAGE' => 'Authentication required']);
}
$limit = (int) ($_GET['limit'] ?? 20);
$offset = (int) ($_GET['offset'] ?? 0);
if ($limit < 1) $limit = 20;
if ($limit > 100) $limit = 100;
if ($offset < 0) $offset = 0;
try {
$qOrders = queryTimed("
SELECT
o.ID, o.UUID, o.BusinessID, o.StatusID, o.OrderTypeID,
o.AddedOn, o.LastEditedOn,
b.Name AS BusinessName,
CASE o.OrderTypeID
WHEN 0 THEN 'Undecided'
WHEN 1 THEN 'Dine-In'
WHEN 2 THEN 'Takeaway'
WHEN 3 THEN 'Delivery'
ELSE 'Unknown'
END AS OrderTypeName
FROM Orders o
LEFT JOIN Businesses b ON b.ID = o.BusinessID
WHERE o.UserID = ? AND o.StatusID > 0
ORDER BY o.AddedOn DESC
LIMIT ? OFFSET ?
", [$userId, $limit, $offset]);
$qCount = queryOne("
SELECT COUNT(*) AS TotalCount
FROM Orders
WHERE UserID = ? AND StatusID > 0
", [$userId]);
$orders = [];
foreach ($qOrders as $row) {
$qItems = queryOne("
SELECT COUNT(*) AS ItemCount, SUM(Quantity * Price) AS Subtotal
FROM OrderLineItems
WHERE OrderID = ? AND ParentOrderLineItemID = 0 AND (IsDeleted = 0 OR IsDeleted IS NULL)
", [(int) $row['ID']]);
$itemCount = (int) ($qItems['ItemCount'] ?? 0);
$subtotal = (float) ($qItems['Subtotal'] ?? 0);
$tax = $subtotal * 0.0875;
$total = $subtotal + $tax;
$statusText = match ((int) $row['StatusID']) {
1 => 'Submitted', 2 => 'In Progress', 3 => 'Ready',
4 => 'Completed', 5 => 'Cancelled', default => 'Unknown',
};
$createdAt = '';
if (!empty($row['AddedOn'])) {
$createdAt = toISO8601($row['AddedOn']);
}
$completedAt = '';
if ((int) $row['StatusID'] >= 4 && !empty($row['LastEditedOn'])) {
$completedAt = toISO8601($row['LastEditedOn']);
}
$orders[] = [
'OrderID' => (int) $row['ID'],
'OrderUUID' => $row['UUID'] ?? '',
'BusinessID' => (int) $row['BusinessID'],
'BusinessName' => $row['BusinessName'] ?? 'Unknown',
'OrderTotal' => round($total * 100) / 100,
'OrderStatusID' => (int) $row['StatusID'],
'StatusName' => $statusText,
'OrderTypeID' => (int) $row['OrderTypeID'],
'TypeName' => $row['OrderTypeName'] ?? 'Unknown',
'ItemCount' => $itemCount,
'CreatedAt' => $createdAt,
'CompletedAt' => $completedAt,
];
}
jsonResponse([
'OK' => true,
'ORDERS' => $orders,
'TOTAL_COUNT' => (int) ($qCount['TotalCount'] ?? 0),
]);
} catch (Exception $e) {
jsonResponse([
'OK' => false,
'ERROR' => 'server_error',
'MESSAGE' => 'Failed to load order history',
'DETAIL' => $e->getMessage(),
]);
}