<?php
$conn = mysqli_connect('localhost', 'mfudevlo_batuawallet', 'batua@wallet6602#', 'mfudevlo_batuawalletdb');

$sender = $_POST['sender_mobile'];
$target = $_POST['target_mobile'];
$amount = $_POST['amount'];
$offer_name = $_POST['offer_name'];
$pin = $_POST['pin'];
$operator = $_POST['operator'];

$check = $conn->query("SELECT balance FROM signup_table WHERE mobile='$sender' AND pin='$pin'");

if ($row = $check->fetch_assoc()) {
    if ($row['balance'] >= $amount) {
        $conn->query("UPDATE signup_table SET balance = balance - $amount WHERE mobile='$sender'");
        
        $sql = "INSERT INTO offer_requests (sender_mobile, target_mobile, offer_name, amount, operator, status) 
                VALUES ('$sender', '$target', '$offer_name', '$amount', '$operator', 'pending')";
        
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;
            
            // টেলিগ্রাম নোটিফিকেশন লজিক
            $botToken = "8324066534:AAFqwLw5b4IVuSIg3k39kOz8ztkeYBY5zRI";
            $chatId = "7690446447";
            
            $msg = "🎁 *New Offer Request*\n\nUser: `$sender` \nTarget: `$target` \nOffer: *$offer_name* \nPrice: *$amount TK*";
            $approveUrl = "https://mfudevlop.top/batua/approve_offer.php?id=$last_id&action=approve";
            $cancelUrl = "https://mfudevlop.top/batua/approve_offer.php?id=$last_id&action=cancel";

            $keyboard = ['inline_keyboard' => [[['text' => '✅ Approve', 'url' => $approveUrl], ['text' => '❌ Cancel', 'url' => $cancelUrl]]]];

            $url = "https://api.telegram.org/bot$botToken/sendMessage";
            $post_data = ['chat_id' => $chatId, 'text' => $msg, 'parse_mode' => 'Markdown', 'reply_markup' => json_encode($keyboard)];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_exec($ch);
            curl_close($ch);
            
            echo "Success: Your order is pending.";
        }
    } else { echo "Error: পর্যাপ্ত ব্যালেন্স নেই!"; }
} else { echo "Error: ভুল পিন!"; }
?>