<?php
// Rest of your code...

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/order_error.log');

if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

try {
    require_once __DIR__ . '/config/db.php';
    require_once __DIR__ . '/config/razorpay.php';

    $input = json_decode(file_get_contents('php://input'), true);

    if (!$input || !isset($input['items']) || !isset($input['totalAmount'])) {
        throw new Exception('Missing required fields: items, totalAmount');
    }

    $items = $input['items'];
    $totalAmount = floatval($input['totalAmount']);
    $shippingAddress = $input['shippingAddress'] ?? [];
    $userId = $_SESSION['user_id'] ?? null;

    // Validate amount
    if ($totalAmount <= 0) {
        throw new Exception('Invalid order amount');
    }

    // Calculate GST (18%)
    $gst = $totalAmount * 0.18;
    $finalAmount = $totalAmount + $gst;

    // Create Razorpay order
    $api = new RazorpayAPI(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET);

    $razorpayOrderData = [
        'amount' => round($finalAmount * 100), // Convert to paise
        'currency' => 'INR',
        'receipt' => 'receipt_' . uniqid(),
        'notes' => [
            'userId' => $userId ?? 'guest',
            'email' => $shippingAddress['email'] ?? ''
        ]
    ];

    $razorpayOrder = $api->order->create($razorpayOrderData);

    if (!isset($razorpayOrder['id'])) {
        throw new Exception('Failed to create Razorpay order');
    }

    // Insert order into database
    $orderQuery = "INSERT INTO orders 
                   (razorpay_order_id, user_id, amount, subtotal, gst, 
                    shipping_address, payment_status, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";

    $orderStmt = $conn->prepare($orderQuery);
    if (!$orderStmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $addressJson = json_encode($shippingAddress);
    $paymentStatus = 'pending';
    $orderId = null;

    $orderStmt->bind_param(
        'sidddss',
        $razorpayOrder['id'],
        $userId,
        $finalAmount,
        $totalAmount,
        $gst,
        $addressJson,
        $paymentStatus
    );

    if (!$orderStmt->execute()) {
        throw new Exception('Failed to save order: ' . $orderStmt->error);
    }

    $orderId = $conn->insert_id;
    $orderStmt->close();

    // Insert order items
    $itemQuery = "INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)";
    $itemStmt = $conn->prepare($itemQuery);
    if (!$itemStmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    foreach ($items as $item) {
        $productId = $item['id'];
        $quantity = intval($item['quantity']);
        $price = floatval($item['price']);

        $itemStmt->bind_param('iidi', $orderId, $productId, $quantity, $price);
        if (!$itemStmt->execute()) {
            error_log('Failed to insert order item: ' . $itemStmt->error);
        }
    }
    $itemStmt->close();

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Order created successfully',
        'orderId' => $orderId,
        'razorpay_order_id' => $razorpayOrder['id'],
        'amount' => $finalAmount,
        'subtotal' => $totalAmount,
        'gst' => $gst
    ]);

} catch (Exception $e) {
    error_log('Create order error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => $e->getMessage()
    ]);
}
?>