<?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();
$ownerToken = isset($body['ownerToken']) ? trim($body['ownerToken']) : '';
if (!$ownerToken) fill_json_response(['ok' => false, 'error' => 'missing_owner_token'], 400);

$title = isset($body['title']) ? trim($body['title']) : 'Untitled form';
$displayMode = in_array($body['displayMode'] ?? '', ['one_at_a_time','single_page','stack'], true) ? $body['displayMode'] : 'one_at_a_time';
$thankYou = isset($body['thankYouMessage']) ? trim($body['thankYouMessage']) : null;
$schema = isset($body['schema']) ? $body['schema'] : ['questions' => []];

try {
    $db = fill_db();
    $id = fill_random_id();
    $stmt = $db->prepare("INSERT INTO fill_forms (id, owner_token, title, display_mode, thank_you_message, schema_json, is_published)
                           VALUES (:id, :owner, :title, :mode, :ty, :schema, 0)");
    $stmt->execute([
        ':id' => $id,
        ':owner' => $ownerToken,
        ':title' => $title,
        ':mode' => $displayMode,
        ':ty' => $thankYou,
        ':schema' => json_encode($schema),
    ]);
    fill_json_response(['ok' => true, 'id' => $id]);
} catch (Exception $e) {
    fill_json_response(['ok' => false, 'error' => 'server_error'], 500);
}
