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

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

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

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 is empty'], 400);
    }

    try {
        $order_id = $order->createOrder($user['id'], $items);

        // Send notification to shop owner
        $shop_id = $items[0]['shop_id'];
        $shop_data = $shop->getShopById($shop_id);
        if ($shop_data && $shop_data['owner_id']) {
            $message = "You have a new order (#{$order_id}) from customer {$user['name']}.";
            $notification->create($shop_data['owner_id'], $message, "/shops/{$shop_id}");
        }

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