<?php
require __DIR__ . '/db.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

$body = fill_read_json_body();
$formId = $body['formId'] ?? '';
$answers = $body['answers'] ?? null;
if (!$formId || !is_array($answers)) fill_json_response(['ok' => false, 'error' => 'missing_fields'], 400);

try {
    $db = fill_db();
    // Confirm the form exists and is actually published before accepting a submission
    $check = $db->prepare("SELECT id FROM fill_forms WHERE id = :id AND is_published = 1");
    $check->execute([':id' => $formId]);
    if (!$check->fetch()) fill_json_response(['ok' => false, 'error' => 'form_not_available'], 404);

    $stmt = $db->prepare("INSERT INTO fill_responses (form_id, answers_json, respondent_ip)
                           VALUES (:form_id, :answers, :ip)");
    $stmt->execute([
        ':form_id' => $formId,
        ':answers' => json_encode($answers),
        ':ip' => $_SERVER['REMOTE_ADDR'] ?? null,
    ]);
    fill_json_response(['ok' => true]);
} catch (Exception $e) {
    fill_json_response(['ok' => false, 'error' => 'server_error'], 500);
}
