<?php
include 'config.php';

header('Content-Type: text/plain; charset=UTF-8');
$conn->set_charset("utf8mb4");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "Only POST Allowed";
    exit;
}

$token      = trim($_POST['token'] ?? '');
$product_id = intval($_POST['product_id'] ?? 0);
$address    = trim($_POST['address'] ?? '');
$extra_json = trim($_POST['extra_json'] ?? '');

if (empty($token) || empty($product_id) || empty($address)) {
    echo "Token, Product ID and Address Required";
    exit;
}

$user_query = $conn->prepare("SELECT * FROM users WHERE token=? LIMIT 1");
$user_query->bind_param("s", $token);
$user_query->execute();
$user_result = $user_query->get_result();

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

$user = $user_result->fetch_assoc();

$product_query = $conn->prepare("SELECT * FROM products WHERE id=? LIMIT 1");
$product_query->bind_param("i", $product_id);
$product_query->execute();
$product_result = $product_query->get_result();

if ($product_result->num_rows == 0) {
    echo "Product Not Found";
    exit;
}

$product = $product_result->fetch_assoc();

$product_amount = floatval($product['discount']);

$delivery_raw = trim($product['DeliveryFree'] ?? '');
$delivery_amount = 0;

if ($delivery_raw !== '' && preg_match('/(\d+(?:\.\d+)?)/', $delivery_raw, $match)) {
    $delivery_amount = floatval($match[1]);
}

$total_amount = $product_amount + $delivery_amount;

$product_image = $product['image_link'];

$balance = floatval($user['balance']);
$winning = floatval($user['winning']);

$total_money = $balance + $winning;

if ($total_money < $total_amount) {
    echo "Insufficient Balance";
    exit;
}

$need = $total_amount;

if ($balance >= $need) {
    $new_balance = $balance - $need;
    $new_winning = $winning;
} else {
    $remain = $need - $balance;
    $new_balance = 0;
    $new_winning = $winning - $remain;
}

$update_user = $conn->prepare("
UPDATE users
SET balance=?, winning=?
WHERE token=?
");

$update_user->bind_param("dds", $new_balance, $new_winning, $token);
$update_user->execute();

$order_id = "PO" . time() . rand(1000, 9999);

$insert_order = $conn->prepare("
INSERT INTO product_orders
(order_id, user_id, product_id, product_title, product_image, amount, address, extra_json, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
");

$insert_order->bind_param(
    "ssissdss",
    $order_id,
    $token,
    $product['id'],
    $product['title'],
    $product_image,
    $total_amount,
    $address,
    $extra_json
);

if ($insert_order->execute()) {
    echo "Order Successfully";
} else {
    echo "Order Failed";
}
?>