Files

64 lines
2.4 KiB
PHP

<?php
header('Content-Type: application/json; charset=utf-8');
try {
require __DIR__ . '/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['ok' => false, 'erro' => 'Metodo nao permitido']);
exit;
}
$payload = json_decode(file_get_contents('php://input'), true);
if (!is_array($payload) || !isset($payload['respostas'], $payload['resultado'])) {
http_response_code(400);
echo json_encode(['ok' => false, 'erro' => 'Dados invalidos']);
exit;
}
$pdo->exec(
'CREATE TABLE IF NOT EXISTS diagnosticos (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
nome VARCHAR(150) NULL,
empresa VARCHAR(200) NULL,
email VARCHAR(255) NULL,
telefone VARCHAR(40) NULL,
consent_contact TINYINT(1) NOT NULL DEFAULT 0,
consent_privacy TINYINT(1) NOT NULL DEFAULT 0,
respostas_json LONGTEXT NOT NULL,
resultado_json LONGTEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci'
);
$answers = $payload['respostas'];
$result = $payload['resultado'];
$toJson = static function ($value) {
return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
};
$stmt = $pdo->prepare(
'INSERT INTO diagnosticos
(nome, empresa, email, telefone, consent_contact, consent_privacy, respostas_json, resultado_json)
VALUES
(:nome, :empresa, :email, :telefone, :consent_contact, :consent_privacy, :respostas_json, :resultado_json)'
);
$stmt->execute([
':nome' => $answers['leadNome'] ?? null,
':empresa' => $answers['leadEmpresa'] ?? null,
':email' => $answers['leadEmail'] ?? null,
':telefone' => $answers['leadTel'] ?? null,
':consent_contact' => !empty($answers['consentContact']) ? 1 : 0,
':consent_privacy' => !empty($answers['consentPrivacy']) ? 1 : 0,
':respostas_json' => $toJson($answers),
':resultado_json' => $toJson($result),
]);
echo json_encode(['ok' => true, 'id' => $pdo->lastInsertId()]);
} catch (Throwable $error) {
http_response_code(500);
echo json_encode(['ok' => false, 'erro' => 'Nao foi possivel guardar o diagnostico']);
}