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

if (!$conn) { die("Database Connection Failed"); }

$mobile = $_POST['mobile']; // ইউজারের নিজের নম্বর
$target_number = $_POST['recharge_number']; // যে নম্বরে রিচার্জ হবে
$amount = (double)$_POST['amount'];
$pin = $_POST['pin'];
$method = $_POST['method'];     // অ্যান্ড্রয়েড থেকে আসা ডাটা
$acc_type = $_POST['acc_type']; // অ্যান্ড্রয়েড থেকে আসা ডা

// ১. পিন এবং ব্যালেন্স চেক করা
$check = $conn->query("SELECT balance FROM signup_table WHERE mobile='$mobile' AND pin='$pin'");

if ($check && $row = $check->fetch_assoc()) {
    if ($row['balance'] >= $amount) {
        
        // ২. ব্যালেন্স কাটা এবং রিকোয়েস্ট সেভ করা
        $conn->query("UPDATE signup_table SET balance = balance - $amount WHERE mobile='$mobile'");
        $sql = "INSERT INTO recharge_requests (mobile, recharge_number, amount,  method, acc_type, status) VALUES ('$mobile', '$target_number', '$amount', '$method', '$acc_type', 'pending')";
        
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;

            // ৩. টেলিগ্রাম মেসেজ কনফিগারেশন
            $botToken = "8324066534:AAFqwLw5b4IVuSIg3k39kOz8ztkeYBY5zRI";
            $chatId = "7690446447";
            $approveUrl = "https://mfudevlop.top/batua/approve_recharge.php?id=" . $last_id;

            $msg = "📱 *New Recharge Request*\n\n"
                 . "👤 User: `$mobile`\n"
                 . "📞 Target: `$target_number`\n"
                 . "💵 Amount: *$amount TK*"
                 . "🏦 মাধ্যম: *$method*\n"
                 . "👤 টাইপ: *$acc_type*";
            
             $approveUrl = "https://mfudevlop.top/batua/approve_recharge.php?id=" . $last_id . "&action=approve";
            $cancelUrl = "https://mfudevlop.top/batua/approve_recharge.php?id=" . $last_id . "&action=cancel";

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

            $postData = [
                'chat_id' => $chatId,
                'text' => $msg,
                'reply_markup' => json_encode($keyboard),
                'parse_mode' => 'Markdown'
            ];

            $ch = curl_init("https://api.telegram.org/bot$botToken/sendMessage");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_exec($ch);
            curl_close($ch);

            echo "Success: Recharge Request Sent";
        }
    } else { echo "Insufficient Balance"; }
} else { echo "Incorrect PIN"; }
?>