<?php
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['success' => false, 'message' => 'Method not allowed']);
  exit;
}

$name = htmlspecialchars(trim($_POST['name'] ?? ''), ENT_QUOTES, 'UTF-8');
$phone = htmlspecialchars(trim($_POST['phone'] ?? ''), ENT_QUOTES, 'UTF-8');
$comment = htmlspecialchars(trim($_POST['comment'] ?? ''), ENT_QUOTES, 'UTF-8');

if ($name === '' || $phone === '') {
  http_response_code(422);
  echo json_encode(['success' => false, 'message' => 'Заполните имя и телефон']);
  exit;
}

$to = 'test@site.ru';
$subject = 'Новая заявка с сайта недвижимости';
$message = "Имя: {$name}\nТелефон: {$phone}\nКомментарий: {$comment}";
$headers = "From: no-reply@site.ru\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n";

$sent = mail($to, $subject, $message, $headers);

echo json_encode([
  'success' => $sent,
  'message' => $sent ? 'Заявка отправлена' : 'Ошибка отправки'
]);
