-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcliente_api.php
More file actions
248 lines (214 loc) · 11.1 KB
/
cliente_api.php
File metadata and controls
248 lines (214 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
<?php
error_reporting(0);
header("Content-Type: application/json; charset=utf-8");
require_once dirname(__FILE__) . "/funcoes_cliente.php";
// CHAVE SECRETA: Apenas pedidos com esta chave serão aceites para salvar o ID do grupo.
define('N8N_SECRET_KEY', 'FestaNoGrupoSegredo-a8b3c4d5e6f7');
// Função para enviar dados para criar o grupo no n8n
function enviarParaN8n($dadosEvento) {
if (empty($dadosEvento['configuracoes_lista']['nomeGrupo']) || empty($dadosEvento['configuracoes_lista']['celularAdminGrupo'])) {
return;
}
$webhookUrl = 'https://n8n-webhook.startingpro.com.br/webhook/07dcf2d0-8943-493f-9fc2-4924a27654cb';
$baseUrl = "https://soulistavip.com.br/teste/sistema_cadastro_eventos/";
$imageUrl = !empty($dadosEvento['arte_topo']) ? $baseUrl . $dadosEvento['arte_topo'] : null;
$payload = json_encode([
'eventoId' => $dadosEvento['id'],
'nome_evento' => $dadosEvento['nome'],
'data_evento' => date('d/m/Y', strtotime($dadosEvento['data'])),
'organizador_email' => $dadosEvento['organizador_email'],
'imagem_url' => $imageUrl,
'configuracoes' => [
'nome_grupo' => $dadosEvento['configuracoes_lista']['nomeGrupo'],
'celular_admin' => $dadosEvento['configuracoes_lista']['celularAdminGrupo'],
'link_google' => $dadosEvento['configuracoes_lista']['linkGoogle'],
'link_instagram' => $dadosEvento['configuracoes_lista']['linkInstagram']
]
]);
$ch = curl_init($webhookUrl);
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_TIMEOUT => 5]);
curl_exec($ch);
curl_close($ch);
}
// Função para notificar o n8n para apagar o grupo
function notificarN8nParaApagarGrupo($groupId) {
if (empty($groupId)) {
return;
}
$webhookUrl = 'https://n8n-webhook.startingpro.com.br/webhook/16d3b478-8c0b-4133-bce5-f0c428b3d09e';
$payload = json_encode(['groupId' => $groupId]);
$ch = curl_init($webhookUrl);
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_TIMEOUT => 5]);
curl_exec($ch);
curl_close($ch);
}
function responder($sucesso, $mensagem, $dados = null) {
$response = ["sucesso" => $sucesso, "mensagem" => $mensagem];
if ($dados) $response = array_merge($response, $dados);
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
}
$isJsonRequest = isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], 'application/json') !== false;
$input = $isJsonRequest ? json_decode(file_get_contents('php://input'), true) : $_POST;
$action = $input['action'] ?? '';
$token = $input['token'] ?? '';
// Ação para salvar o ID do grupo não precisa de token de cliente, mas de uma chave secreta
if ($action !== 'salvar_id_grupo') {
if (empty($token)) {
responder(false, "Token não fornecido");
}
$cliente = obterClientePorToken($token);
if (!$cliente) {
responder(false, "Token inválido");
}
}
switch ($action) {
case 'listar_eventos':
$eventosFile = dirname(__FILE__) . "/eventos_cadastrados.json";
$eventosCliente = [];
if (file_exists($eventosFile)) {
$todosEventos = json_decode(file_get_contents($eventosFile), true);
if (is_array($todosEventos)) {
$eventosCliente = array_filter($todosEventos, fn($e) => ($e['organizador_email'] ?? '') === $cliente['email']);
}
}
$eventosComStats = array_map(function($evento) {
$totalPessoas = 0; $confirmados = 0;
if (($evento['modelo'] ?? '') === 'lista') {
$convidadosFile = dirname(__FILE__) . '/cadastros_lista/' . $evento['id'] . '.json';
if (file_exists($convidadosFile)) {
$convidados = json_decode(file_get_contents($convidadosFile), true) ?? [];
foreach ($convidados as $cadastro) {
if (isset($cadastro['checkin']) && $cadastro['checkin']['status']) $confirmados++;
$totalPessoas++;
if (!empty($cadastro['familia'])) {
foreach ($cadastro['familia'] as $membro) {
if (isset($membro['checkin']) && $membro['checkin']['status']) $confirmados++;
$totalPessoas++;
}
}
}
}
}
$evento['stats'] = ['totalPessoas' => $totalPessoas, 'confirmados' => $confirmados];
return $evento;
}, $eventosCliente);
responder(true, "Eventos carregados.", ["eventos" => array_values($eventosComStats)]);
break;
case 'criar_evento':
if ($cliente['eventos_criados_mes_atual'] >= $cliente['limite_eventos_mensal']) {
responder(false, "Limite de eventos mensal atingido.");
}
$arteTopoPath = null;
if (isset($_FILES['arteTopo']) && $_FILES['arteTopo']['error'] === UPLOAD_ERR_OK) {
$imgDir = dirname(__FILE__) . '/img_eventos/';
if (!is_dir($imgDir)) mkdir($imgDir, 0755, true);
$fileName = uniqid() . '-' . basename($_FILES['arteTopo']['name']);
$targetFile = $imgDir . $fileName;
if (move_uploaded_file($_FILES['arteTopo']['tmp_name'], $targetFile)) {
$arteTopoPath = 'img_eventos/' . $fileName;
} else {
responder(false, "Erro ao carregar a imagem.");
}
}
$eventoId = uniqid('evento_');
$novoEvento = [
"id" => $eventoId,
"nome" => $_POST['nomeEvento'] ?? 'Novo Evento',
"data" => $_POST['dataEvento'] ?? date('Y-m-d'),
"modelo" => $_POST['modeloEvento'] ?? 'lista',
"organizador_email" => $cliente['email'],
"organizador_nome" => empty($_POST['organizadorNome']) ? explode('@', $cliente['email'])[0] : $_POST['organizadorNome'],
"email_contato" => empty($_POST['emailContato']) ? $cliente['email'] : $_POST['emailContato'],
"arte_topo" => $arteTopoPath,
"data_criacao" => date("Y-m-d H:i:s"),
"configuracoes_lista" => [
'quantidade' => $_POST['quantidade'] ?? 100,
'confirmarPagamento' => isset($_POST['confirmarPagamento']),
'confirmarPresenca' => isset($_POST['confirmarPresenca']),
'nomeGrupo' => $_POST['nomeGrupo'] ?? '',
'celularAdminGrupo' => $_POST['celularAdminGrupo'] ?? '',
'exigirCpf' => isset($_POST['exigirCpf']),
'exigirCelular' => isset($_POST['exigirCelular']),
'exigirIdade' => isset($_POST['exigirIdade']),
'responsavelFamilia' => isset($_POST['responsavelFamilia']),
'linkGoogle' => $_POST['linkGoogle'] ?? '',
'linkInstagram' => $_POST['linkInstagram'] ?? ''
]
];
$eventosFile = dirname(__FILE__) . "/eventos_cadastrados.json";
$eventos = file_exists($eventosFile) ? json_decode(file_get_contents($eventosFile), true) : [];
$eventos[] = $novoEvento;
if (file_put_contents($eventosFile, json_encode($eventos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
atualizarCliente($cliente['email'], ['eventos_criados_mes_atual' => $cliente['eventos_criados_mes_atual'] + 1]);
enviarParaN8n($novoEvento);
responder(true, "Evento criado com sucesso");
} else {
responder(false, "Erro ao salvar evento");
}
break;
case 'apagar_evento':
$eventoId = $input['eventoId'] ?? '';
if (empty($eventoId)) responder(false, "ID do evento não fornecido.");
$eventosFile = dirname(__FILE__) . "/eventos_cadastrados.json";
$eventos = file_exists($eventosFile) ? json_decode(file_get_contents($eventosFile), true) : [];
$eventoParaApagar = null;
$eventosFiltrados = array_filter($eventos, function($evento) use ($eventoId, $cliente, &$eventoParaApagar) {
if (($evento['id'] ?? '') === $eventoId && ($evento['organizador_email'] ?? '') === $cliente['email']) {
$eventoParaApagar = $evento;
return false;
}
return true;
});
if (!$eventoParaApagar) {
responder(false, "Evento não encontrado ou sem permissão para apagar.");
}
if (!empty($eventoParaApagar['grupo_whatsapp_id'])) {
notificarN8nParaApagarGrupo($eventoParaApagar['grupo_whatsapp_id']);
}
file_put_contents($eventosFile, json_encode(array_values($eventosFiltrados), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
if (!empty($eventoParaApagar['arte_topo']) && file_exists(dirname(__FILE__) . '/' . $eventoParaApagar['arte_topo'])) {
unlink(dirname(__FILE__) . '/' . $eventoParaApagar['arte_topo']);
}
$convidadosFile = dirname(__FILE__) . '/cadastros_lista/' . $eventoId . '.json';
if (file_exists($convidadosFile)) unlink($convidadosFile);
responder(true, "Evento apagado com sucesso.");
break;
case 'salvar_id_grupo':
$secretKey = $_SERVER['HTTP_X_N8N_SECRET'] ?? '';
if ($secretKey !== N8N_SECRET_KEY) {
http_response_code(403);
responder(false, "Acesso não autorizado.");
}
$eventoId = $input['eventoId'] ?? '';
$groupId = $input['groupId'] ?? '';
$groupLink = $input['groupLink'] ?? ''; // Novo campo para o link do grupo
if (empty($eventoId) || empty($groupId) || empty($groupLink)) {
responder(false, "Dados insuficientes para salvar o ID e link do grupo.");
}
$eventosFile = dirname(__FILE__) . "/eventos_cadastrados.json";
if (!file_exists($eventosFile)) {
responder(false, "Ficheiro de eventos não encontrado.");
}
$eventos = json_decode(file_get_contents($eventosFile), true);
$eventoEncontrado = false;
foreach ($eventos as $key => $evento) {
if ($evento['id'] === $eventoId) {
$eventos[$key]['grupo_whatsapp_id'] = $groupId;
$eventos[$key]['grupo_whatsapp_link'] = $groupLink; // Salva o link do grupo
$eventoEncontrado = true;
break;
}
}
if ($eventoEncontrado) {
file_put_contents($eventosFile, json_encode($eventos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
responder(true, "ID e link do grupo salvos com sucesso para o evento " . $eventoId);
} else {
responder(false, "Evento com ID " . $eventoId . " não foi encontrado para salvar o grupo.");
}
break;
default:
responder(false, "Ação não reconhecida");
break;
}
?>