<?php
// FINAL SCRIPT: place_order.php (Matching new table schema)

// --- 1. Prevent Network Errors & Set Up ---
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php'; 

header('Content-Type: application/json');

ob_clean();

$response = [];

// --- 2. Validate Connection ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

// --- 3. Validate Required Input ---
$required_fields = ['user_id', 'cart_items', 'subtotal', 'delivery_charge', 'total_price', 'payment_method'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field])) {
        http_response_code(400);
        $response['status'] = 'error';
        $response['message'] = "Required field '{$field}' is missing.";
        echo json_encode($response);
        exit;
    }
}

// --- 4. Assign and Sanitize Data ---
$userId = intval($_POST['user_id']);
$cartItemsJson = $_POST['cart_items'];
$subtotal = floatval($_POST['subtotal']);
$deliveryCharge = floatval($_POST['delivery_charge']);
$totalPrice = floatval($_POST['total_price']);
$paymentMethod = trim($_POST['payment_method']);

// Handle all optional fields safely
$gateway_charge = isset($_POST['gateway_charge']) ? floatval($_POST['gateway_charge']) : 0.0;
$discount = isset($_POST['discount']) ? floatval($_POST['discount']) : 0.0;
$bkash_number = isset($_POST['bkash_number']) ? trim($_POST['bkash_number']) : null;
$bkash_transaction_id = isset($_POST['bkash_transaction_id']) ? trim($_POST['bkash_transaction_id']) : null;

$status = 'Pending'; // Default order status

// Decode the JSON string of cart items into a PHP array
$cartItems = json_decode($cartItemsJson, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($cartItems) || empty($cartItems)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Invalid or empty cart items data provided.';
    echo json_encode($response);
    exit;
}

// --- 5. Use a Database Transaction for Safety ---
$conn->begin_transaction();

try {
    // --- Step A: INSERT into the main 'orders' table ---
    $sql_order = "INSERT INTO orders (user_id, subtotal, delivery_charge, gateway_charge, discount, total_price, payment_method, bkash_number, bkash_transaction_id, status) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt_order = $conn->prepare($sql_order);
    
    // The type string must perfectly match the columns: i(integer), d(double), s(string)
    $stmt_order->bind_param("idddddssss", 
        $userId, 
        $subtotal, 
        $deliveryCharge, 
        $gateway_charge, 
        $discount, 
        $totalPrice, 
        $paymentMethod, 
        $bkash_number, 
        $bkash_transaction_id, 
        $status
    );
    $stmt_order->execute();

    // Get the ID of the order we just created
    $orderId = $conn->insert_id;
    if ($orderId == 0) {
        throw new Exception("Failed to create the main order record.");
    }

    // --- Step B: Loop through cart items and INSERT into 'order_items' ---
    $sql_items = "INSERT INTO order_items (order_id, product_id, product_name, quantity, price) VALUES (?, ?, ?, ?, ?)";
    $stmt_items = $conn->prepare($sql_items);

    foreach ($cartItems as $item) {
        $productId = intval($item['productId']);
        $productName = trim($item['productName']);
        $quantity = intval($item['quantity']);
        $price = floatval($item['productPrice']);
        
        $stmt_items->bind_param("iisid", $orderId, $productId, $productName, $quantity, $price);
        $stmt_items->execute();
    }

    // If all steps were successful, commit the transaction to the database
    $conn->commit();

    // --- Success ---
    $response['status'] = 'success';
    $response['message'] = 'Order placed successfully.';
    $response['order_id'] = $orderId;

} catch (Exception $e) {
    // If any step failed, roll back the entire transaction so no partial data is saved
    $conn->rollback();

    // --- Failure ---
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Failed to place order: ' . $e->getMessage();
}

// --- 6. Final Clean Output ---
echo json_encode($response);
$conn->close();
exit;
?>