<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Order.php';
require_once '../../includes/Notification.php';

$auth = new Auth();
$user = $auth->requireAuth();

$order = new Order();
$notification = new Notification();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $cart = $input['cart'] ?? null;

    if (!$cart || empty($cart)) {
        jsonResponse(['success' => false, 'message' => 'Cart is empty'], 400);
    }

    $db = new Database();
    $db->beginTransaction();

    try {
        $created_orders = [];
        // One order per shop in the cart
        foreach ($cart as $shop_id => $shop_data) {
            $order_id = $order->create($user['id'], $shop_id, $shop_data['items']);
            $created_orders[] = $order_id;

            // Notify the shop owner
            $shop_owner_id = $order->getShopOwnerId($shop_id);
            if ($shop_owner_id) {
                $message = "You have a new order (#{$order_id}) from customer {$user['name']}.";
                $notification->create($shop_owner_id, $message, "/shops/{$shop_id}");
            }
        }

        $db->commit();

        jsonResponse([
            'success' => true,
            'message' => 'Order(s) placed successfully!',
            'order_ids' => $created_orders
        ]);

    } catch (Exception $e) {
        $db->rollBack();
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
}
?>