<?php
header('Content-Type: application/json; charset=UTF-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");



// Обрабатываем preflight (CORS)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// === 1️⃣ Читаем JSON-тело ===
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// === 2️⃣ Получаем данные ===

$name = $_POST['name'];
$phone = $_POST['phone'];


// === 3️⃣ Проверка на ошибки ===
$errors = [];
if (empty($name or $phone)) {
    $errors[] = "Контактные данные не указаны";
}
if (!empty($errors)) {
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit;
}

// === 4️⃣ Формируем текст для Telegram ===
$now = date('d.m.Y H:i');
$text = "🧮 *Заказ звонка* ({$now})\n\n";
$text .= "*Имя:* {$name}\n";
$text .= "*Телефон* {$phone}\n";


// === 5️⃣ Отправка в Telegram ===
$botToken = '7277395348:AAGQmdyTT_aJQbkAJYsm0YmZBp8gNrZPSXs';
$chatId = '-1002953198412';
$url = "https://api.telegram.org/bot{$botToken}/sendMessage";

$params = [
    'chat_id' => $chatId,
    'text' => $text,
    'parse_mode' => 'Markdown'
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($params)
    ]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

// === 6️⃣ Ответ клиенту ===
if ($result === false) {
	header('Location: fail.php');
} else {
    header('Location: ok.php');
}
?>
