<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php';

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

if (!$data) {
    echo json_encode(["success" => false, "message" => "No input data"]);
    exit;
}

$user_id        = intval($data["user_id"]);
$grand_total    = floatval($data["grand_total"]);
$discount_amount= floatval($data["discount_amount"]);
$delivery_charge= floatval($data["delivery_charge"]);
$final_amount   = floatval($data["final_amount"]);
$referral_bonus = floatval($data["referral_bonus"]); // ✅ from Flutter
$items          = $data["items"]; // array of order items

if (!is_array($items) || count($items) === 0) {
    echo json_encode(["success" => false, "message" => "No order items provided"]);
    exit;
}

// ✅ Generate manual ID
$sqlID = "SELECT id FROM tbl_order ORDER BY id DESC LIMIT 1";
$rID = $conn->query($sqlID);
if ($rID && $rID->num_rows > 0) {
    $rowID = $rID->fetch_assoc();
    $id = (int)$rowID['id'] + 1;
} else {
    $id = 1;
}

// ✅ Insert into tbl_order
$sql = "INSERT INTO tbl_order (id, user_id, total_amount, discount_amount, delivery_charge, final_amount, status, payment_status) 
        VALUES (?, ?, ?, ?, ?, ?, 'Pending', 'Unpaid')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iidddd", $id, $user_id, $grand_total, $discount_amount, $delivery_charge, $final_amount);

if ($stmt->execute()) {
    $order_id = $id; // manual ID

    // ✅ Loop and insert items
    foreach ($items as $item) {
        $product_id  = intval($item["product_id"]);
        $service_id  = intval($item["service_id"]);
        $quantity    = intval($item["quantity"]);
        $unit_price  = floatval($item["unit_price"]);
        $total_price = floatval($item["total_price"]);

        $sqlItem = "INSERT INTO tbl_order_items (order_id, product_id, service_id, quantity, unit_price, total_price) 
                    VALUES (?, ?, ?, ?, ?, ?)";
        $stmtItem = $conn->prepare($sqlItem);
        $stmtItem->bind_param("iiiidd", $order_id, $product_id, $service_id, $quantity, $unit_price, $total_price);

        if (!$stmtItem->execute()) {
            echo json_encode([
                "success" => false,
                "message" => "Failed to save order item",
                "error" => $stmtItem->error,
                "item_data" => $item
            ]);
            exit;
        }
        $stmtItem->close();
    }

    // ✅ Update referral rewards (deduct available, add withdrawn)
    if ($referral_bonus > 0) {
        $sqlRef = "UPDATE tbl_referral_rewards 
                   SET available_balance = available_balance - ?, 
                       withdrawn_balance = withdrawn_balance + ?, 
                       last_updated = NOW()
                   WHERE user_id = ? AND available_balance >= ?";
        $stmtRef = $conn->prepare($sqlRef);
        $stmtRef->bind_param("ddid", $referral_bonus, $referral_bonus, $user_id, $referral_bonus);
        if (!$stmtRef->execute()) {
            echo json_encode([
                "success" => false,
                "message" => "Order saved but failed to update referral rewards",
                "error" => $stmtRef->error
            ]);
            exit;
        }
        $stmtRef->close();
    }

    echo json_encode([
        "success" => true,
        "message" => "Order placed successfully",
        "order_id" => $order_id
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "Failed to save order",
        "error" => $stmt->error
    ]);
}

$conn->close();




/*
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php';

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

if (!$data) {
    echo json_encode(["success" => false, "message" => "No input data"]);
    exit;
}

$user_id = intval($data["user_id"]);
$grand_total = floatval($data["grand_total"]);
$discount_amount = floatval($data["discount_amount"]);
$delivery_charge = floatval($data["delivery_charge"]);
$final_amount = floatval($data["final_amount"]);
$items = $data["items"]; // array of order items

if (!is_array($items) || count($items) === 0) {
    echo json_encode(["success" => false, "message" => "No order items provided"]);
    exit;
}

// ✅ Generate manual ID
$sqlID = "SELECT id FROM tbl_order ORDER BY id DESC LIMIT 1";
$rID = $conn->query($sqlID);
if ($rID && $rID->num_rows > 0) {
    $rowID = $rID->fetch_assoc();
    $id = (int)$rowID['id'] + 1;
} else {
    $id = 1;
}

// ✅ Insert into tbl_order
$sql = "INSERT INTO tbl_order (id, user_id, total_amount, discount_amount, delivery_charge, final_amount, status, payment_status) 
        VALUES (?, ?, ?, ?, ?, ?, 'Pending', 'Unpaid')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iidddd", $id, $user_id, $grand_total, $discount_amount, $delivery_charge, $final_amount);

if ($stmt->execute()) {
    $order_id = $id; // manual ID

    // ✅ Loop and insert items
    foreach ($items as $item) {
        $product_id = intval($item["product_id"]);
        $service_id = intval($item["service_id"]);
        $quantity   = intval($item["quantity"]);
        $unit_price = floatval($item["unit_price"]);
        $total_price = floatval($item["total_price"]);

        $sqlItem = "INSERT INTO tbl_order_items (order_id, product_id, service_id, quantity, unit_price, total_price) 
                    VALUES (?, ?, ?, ?, ?, ?)";
        $stmtItem = $conn->prepare($sqlItem);
        $stmtItem->bind_param("iiiidd", $order_id, $product_id, $service_id, $quantity, $unit_price, $total_price);

        if (!$stmtItem->execute()) {
            echo json_encode([
                "success" => false,
                "message" => "Failed to save order item",
                "error" => $stmtItem->error,
                "item_data" => $item
            ]);
            exit;
        }
        $stmtItem->close();
    }

    echo json_encode(["success" => true, "message" => "Order placed successfully", "order_id" => $order_id]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to save order", "error" => $stmt->error]);
}

$conn->close();
*/
?>

