<?php  

header('Content-Type: text/plain');  
include 'config.php';  

$product_id = trim($_POST['product_id'] ?? '');  
$user_token = trim($_POST['user_token'] ?? '');  
$topup_uid  = trim($_POST['topup_uid'] ?? '');  

if (empty($product_id) || empty($user_token) || empty($topup_uid)) {  
    echo "All Fields Required";  
    exit();  
}  

$conn->autocommit(false);

try {

    $product_stmt = $conn->prepare(
        "SELECT title, real_price, discount_price FROM topup_list WHERE id = ?"
    );
    $product_stmt->bind_param("i", $product_id);
    $product_stmt->execute();
    $product_result = $product_stmt->get_result();

    if ($product_result->num_rows === 0) {
        echo "Invalid Product ID";
        $conn->rollback();
        exit();
    }

    $product = $product_result->fetch_assoc();
    $product_title  = $product['title'];
    $product_price  = $product['real_price'];
    $discount_price = $product['discount_price'];

    $product_stmt->close();

    // FOR UPDATE -> row lock kore, jate ekshathe duita request 
    // same balance/winning read kore double-deduct korte na pare
    $user_stmt = $conn->prepare(
        "SELECT username, email, balance, winning FROM users WHERE token = ? FOR UPDATE"
    );  
    $user_stmt->bind_param("s", $user_token);  
    $user_stmt->execute();  
    $user_result = $user_stmt->get_result();  

    if ($user_result->num_rows === 0) {  
        echo "Invalid User Token";  
        $conn->rollback();
        exit();  
    }  

    $user = $user_result->fetch_assoc();  
    $username = $user['username'];  
    $email    = $user['email'];  
    $balance  = (float)$user['balance'];  
    $winning  = (float)$user['winning'];  
    $price    = (float)$discount_price;  

    $user_stmt->close();  

    $balance_deducted = 0;
    $winning_deducted = 0;

    if ($balance >= $price) {
        // Sudhu balance theke full price kata jabe
        $balance_deducted = $price;

    } elseif (($balance + $winning) >= $price) {
        // Balance + Winning mile price cover hoy -> duitao theke katbe
        $balance_deducted = $balance;              // balance ja ase full ta kata jabe
        $winning_deducted = $price - $balance;      // baki ta winning theke

    } else {
        echo "Insufficient balance";
        $conn->rollback();
        exit();
    }

    $new_balance = $balance - $balance_deducted;
    $new_winning = $winning - $winning_deducted;

    $update = $conn->prepare(
        "UPDATE users SET balance = ?, winning = ? WHERE token = ?"
    );
    $update->bind_param("dds", $new_balance, $new_winning, $user_token);

    if (!$update->execute()) {
        throw new Exception("Balance update failed: " . $conn->error);
    }
    $update->close();

    $stmt = $conn->prepare(  
        "INSERT INTO topup_orders   
        (product_id, user_token, username, email, product_title, product_price, discount_price, topup_uid, balance_deducted, winning_deducted)  
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"  
    );  
    $stmt->bind_param(  
        "isssssssdd",  
        $product_id,  
        $user_token,  
        $username,  
        $email,  
        $product_title,  
        $product_price,  
        $discount_price,
        $topup_uid,
        $balance_deducted,
        $winning_deducted
    );  

    if (!$stmt->execute()) {
        throw new Exception("Order insert failed: " . $conn->error);
    }
    $stmt->close();

    $conn->commit();
    echo "Order Placed Successfully";

} catch (Exception $e) {
    $conn->rollback();
    echo "Failed To Place Order: " . $e->getMessage();
}

$conn->close();

?>