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

$raw = json_decode((string)file_get_contents('php://input'), true);
$payload = is_array($raw) ? $raw : $_POST;
$slug = slugify((string)($payload['form'] ?? ''));
$form = $slug ? load_form($slug) : null;

if (!$form) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Sondage introuvable.'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (is_form_closed($form)) {
    echo json_encode(['success' => false, 'closed' => true, 'message' => 'Le sondage est fermé.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$honeypot = trim((string)($payload['honeypot'] ?? ''));
if ($honeypot !== '') {
    echo json_encode(['success' => false, 'message' => 'Tentative détectée.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$cookieName = 'mk_survey_' . $slug;
if (!empty($_COOKIE[$cookieName])) {
    echo json_encode([
        'success' => false,
        'alreadyAnswered' => true,
        'message' => 'Une participation a déjà été enregistrée depuis ce navigateur.'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if (recent_ip_attempts($slug, 3600) >= 2) {
    echo json_encode([
        'success' => false,
        'alreadyAnswered' => true,
        'message' => 'Limite douce atteinte : maximum 2 réponses par IP et par heure.'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$answers = $payload['answers'] ?? [];
if (!is_array($answers)) {
    $answers = [];
}

$prenom = trim((string)($answers['prenom'] ?? ''));
$nom = trim((string)($answers['nom'] ?? ''));
if ($prenom === '' || $nom === '') {
    echo json_encode(['success' => false, 'message' => 'Prénom et nom sont obligatoires.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$qIndex = 1;
foreach ($form['steps'] as $step) {
    $type = $step['type'] ?? '';
    if (!in_array($type, ['multiple', 'text'], true)) {
        continue;
    }
    $key = 'Q' . $qIndex;
    $value = $answers[$key] ?? '';
    if ($type === 'multiple') {
        if (($step['selection'] ?? 'single') === 'multiple') {
            if (!is_array($value) || count(array_filter(array_map('trim', $value))) === 0) {
                echo json_encode(['success' => false, 'message' => 'Merci de répondre à toutes les questions.'], JSON_UNESCAPED_UNICODE);
                exit;
            }
        } else {
            if (trim((string)$value) === '') {
                echo json_encode(['success' => false, 'message' => 'Merci de répondre à toutes les questions.'], JSON_UNESCAPED_UNICODE);
                exit;
            }
        }
    }
    if ($type === 'text' && trim((string)$value) === '') {
        echo json_encode(['success' => false, 'message' => 'Merci de répondre à toutes les questions.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $qIndex++;
}

try {
    save_response($slug, $answers);
    setcookie($cookieName, '1', [
        'expires' => time() + (180 * 24 * 3600),
        'path' => '/',
        'samesite' => 'Lax',
    ]);
    echo json_encode([
        'success' => true,
        'count' => response_count($slug)
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur serveur : ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
