<?php
if (ob_get_length()) ob_clean();
require_once 'config.php';

checkAccess(['admin', 'programmer', 'board']);

$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data['title']) || !isset($data['fields'])) {
    response(["error" => "Estructura de formulario incompleta"], 400);
}

// Filtro estricto: Si el ID es demasiado largo (JS timestamp), tratarlo como nuevo registro
$formId = null;
if (isset($data['id']) && is_numeric($data['id']) && (int)$data['id'] < 1000000) {
    $formId = (int)$data['id'];
}

try {
    if ($formId) {
        // UPDATE
        $stmt = $pdo->prepare("UPDATE data_forms SET title = ?, description = ?, fields_json = ? WHERE id = ?");
        $stmt->execute([
            $data['title'],
            $data['description'],
            json_encode($data['fields']),
            $formId
        ]);
    } else {
        // INSERT
        $stmt = $pdo->prepare("INSERT INTO data_forms (title, description, fields_json, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([
            $data['title'],
            $data['description'],
            json_encode($data['fields']),
            'Activo'
        ]);
    }
    response(["success" => true, "is_new" => ($formId === null)]);
} catch (PDOException $e) {
    response(["error" => $e->getMessage()], 500);
}
?>