5) jsonError('order_id and rating (1-5) are required'); $order = foodAssertOrderOwnership($orderId, 'customer', $food_passenger_id); if ($order['status'] !== 'delivered') jsonError('Only delivered orders can be rated', 409); if ($order['rating'] !== null) jsonError('Order already rated', 409); $food_con->beginTransaction(); try { $food_con->prepare("UPDATE food_orders SET rating=?, rating_comment=? WHERE id=?") ->execute([$rating, $comment, $orderId]); $food_con->prepare( "UPDATE food_merchants SET rating_avg = ((rating_avg * rating_count) + ?) / (rating_count + 1), rating_count = rating_count + 1 WHERE id=?" )->execute([$rating, $order['merchant_id']]); $food_con->commit(); } catch (Throwable $e) { $food_con->rollBack(); appLog('[FOOD][ORDER][rate] ' . $e->getMessage(), 'ERROR'); jsonError('Failed to save rating', 500); } jsonSuccess(['order_id' => $orderId, 'rating' => $rating]);