<?php
require __DIR__ . '/db.php';
header('Access-Control-Allow-Origin: *');

$id = $_GET['id'] ?? '';
if (!$id) fill_json_response(['ok' => false, 'error' => 'missing_id'], 400);

try {
    $db = fill_db();
    $stmt = $db->prepare("SELECT id, title, display_mode, thank_you_message, schema_json, is_published
                           FROM fill_forms WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch();
    if (!$row) fill_json_response(['ok' => false, 'error' => 'not_found'], 404);
    if (!$row['is_published']) fill_json_response(['ok' => false, 'error' => 'not_published'], 403);

    $schema = json_decode($row['schema_json'], true);
    fill_json_response([
        'ok' => true,
        'form' => [
            'id' => $row['id'],
            'title' => $row['title'],
            'displayMode' => $row['display_mode'],
            'thankYouMessage' => $row['thank_you_message'],
            'questions' => $schema['questions'] ?? [],
            'stackGroupSize' => $schema['stackGroupSize'] ?? 2,
        ],
    ]);
} catch (Exception $e) {
    fill_json_response(['ok' => false, 'error' => 'server_error'], 500);
}
