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

$formId = $_GET['formId'] ?? '';
$ownerToken = $_GET['ownerToken'] ?? '';
if (!$formId || !$ownerToken) fill_json_response(['ok' => false, 'error' => 'missing_fields'], 400);

try {
    $db = fill_db();
    $check = $db->prepare("SELECT owner_token, schema_json FROM fill_forms WHERE id = :id");
    $check->execute([':id' => $formId]);
    $form = $check->fetch();
    if (!$form) fill_json_response(['ok' => false, 'error' => 'not_found'], 404);
    if ($form['owner_token'] !== $ownerToken) fill_json_response(['ok' => false, 'error' => 'forbidden'], 403);

    $stmt = $db->prepare("SELECT id, answers_json, submitted_at FROM fill_responses WHERE form_id = :id ORDER BY submitted_at DESC");
    $stmt->execute([':id' => $formId]);
    $rows = $stmt->fetchAll();
    $responses = array_map(function ($r) {
        return [
            'id' => $r['id'],
            'answers' => json_decode($r['answers_json'], true),
            'submittedAt' => $r['submitted_at'],
        ];
    }, $rows);

    fill_json_response(['ok' => true, 'responses' => $responses, 'schema' => json_decode($form['schema_json'], true)]);
} catch (Exception $e) {
    fill_json_response(['ok' => false, 'error' => 'server_error'], 500);
}
