<?php
header('Content-Type: text/plain; charset=utf-8');

// ডাটাবেজ কানেকশন
$conn = mysqli_connect('localhost', 'mfudevlo_batuawallet', 'batua@wallet6602#', 'mfudevlo_batuawalletdb');

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

// অ্যান্ড্রয়েড থেকে আসা ডাটা রিসিভ করা
$mobile  = $_POST['mobile'] ?? '';
$user_id = $_POST['userid'] ?? ''; // অ্যান্ড্রয়েড ভলি থেকে আসা 'user_id'
$new_pin = $_POST['new_pin'] ?? '';

if(empty($mobile) || empty($user_id) || empty($new_pin)) {
    echo "Empty Data Received"; exit;
}

// ১. চেক করুন ইউজার signup_table এ আছে কি না (এখানেuserid কলাম ব্যবহার করা হয়েছে)
$stmt = $conn->prepare("SELECT * FROM signup_table WHERE mobile=? AND userid=?");
$stmt->bind_param("ss", $mobile, $user_id);
$stmt->execute();
$checkUser = $stmt->get_result();

if($checkUser->num_rows > 0) {
    // ২. পেন্ডিং টেবিলে ডাটা সেভ (নিশ্চিত করুন pin_reset_requests টেবিলে userid কলাম আছে)
    $stmt2 = $conn->prepare("INSERT INTO pin_reset_requests (mobile, userid, new_pin, status) VALUES (?, ?, ?, 'pending')");
    $stmt2->bind_param("sss", $mobile, $user_id, $new_pin);
    
    if($stmt2->execute()) {
        $last_id = $conn->insert_id;
        sendTelegramNotification($mobile, $user_id, $last_id);
        echo "Success";
    } else {
        echo "Insert Failed: " . $conn->error;
    }
} else {
    echo "User Not Found";
}

// টেলিগ্রাম মেসেজ পাঠানোর ফাংশন
function sendTelegramNotification($mobile, $userid, $request_id) {
    $botToken = "8324066534:AAFqwLw5b4IVuSIg3k39kOz8ztkeYBY5zRI";
    $chatId = "7690446447";
    $approveUrl = "https://mfudevlop.top/batua/approve_pin.php?id=" . $request_id;

    $message = "🔐 *New PIN Reset Request*\n\n" .
               "📱 Mobile: `$mobile`\n" .
               "🆔 User ID: `$userid`\n" .
               "⏳ Status: Pending Approval";

    $keyboard = ['inline_keyboard' => [[['text' => '✅ Approve & Update', 'url' => $approveUrl]]]];

    $url = "https://api.telegram.org/bot$botToken/sendMessage";
    $postData = [
        'chat_id' => $chatId,
        'text' => $message,
        '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, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}
?>