home
/
u529748449
/
domains
/
borabilhete.com
/
public_html
/
admin
➕ New
📤 Upload
✎ Editing:
cadastrar_evento.php
← Back
<?php // admin/cadastrar_evento.php session_start(); require_once __DIR__ . '/conexao.php'; require_once __DIR__ . '/auth.php'; error_reporting(E_ALL); ini_set('display_errors', 1); date_default_timezone_set('America/Sao_Paulo'); require_login(['admin','produtor']); if (($_SESSION['role'] ?? '') === 'agente') { header('Location: validar_ingresso.php'); exit; } $role = $_SESSION['role'] ?? 'produtor'; $produtorId = (int)($_SESSION['produtor_id'] ?? 0); if ($produtorId <= 0) { http_response_code(403); exit('Sessão inválida.'); } // ——— helpers ——— function gerarSlug($nome) { $nome = trim($nome); $nome = mb_strtolower($nome, 'UTF-8'); $nome = strtr($nome, [ 'á'=>'a','à'=>'a','ã'=>'a','â'=>'a','ä'=>'a', 'é'=>'e','è'=>'e','ê'=>'e','ë'=>'e', 'í'=>'i','ì'=>'i','î'=>'i','ï'=>'i', 'ó'=>'o','ò'=>'o','õ'=>'o','ô'=>'o','ö'=>'o', 'ú'=>'u','ù'=>'u','û'=>'u','ü'=>'u', 'ñ'=>'n','ç'=>'c' ]); $nome = preg_replace('/[^a-z0-9]+/', '-', $nome); return trim($nome, '-'); } // ——— produtoras disponíveis para este usuário ——— // ADMIN enxerga todas; PRODUTOR enxerga as vinculadas (pivot) + fallback do campo empresa_id. $produtoras = []; if ($role === 'admin') { $rs = $conn->query("SELECT id, nome_fantasia FROM produtoras ORDER BY nome_fantasia"); while ($r = $rs->fetch_assoc()) $produtoras[(int)$r['id']] = $r['nome_fantasia']; } else { // lista via pivot + fallback empresa_id (retrocompatibilidade) $sql = " SELECT p.id, p.nome_fantasia FROM produtoras p WHERE p.id IN ( SELECT COALESCE(pr.empresa_id, 0) FROM produtores pr WHERE pr.id = ? UNION SELECT pp.produtora_id FROM produtores_produtoras pp WHERE pp.produtor_id = ? ) ORDER BY p.nome_fantasia "; $st = $conn->prepare($sql); $st->bind_param('ii', $produtorId, $produtorId); $st->execute(); $res = $st->get_result(); while ($r = $res->fetch_assoc()) $produtoras[(int)$r['id']] = $r['nome_fantasia']; $st->close(); } $flash = ['type'=>null,'msg'=>null]; // ——— POST ——— if ($_SERVER["REQUEST_METHOD"] === "POST") { $nome = trim($_POST["nome"] ?? ''); // agora recebemos separados $dataDia = trim($_POST['data_dia'] ?? ''); // yyyy-mm-dd $dataHora = trim($_POST['data_hora'] ?? ''); // HH:mm // validações simples if ($dataDia === '' || $dataHora === '') { $flash = ['type'=>'err','msg'=>'Informe a data e a hora do evento.']; } elseif ( !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dataDia) || !preg_match('/^\d{2}:\d{2}$/', $dataHora) ) { $flash = ['type'=>'err','msg'=>'Formato inválido de data/hora.']; } else { // monta "YYYY-mm-dd HH:ii:00" $data = $dataDia.' '.$dataHora.':00'; } $local = trim($_POST["local"] ?? ''); $descricao_evento = trim($_POST["descricao_evento"] ?? ''); $produtora_id = (int)($_POST["produtora_id"] ?? 0); // valida produtora escolhida (apenas se ainda não tem erro) if (!$flash['type']) { if ($role !== 'admin' && $produtora_id && !array_key_exists($produtora_id, $produtoras)) { $flash = ['type'=>'err','msg'=>'Produtora selecionada não está vinculada à sua conta.']; } elseif ($produtora_id <= 0) { $flash = ['type'=>'err','msg'=>'Selecione a produtora responsável pelo evento.']; } } // Só prossegue se não houve erro if (!$flash['type']) { $slug = gerarSlug($nome); // uploads $dir_upload = __DIR__ . "/../public/imagens_eventos/"; if (!is_dir($dir_upload)) mkdir($dir_upload, 0755, true); $imagem_topo = $imagem_mapa = ""; if (!empty($_FILES["imagem_topo"]["name"])) { $ext = strtolower(pathinfo($_FILES["imagem_topo"]["name"], PATHINFO_EXTENSION)); $nome_arquivo = "topo_" . time() . ".$ext"; if (move_uploaded_file($_FILES["imagem_topo"]["tmp_name"], $dir_upload.$nome_arquivo)) { $imagem_topo = "imagens_eventos/" . $nome_arquivo; } } if (!empty($_FILES["imagem_mapa"]["name"])) { $ext = strtolower(pathinfo($_FILES["imagem_mapa"]["name"], PATHINFO_EXTENSION)); $nome_arquivo = "mapa_" . time() . ".$ext"; if (move_uploaded_file($_FILES["imagem_mapa"]["tmp_name"], $dir_upload.$nome_arquivo)) { $imagem_mapa = "imagens_eventos/" . $nome_arquivo; } } // insert do evento (agora com produtora_id) $sql_evento = "INSERT INTO eventos (nome, slug, data, local, descricao, imagem_topo, imagem_mapa, produtor_id, produtora_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; $stmt_evento = $conn->prepare($sql_evento); if (!$stmt_evento) { $flash = ['type'=>'err', 'msg'=>"Erro ao preparar INSERT do evento: ".$conn->error]; } else { $stmt_evento->bind_param( "sssssssii", $nome, $slug, $data, $local, $descricao_evento, $imagem_topo, $imagem_mapa, $produtorId, $produtora_id ); if ($stmt_evento->execute()) { $id_evento = $stmt_evento->insert_id; // setores $nomes = $_POST["nome_setor"] ?? []; $precos = $_POST["preco"] ?? []; $quant = $_POST["quantidade"] ?? []; $descricoes = $_POST["descricao_setor"] ?? []; $inicios = $_POST["inicio_vendas"] ?? []; $fins = $_POST["fim_vendas"] ?? []; if (!is_array($nomes)) $nomes = []; $sql_setor = "INSERT INTO setores (id_evento, nome_setor, preco, quantidade_total, descricao, inicio_vendas, fim_vendas) VALUES (?, ?, ?, ?, ?, ?, ?)"; $stmt_setor = $conn->prepare($sql_setor); if ($stmt_setor) { for ($i=0; $i<count($nomes); $i++) { $nomeSetor = trim($nomes[$i] ?? ''); $precoSetor = (float)($precos[$i] ?? 0); $qtdSetor = (int) ($quant[$i] ?? 0); $descSetor = trim($descricoes[$i] ?? ''); $inicio = $inicios[$i] ?? null; $fim = $fins[$i] ?? null; if ($inicio) $inicio = str_replace('T',' ',$inicio) . ':00'; if ($fim) $fim = str_replace('T',' ',$fim) . ':00'; if ($nomeSetor !== '' && $precoSetor > 0 && $qtdSetor > 0) { $stmt_setor->bind_param("isdisss", $id_evento, $nomeSetor, $precoSetor, $qtdSetor, $descSetor, $inicio, $fim); $stmt_setor->execute(); } } $stmt_setor->close(); } // página pública (slug) if (!is_dir(__DIR__ . "/../public/evento")) mkdir(__DIR__ . "/../public/evento", 0755, true); $caminho_pagina = __DIR__ . "/../public/evento/$slug.php"; $conteudo_pagina = "<?php\n\$id_evento = $id_evento;\ninclude __DIR__ . '/../template_evento.php';\n"; file_put_contents($caminho_pagina, $conteudo_pagina); $flash = ['type'=>'ok', 'msg'=>"Evento e setores cadastrados com sucesso! <a href=\"../public/evento/$slug.php\" target=\"_blank\" rel=\"noopener\">Abrir página</a>"]; } else { $flash = ['type'=>'err', 'msg'=>"Erro ao cadastrar evento: ".$conn->error]; } $stmt_evento->close(); } } } ?> <!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Cadastrar Evento</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"> <link rel="stylesheet" href="css/cadastrar_evento.css?v=1"> <link rel="stylesheet" href="../public/css/header.css"> </head> <body> <?php include __DIR__ . '/includes/header_admin.php'; ?> <div class="container"> <?php if (!$produtoras): ?> <div class="card"> <p class="err" style="margin:0 0 6px">Você não tem nenhuma produtora vinculada.</p> <p class="muted" style="margin:0">Peça a um administrador para vincular você a uma produtora ou cadastre uma nova produtora.</p> </div> <?php endif; ?> <?php if ($flash['type']): ?> <div class="card"> <div class="<?= htmlspecialchars($flash['type']) ?>"><?= $flash['msg'] ?></div> </div> <?php endif; ?> <form method="POST" enctype="multipart/form-data"> <!-- Informações do evento --> <div class="card"> <h2>Informações do Evento</h2> <div class="grid-2"> <div class="form-row"> <label class="label">Produtora responsável *</label> <select name="produtora_id" required> <option value="">— selecione —</option> <?php foreach($produtoras as $id=>$nome): ?> <option value="<?= (int)$id ?>" <?= (isset($_POST['produtora_id']) && (int)$_POST['produtora_id']===$id)?'selected':'' ?>> <?= htmlspecialchars($nome) ?> </option> <?php endforeach; ?> </select> <div class="help">O evento ficará vinculado a esta produtora.</div> </div> <div class="form-row"> <label class="label">Nome *</label> <input type="text" name="nome" required value="<?= htmlspecialchars($_POST['nome'] ?? '') ?>"> </div> </div> <div class="grid-2"> <div class="form-row"> <label class="label">Data *</label> <input type="date" name="data_dia" required value="<?= htmlspecialchars($_POST['data_dia'] ?? '') ?>"> </div> <div class="form-row"> <label class="label">Hora *</label> <input type="time" name="data_hora" step="60" required value="<?= htmlspecialchars($_POST['data_hora'] ?? '') ?>"> </div> <div class="form-row"> <label class="label">Local *</label> <input type="text" name="local" required value="<?= htmlspecialchars($_POST['local'] ?? '') ?>"> </div> </div> <div class="form-row"> <label class="label">Descrição</label> <textarea name="descricao_evento"><?= htmlspecialchars($_POST['descricao_evento'] ?? '') ?></textarea> </div> </div> <!-- Imagens --> <div class="card"> <h2>Mídia</h2> <div class="grid-2"> <div class="form-row"> <label class="label">Imagem de topo (proporção 4:5) *</label> <input type="file" name="imagem_topo" accept="image/*" <?= empty($_POST) ? 'required':'' ?>> <div class="help">Será exibida no cabeçalho da página pública.</div> </div> <div class="form-row"> <label class="label">Mapa do evento (opcional)</label> <input type="file" name="imagem_mapa" accept="image/*"> <div class="help">Mostrado no botão “Ver Mapa Evento”.</div> </div> </div> </div> <!-- Setores --> <div class="card"> <h2>Adicionar Setor</h2> <div class="grid-4"> <div class="form-row"> <label class="label">Nome do setor *</label> <input type="text" id="nome_setor"> </div> <div class="form-row"> <label class="label">Preço (R$) *</label> <input type="number" step="0.01" id="preco_setor"> </div> <div class="form-row"> <label class="label">Quantidade *</label> <input type="number" id="quantidade_setor" min="1"> </div> <div class="form-row"> <label class="label">Descrição (opcional)</label> <input type="text" id="descricao_setor"> </div> </div> <div class="grid-4" style="margin-top:10px"> <div class="form-row"> <label class="label">Início — Data *</label> <input type="date" id="inicio_data_setor"> </div> <div class="form-row"> <label class="label">Início — Hora *</label> <input type="time" id="inicio_hora_setor" step="60"> </div> <div class="form-row"> <label class="label">Fim — Data *</label> <input type="date" id="fim_data_setor"> </div> <div class="form-row"> <label class="label">Fim — Hora *</label> <input type="time" id="fim_hora_setor" step="60"> </div> </div> <div class="actions" style="margin-top:10px"> <button type="button" class="btn btn-primary" onclick="confirmarSetor()">Adicionar setor</button> <span class="muted">Os setores adicionados aparecem na tabela abaixo.</span> </div> <h2 style="margin-top:16px">Setores Adicionados</h2> <table class="table"> <thead> <tr> <th>Nome</th> <th>Preço</th> <th>Qtd</th> <th>Descrição</th> <th>Início</th> <th>Fim</th> <th>Ações</th> </tr> </thead> <tbody id="lista_setores"></tbody> </table> </div> <div class="card"> <div class="actions"> <button type="submit" class="btn btn-primary">Cadastrar Evento</button> <a href="index.php" class="btn btn-outline">Voltar ao painel</a> </div> </div> </form> </div> <script> let setores = []; function confirmarSetor() { const nome = document.getElementById("nome_setor").value.trim(); const preco = document.getElementById("preco_setor").value.trim(); const qtd = document.getElementById("quantidade_setor").value.trim(); const desc = document.getElementById("descricao_setor").value.trim(); const iData = document.getElementById("inicio_data_setor").value.trim(); const iHora = document.getElementById("inicio_hora_setor").value.trim(); const fData = document.getElementById("fim_data_setor").value.trim(); const fHora = document.getElementById("fim_hora_setor").value.trim(); if (!iData || !iHora || !fData || !fHora) { alert("Preencha início (data e hora) e fim (data e hora) do setor."); return; } // monta strings "YYYY-MM-DD HH:MM" const inicio = `${iData} ${iHora}`; const fim = `${fData} ${fHora}`; // (opcional) valida se fim > início const iniIso = new Date(`${iData}T${iHora}`); const fimIso = new Date(`${fData}T${fHora}`); if (isFinite(+iniIso) && isFinite(+fimIso) && fimIso <= iniIso) { alert("A data/hora de fim deve ser posterior ao início."); return; } if (!nome || !preco || !qtd || !inicio || !fim) { alert("Preencha todos os campos do setor (nome, preço, quantidade, início e fim)."); return; } setores.push({ nome, preco, qtd, descricao:desc, inicio, fim }); atualizarTabela(); limparCampos(); } function excluirSetor(i){ setores.splice(i,1); atualizarTabela(); } function atualizarTabela(){ const tb = document.getElementById("lista_setores"); tb.innerHTML = ""; setores.forEach((s,i)=>{ tb.innerHTML += ` <tr> <td data-label="Nome"> <input type="hidden" name="nome_setor[]" value="${escapeHtml(s.nome)}"> ${escapeHtml(s.nome)} </td> <td data-label="Preço"> <input type="hidden" name="preco[]" value="${s.preco}">R$ ${Number(s.preco).toFixed(2)} </td> <td data-label="Qtd"> <input type="hidden" name="quantidade[]" value="${s.qtd}">${s.qtd} </td> <td data-label="Descrição"> <input type="hidden" name="descricao_setor[]" value="${escapeHtml(s.descricao || '')}"> ${escapeHtml(s.descricao || '')} </td> <td data-label="Início"> <input type="hidden" name="inicio_vendas[]" value="${s.inicio}">${s.inicio} </td> <td data-label="Fim"> <input type="hidden" name="fim_vendas[]" value="${s.fim}">${s.fim} </td> <td data-label="Ações"> <button type="button" class="btn btn-danger" onclick="excluirSetor(${i})">Excluir</button> </td> </tr> `; }); } function limparCampos(){ document.getElementById("nome_setor").value = ""; document.getElementById("preco_setor").value = ""; document.getElementById("quantidade_setor").value = ""; document.getElementById("descricao_setor").value = ""; document.getElementById("inicio_data_setor").value = ""; document.getElementById("inicio_hora_setor").value = ""; document.getElementById("fim_data_setor").value = ""; document.getElementById("fim_hora_setor").value = ""; } function escapeHtml(s){ return String(s).replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); } </script> </body> </html>
💾 Save Changes
Cancel
📤 Upload File
×
Select File
Upload
Cancel
➕ Create New
×
Type
📄 File
📁 Folder
Name
Create
Cancel
✎ Rename Item
×
Current Name
New Name
Rename
Cancel
🔐 Change Permissions
×
Target File
Permission (e.g., 0755, 0644)
0755
0644
0777
Apply
Cancel