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

$user_mobile = $_POST['user_mobile'];
$bill_no = $_POST['bill_no'];
$bill_type = $_POST['bill_type'];
$amount = $_POST['amount'];
$method = $_POST['method'];
$pin = $_POST['pin'];

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

if ($row = $check->fetch_assoc()) {
    if ($row['balance'] >= $amount) {
        // টাকা কাটা
        $conn->query("UPDATE signup_table SET balance = balance - $amount WHERE mobile='$user_mobile'");
        
        // বিল রিকোয়েস্ট সেভ করা
        $sql = "INSERT INTO pay_bill_requests (user_mobile, bill_no, bill_type, method, amount, status) 
                VALUES ('$user_mobile', '$bill_no', '$bill_type', '$method', '$amount', 'Pending')";
        
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;

            // --- টেলিগ্রাম নোটিফিকেশন সেটআপ ---
            $botToken = "8324066534:AAFqwLw5b4IVuSIg3k39kOz8ztkeYBY5zRI";
            $chatId = "7690446447";
            
            $msg = "🧾 *New Bill Payment Request*\n\n"
                 . "👤 User: `$user_mobile`\n"
                 . "🆔 Bill No: `$bill_no`\n"
                 . "📂 Type: *$bill_type*\n"
                 . "💵 Amount: *$amount TK*\n"
                 . "💳 Method: $method";

            // Approve এবং Cancel URL (আপনার ডোমেইন অনুযায়ী)
            $approveUrl = "https://mfudevlop.top/batua/approve_bill.php?id=$last_id&action=approve";
            $cancelUrl = "https://mfudevlop.top/batua/approve_bill.php?id=$last_id&action=cancel";

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

            $telegramUrl = "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, $telegramUrl);
            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 Bill is submitted!";
        } else {
            echo "Error: Database error!";
        }
    } else {
        echo "Error: পর্যাপ্ত ব্যালেন্স নেই!";
    }
} else {
    echo "Error: ভুল পিন নম্বর!";
}
?>