<?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);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Некорректный JSON']]);
    exit();
}

// 2️⃣ Honeypot-защита
if (!empty($data['website']) && trim($data['website']) !== '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Bot detected']]);
    exit();
}

// 3️⃣ Извлекаем данные из JSON (а не из $_POST!)
$category      = trim($data['category'] ?? '');
$subCategory   = trim($data['subCategory'] ?? '');
$name          = trim($data['name'] ?? '');
$contactMethod = trim($data['contactMethod'] ?? '');
$contactValue  = trim($data['contactValue'] ?? '');
$message       = trim($data['message'] ?? '');

// Дополнительные поля (если используются)
$services      = $data['services'] ?? [];
$form_name     = $data['formName'] ?? $category; // fallback на category
$totalPrice    = (int)($data['totalPrice'] ?? 0);
$messageText   = $message; // или $data['messageText'] ?? ''

// 4️⃣ Валидация
$errors = [];
if (empty($contactValue)) {
    $errors[] = "Контактные данные не указаны";
}
if (empty($name)) {
    $errors[] = "Имя не указано";
}

if (!empty($errors)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit();
}

// 5️⃣ Экранирование HTML для Telegram (parse_mode=HTML)
function escapeHtml($text) {
    return htmlspecialchars($text, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
}

$now = date('d.m.Y H:i');

// Преобразуем услуги в список
if (is_string($services)) {
    $services = array_map('trim', explode(',', $services));
}
$serviceList = '';
if (!empty($services)) {
    $serviceList = implode("\n", array_map(fn($s) => "– " . escapeHtml($s), (array)$services));
}

// 6️⃣ Формируем сообщение
$text = "🧮 <b>Новая заявка со скрытой формы калькулятора</b> ({$now})\n\n";
$text .= "<b>Категория:</b> " . escapeHtml($form_name) . "\n";
if (!empty($subCategory)) {
    $text .= "<b>Подкатегория:</b> " . escapeHtml($subCategory) . "\n";
}
if (!empty($serviceList)) {
    $text .= "<b>Услуги:</b>\n{$serviceList}\n";
}
if ($totalPrice > 0) {
    $text .= "<b>Сумма:</b> ~" . number_format($totalPrice, 0, '', ' ') . " руб.\n\n";
} else {
    $text .= "\n";
}
$text .= "<b>Имя:</b> " . escapeHtml($name) . "\n";
$text .= "<b>Способ связи:</b> " . escapeHtml($contactMethod) . "\n";
$text .= "<b>Контакт:</b> " . escapeHtml($contactValue) . "\n";
if (!empty($messageText)) {
    $text .= "<b>Сообщение:</b> " . escapeHtml($messageText) . "\n";
}
$text .= "━━━━━━━━━━━━━━━━\n<em>{$now}</em>";

// 7️⃣ Отправка в Telegram
$botToken = '7277395348:AAGQmdyTT_aJQbkAJYsm0YmZBp8gNrZPSXs';
$chatId = '-1002953198412';
$url = "https://api.telegram.org/bot{$botToken}/sendMessage"; // ⚠️ Был пробел — удалён!

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

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

$result = file_get_contents($url, false, $context);

// 8️⃣ Ответ клиенту
if ($result === false) {
    error_log("Telegram send failed: " . $text);
    echo json_encode(['success' => false, 'errors' => ['Ошибка отправки в Telegram']]);
} else {
    $response = json_decode($result, true);
    if (isset($response['ok']) && $response['ok']) {
        echo json_encode(['success' => true]);
    } else {
        $errorMsg = $response['description'] ?? 'Неизвестная ошибка Telegram';
        error_log("Telegram API error: " . $errorMsg);
        echo json_encode(['success' => false, 'errors' => [$errorMsg]]);
    }
}