<?php
include "conn.php";

$secret = "TRANSFER_SECRET_KEY";

/* VALIDATION */
if (!isset($_GET['sender_id'],$_GET['receiver_id'],$_GET['amount'],$_GET['token'])) {
    exit("INVALID");
}

$sender_id   = intval($_GET['sender_id']);
$receiver_id = intval($_GET['receiver_id']);
$amount      = round(floatval($_GET['amount']), 2);
$token       = $_GET['token'];

$verify = hash_hmac('sha256', "$sender_id|$receiver_id|$amount", $secret);
if ($verify !== $token) {
    exit("UNAUTHORIZED");
}

/* RECEIVER FETCH (BOT STRUCTURE) */
$rq = mysqli_query($conn,"
    SELECT user_id, name, balance, status 
    FROM user_data 
    WHERE user_id='$receiver_id' AND status='active'
");
$r = mysqli_fetch_assoc($rq);

if (!$r) {
    exit("USER NOT FOUND");
}

/* ADD BALANCE */
mysqli_query($conn,"
UPDATE user_data 
SET balance = balance + $amount
WHERE user_id='$receiver_id'
");

/* OPTIONAL: UPDATE SPEND */
mysqli_query($conn,"
UPDATE user_data 
SET spend = spend + $amount
WHERE user_id='$receiver_id'
");

/* TELEGRAM NOTIFY */
$botToken = "BOT_TOKEN";
$msg = "💰 *Balance Received*\n\n".
       "Amount: ₹$amount\n".
       "From User ID: $sender_id";

file_get_contents(
"https://api.telegram.org/bot$botToken/sendMessage?".
"chat_id=$receiver_id&parse_mode=Markdown&text=".urlencode($msg)
);

echo "SUCCESS";
