<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// POST /api/customer/orders/place — place a cash-on-delivery order
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

$authUser = requireAuth();
// Support both old token format (user_id) and new format (id)
$authUserId = $authUser['id'] ?? $authUser['user_id'] ?? null;
if (!$authUserId) jsonError('Unauthorized: could not identify user', 401);

$body     = getBody();

$items       = $body['items']       ?? [];
$fulfillment = $body['fulfillment'] ?? 'delivery';
$address     = trim($body['address'] ?? '');
$phone       = trim($body['phone'] ?? '');
$notes       = trim($body['notes']   ?? '');

if (empty($items)) jsonError('No items provided');
if ($fulfillment === 'delivery' && !$address) jsonError('Delivery address is required');

$db    = getDB();
$total = 0.0;

// Fallback to account phone for clients that do not send phone explicitly.
if (!$phone) {
    $pStmt = $db->prepare('SELECT phone FROM users WHERE id = ?');
    $pStmt->execute([$authUserId]);
    $phone = trim((string)($pStmt->fetchColumn() ?? ''));
}
if (!$phone) jsonError('Phone number is required');

// Enrich items + validate stock
$enriched = [];
try {
    $db->beginTransaction();

    foreach ($items as $item) {
        $productId = $item['productId'] ?? null;
        $qty       = (int)($item['quantity'] ?? 1);
        $price     = (float)($item['price']  ?? 0);
        $isCustom  = !$productId || $productId === 'lpg-custom';

        if ($qty < 1) {
            throw new RuntimeException('Invalid quantity provided');
        }

        $productName = $item['productName'] ?? null;
        $category    = $item['category']    ?? null;

        if (!$isCustom) {
            $s = $db->prepare('SELECT name, category, stock FROM products WHERE id = ? FOR UPDATE');
            $s->execute([$productId]);
            $prod = $s->fetch();
            if (!$prod) {
                throw new RuntimeException('Product no longer exists');
            }

            $productName = $prod['name'];
            $category    = $prod['category'];

            // Validate stock for accessories under row lock.
            if ($prod['category'] === 'accessory' && (int)$prod['stock'] < $qty) {
                throw new RuntimeException('Sorry, only ' . (int)$prod['stock'] . ' unit(s) of "' . $prod['name'] . '" available.');
            }
        } else {
            $productId   = null;
            $productName = $productName ?: 'Custom LPG Cylinder';
            $category    = $category    ?: 'lpg';
        }

        $total     += $price * $qty;
        $enriched[] = compact('productId', 'productName', 'category', 'qty', 'price');
    }

    // Create order (always cash-on-delivery).
    $orderId = generateId();
    $db->prepare(
        'INSERT INTO orders (id, user_id, status, total, fulfillment, payment_method, address, phone, notes)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([
        $orderId,
        $authUserId,
        'pending',
        $total,
        $fulfillment,
        'cod',
        $address ?: null,
        $phone,
        $notes   ?: null,
    ]);

    // Create order items + decrement stock.
    foreach ($enriched as $ei) {
        $db->prepare(
            'INSERT INTO order_items (id, order_id, product_id, product_name, category, quantity, price)
             VALUES (?, ?, ?, ?, ?, ?, ?)'
        )->execute([
            generateId(),
            $orderId,
            $ei['productId'],
            $ei['productName'],
            $ei['category'],
            $ei['qty'],
            $ei['price'],
        ]);

        if ($ei['productId'] && $ei['category'] === 'accessory') {
            $db->prepare('UPDATE products SET stock = stock - ? WHERE id = ?')
                ->execute([$ei['qty'], $ei['productId']]);
        }
    }

    $db->commit();
} catch (Throwable $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    jsonError($e->getMessage() ?: 'Failed to place order', 400);
}

// Return created order with items
$stmt = $db->prepare(
    'SELECT o.*, u.name AS customer_name, u.email AS customer_email, u.phone AS customer_phone
     FROM orders o JOIN users u ON u.id = o.user_id WHERE o.id = ?'
);
$stmt->execute([$orderId]);
$order = $stmt->fetch();

$iStmt = $db->prepare('SELECT * FROM order_items WHERE order_id = ?');
$iStmt->execute([$orderId]);
$order['items'] = $iStmt->fetchAll();

jsonResponse($order, 201);
