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

$auth = new Auth();
$user = $auth->requireAuth(); // The customer placing the order

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

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

    if (empty($items)) {
        jsonResponse(['success' => false, 'message' => 'Cart items are required.'], 400);
    }

    try {
        // Create the order in the database
        $order_id = $order->createOrder($user['id'], $items);

        // Get shop owner to send notification
        // Assumes all items are from the same shop, as per Order::createOrder logic
        $shop_id = $items[0]['shop_id'];
        $shop = new Shop();
        $shop_details = $shop->getShopById($shop_id); // Assumes getShopById exists and returns owner_id

        if ($shop_details && !empty($shop_details['owner_id'])) {
            $message = "You have a new order (#{$order_id}) from customer {$user['name']}.";
            $notification->create($shop_details['owner_id'], $message, "/shop-owner/orders/{$order_id}");
        }

        jsonResponse(['success' => true, 'message' => 'Order placed successfully!', 'order_id' => $order_id]);
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
}
?>