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

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

// Получаем содержимое запроса (поддерживаем form-data, JSON и urlencoded)
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$data = $_POST;

if (stripos($contentType, 'application/json') !== false) {
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($json)) {
        $data = array_merge($data, $json);
    }
} elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false && empty($_POST)) {
    $raw = file_get_contents('php://input');
    parse_str($raw, $parsed);
    if (is_array($parsed)) {
        $data = array_merge($data, $parsed);
    }
}

// Тип формы (ожидаем 'feedback' или 'newsletter')
$formType = trim($data['form_type'] ?? '');

if (!in_array($formType, ['feedback', 'newsletter'], true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Error bad form type']);
    exit;
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

// Валидация и санитизация по типу формы
$payload = [];

if ($formType === 'feedback') {
    $name = trim($data['name'] ?? '');
    $email = trim($data['email'] ?? '');
    $message = trim($data['message'] ?? '');

    if ($name === '' || $email === '' || $message === '') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error bad feedback data']);
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error']);
        exit;
    }

    // Ограничим длину и уберём теги/переводы строк
    if (mb_strlen($name) > 200) $name = mb_substr($name, 0, 200);
    if (mb_strlen($message) > 5000) $message = mb_substr($message, 0, 5000);

    $name = str_replace(["\r","\n"], [' ', ' '], strip_tags($name));
    $message = str_replace(["\r","\n"], [' ', ' '], strip_tags($message));

    $payload = [
        'name' => $name,
        'email' => $email,
        'message' => $message
    ];
} else { // newsletter
    $email = trim($data['email'] ?? '');
    if ($email === '') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error']);
        exit;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error']);
        exit;
    }
    $payload = ['email' => $email];
}

$file = __DIR__ . '/results.txt';
$record = [
    'ts'   => date('Y-m-d H:i:s'),
    'form' => $formType,
    'ip'   => $ip,
    'ua'   => mb_substr($ua, 0, 400),
    'data' => $payload,
];

$line = json_encode($record, JSON_UNESCAPED_UNICODE) . PHP_EOL;

$ok = @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);

if ($ok === false) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error']);
    exit;
}

// Успешный ответ (единый текст — одинаков для всех JS)
echo json_encode(['success' => true, 'message' => 'Success']);