<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$input = hw_input_json();
$items = $input['items'] ?? [];
$shippingAddress = $input['shipping_address'] ?? null;

if (empty($items) || !is_array($items)) {
    hw_json(['success' => false, 'message' => 'Cart items are required'], 422);
}

try {
    $pdo = hw_db();
    $pdo->beginTransaction();
    
    $totalAmount = 0;
    $orderItems = [];
    
    // Validate items and calculate total
    foreach ($items as $item) {
        $productId = (int)($item['product_id'] ?? 0);
        $quantity = (int)($item['quantity'] ?? 0);
        
        if ($productId <= 0 || $quantity <= 0) {
            throw new Exception('Invalid product or quantity');
        }
        
        // Get product details
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND active = 1");
        $stmt->execute([$productId]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$product) {
            throw new Exception("Product not found: $productId");
        }
        
        if ($product['stock_quantity'] < $quantity) {
            throw new Exception("Insufficient stock for: {$product['name']}");
        }
        
        $itemTotal = $product['price'] * $quantity;
        $totalAmount += $itemTotal;
        
        $orderItems[] = [
            'product_id' => $productId,
            'quantity' => $quantity,
            'price' => $product['price'],
            'name' => $product['name']
        ];
    }
    
    // Create order
    $stmt = $pdo->prepare("
        INSERT INTO orders (user_id, total_amount, shipping_address, payment_status) 
        VALUES (?, ?, ?, 'paid')
    ");
    $stmt->execute([
        (int)$user['sub'],
        $totalAmount,
        $shippingAddress ? json_encode($shippingAddress) : null
    ]);
    $orderId = (int)$pdo->lastInsertId();
    
    // Create order items and update stock
    foreach ($orderItems as $item) {
        // Add order item
        $stmt = $pdo->prepare("
            INSERT INTO order_items (order_id, product_id, quantity, price) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$orderId, $item['product_id'], $item['quantity'], $item['price']]);
        
        // Update stock
        $stmt = $pdo->prepare("
            UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?
        ");
        $stmt->execute([$item['quantity'], $item['product_id']]);
    }
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("order_id", ?, "total", ?, "items", ?))')
        ->execute([(int)$user['sub'], 'order_created', $orderId, $totalAmount, count($orderItems)]);
    
    $pdo->commit();
    
    hw_json([
        'success' => true,
        'message' => 'Order created successfully',
        'order_id' => $orderId,
        'total_amount' => $totalAmount
    ]);
} catch (Throwable $e) {
    $pdo->rollBack();
    hw_json(['success' => false, 'message' => $e->getMessage()], 500);
}