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

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

    $title = isset($body['title']) ? trim($body['title']) : null;
    $displayMode = in_array($body['displayMode'] ?? '', ['one_at_a_time','single_page','stack'], true) ? $body['displayMode'] : null;
    $thankYou = $body['thankYouMessage'] ?? null;
    $schema = isset($body['schema']) ? json_encode($body['schema']) : null;
    $isPublished = isset($body['isPublished']) ? (int) !!$body['isPublished'] : null;

    $fields = []; $params = [':id' => $id];
    if ($title !== null) { $fields[] = 'title = :title'; $params[':title'] = $title; }
    if ($displayMode !== null) { $fields[] = 'display_mode = :mode'; $params[':mode'] = $displayMode; }
    if ($thankYou !== null) { $fields[] = 'thank_you_message = :ty'; $params[':ty'] = $thankYou; }
    if ($schema !== null) { $fields[] = 'schema_json = :schema'; $params[':schema'] = $schema; }
    if ($isPublished !== null) { $fields[] = 'is_published = :pub'; $params[':pub'] = $isPublished; }
    if (empty($fields)) fill_json_response(['ok' => true]); // nothing to update

    $sql = "UPDATE fill_forms SET " . implode(', ', $fields) . " WHERE id = :id";
    $db->prepare($sql)->execute($params);
    fill_json_response(['ok' => true]);
} catch (Exception $e) {
    fill_json_response(['ok' => false, 'error' => 'server_error'], 500);
}
