<?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️⃣ Получаем данные ===

if (!empty($data['website']) && trim($data['website']) !== '') {
    // Поле заполнено — это бот. Молча игнорируем.
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Bot detected']]);
    exit();
}
$phone      = trim($data['phone'] ?? '');
$city       = trim($data['city'] ?? 'Не указан');
$title      = trim($data['title'] ?? 'Не указан');
$brandName  = trim($data['brandName'] ?? 'Не указан');


$form_name = $data['category'] ?? 'Калькулятор';
$name = $data['name'] ?? 'Не указано';
$contactMethod = $data['contactMethod'] ?? 'Не указан';
$contactValue = $data['contactValue'] ?? 'Не указан';
$messageText = $data['message'] ?? '';
$services = $data['services'] ?? [];
$totalPrice = $data['totalPrice'] ?? 0;

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

// === 4️⃣ Формируем текст для Telegram ===
$now = date('d.m.Y H:i');
$text = "🧮 <b>Новая заявка с калькулятора</b> ({$now})\n\n";
$text .= "<b>Категория:</b> {$form_name}\n";
if (!empty($data['subCategory'])) $text .= "<b>Подкатегория:</b> {$data['subCategory']}\n";
if (!empty($services)) {
    $serviceList = implode("\n", array_map(fn($s) => "– {$s}", $services));
    $text .= "<b>Услуги:</b>\n{$serviceList}\n";
}
$text .= "<b>Сумма:</b> ~{$totalPrice} руб.\n\n";
$text .= "<b>Имя:</b> {$name}\n";
$text .= "<b>Способ связи:</b> {$contactMethod}\n";
$text .= "<b>Контакт:</b> {$contactValue}\n";
if (!empty($messageText)) $text .= "<b>Сообщение:</b> " . htmlspecialchars($messageText, ENT_NOQUOTES, 'UTF-8') . "\n";
$text .= "━━━━━━━━━━━━━━━━\n<em>{$now}</em>";

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

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

$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) {
//     echo json_encode(['success' => false, 'errors' => ['Ошибка отправки в Telegram']]);
// } else {
//     $response = json_decode($result, true);
//     echo json_encode(['success' => $response['ok'] ?? false]);
// }

// === 6️⃣ Дублирование письма на почту ===
$to = "rumta44@ya.ru";
$subject = "Новая заявка с калькулятора";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers .= "From: no-reply@" . $_SERVER['SERVER_NAME'] . "\r\n";

@mail($to, $subject, nl2br($text), $headers);

// === 7️⃣ Ответ клиенту ===
if ($result === false) {
    echo json_encode(['success' => false, 'errors' => ['Ошибка отправки в Telegram']]);
} else {
    $response = json_decode($result, true);
    echo json_encode(['success' => $response['ok'] ?? false]);
}
?>
