<?php
require_once __DIR__ . '/../functions.php';
requireAuth();
header('Content-Type: application/json');

$db = db();
$userId = $_SESSION['user_id'];

$cartId = getCartId();
$items = getCartItems();

if (count($items) === 0) {
    echo json_encode(['success' => false, 'message' => 'Your cart is empty.', 'redirect' => '']);
    exit;
}

$subtotal = (float)($_POST['subtotal'] ?? 0);
$taxAmount = (float)($_POST['tax_amount'] ?? 0);
$shippingAmount = (float)($_POST['shipping_amount'] ?? 0);
$discountAmount = (float)($_POST['discount_amount'] ?? 0);
$total = (float)($_POST['total'] ?? 0);
$paymentMethod = $_POST['payment_method'] ?? 'cod';
$razorpayPaymentId = $_POST['razorpay_payment_id'] ?? '';
$razorpayOrderId = $_POST['razorpay_order_id'] ?? '';

$paymentStatus = ($paymentMethod === 'razorpay' && $razorpayPaymentId) ? 'paid' : 'pending';

$orderNumber = generateOrderNumber();

$db->beginTransaction();
try {
    $db->prepare("INSERT INTO orders (user_id, order_number, status, subtotal, tax_amount, shipping_amount, discount_amount, total, payment_method, payment_status, razorpay_order_id, razorpay_payment_id, shipping_name, shipping_phone, shipping_address, shipping_city, shipping_state, shipping_pincode, shipping_country, notes, coupon_id) VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT coupon_id FROM carts WHERE id = ?))")
        ->execute([
            $userId, $orderNumber, $subtotal, $taxAmount, $shippingAmount, $discountAmount, $total,
            $paymentMethod, $paymentStatus, $razorpayOrderId, $razorpayPaymentId,
            $_POST['shipping_name'], $_POST['shipping_phone'], $_POST['shipping_address'],
            $_POST['shipping_city'], $_POST['shipping_state'], $_POST['shipping_pincode'],
            $_POST['shipping_country'] ?? 'India', $_POST['notes'] ?? '', $cartId
        ]);

    $orderId = $db->lastInsertId();

    foreach ($items as $item) {
        $db->prepare("INSERT INTO order_items (order_id, product_id, product_name, product_sku, variant_info, quantity, unit_price, total, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
            ->execute([
                $orderId, $item['product_id'], $item['name'], null,
                $item['variant_value'] ? ($item['variant_type'] . ': ' . $item['variant_value']) : null,
                $item['quantity'], $item['unit_price'], $item['unit_price'] * $item['quantity'],
                $item['variant_image'] ?: $item['image']
            ]);

        $db->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?")->execute([$item['quantity'], $item['product_id']]);
    }

    $db->prepare("DELETE FROM cart_items WHERE cart_id = ?")->execute([$cartId]);
    $db->prepare("UPDATE carts SET coupon_id = NULL, discount_amount = 0 WHERE id = ?")->execute([$cartId]);

    $coupon = getAppliedCoupon();
    if ($coupon) {
        $db->prepare("UPDATE coupons SET used_count = used_count + 1 WHERE id = ?")->execute([$coupon['id']]);
    }

    $db->commit();

    $redirect = BASE_PATH . '/account/order-detail.php?id=' . $orderId;
    echo json_encode(['success' => true, 'message' => 'Order placed successfully! Your order number is ' . $orderNumber, 'redirect' => $redirect]);
    exit;

} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => 'Failed to place order. Please try again.', 'redirect' => '']);
    exit;
}
