<?php
// eventos/app/Views/conteudo.php
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="shortcut icon" href="/static/favicon/favicon.ico">
  <title>Portal Integrador - Mogi Guaçu - Eventos</title>
  
  <!-- External Fonts and Icons -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
  <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css">
  
  <!-- Theme CSS Files -->
  <link href="./assets/css/nucleo-icons.css" rel="stylesheet" />
  <link href="./assets/css/nucleo-svg.css" rel="stylesheet" />
  <link href="./assets/css/font-awesome.css" rel="stylesheet" />
  <link href="./assets/css/argon-design-system.css?v=1.2.2" rel="stylesheet" />
  
  <!-- Leaflet Map -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" 
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
  
  <!-- Custom Styles -->
  <link href="./assets/css/custom-form.css" rel="stylesheet" />
</head>

<body class="profile-page">
  <!-- Background Image -->
  <div id="background-image"></div>

  <!-- Navbar -->
  <nav id="navbar-main" class="navbar navbar-main navbar-expand-lg navbar-transparent navbar-light py-2 mt-2">
    <div class="container">
      <a class="navbar-brand mr-lg-5" href="../index.html">
        <img src="https://digital.mogiguacu.sp.gov.br/wp-content/uploads/2025/07/logo-josi-scaled-278x71.png" alt="Guaçu Digital" style="height: 60px">
      </a>
      <div class="navbar-collapse" id="navbar_global">
        <ul class="navbar-nav align-items-lg-center ml-lg-auto">
          <li class="nav-item">
            <a class="nav-link nav-link-icon" href="https://www.facebook.com/PrefeituradeMogiGuacu/?locale=pt_BR" target="_blank" 
               data-toggle="tooltip" title="Curta no Facebook">
              <i class="fa fa-facebook-square"></i>
              <span class="nav-link-inner--text d-lg-none">Facebook</span>
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link nav-link-icon" href="https://www.instagram.com/prefeituramogiguacu/" target="_blank" 
               data-toggle="tooltip" title="Nos siga no Instagram">
              <i class="fa fa-instagram"></i>
              <span class="nav-link-inner--text d-lg-none">Instagram</span>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <div class="wrapper">
    <!-- Hero Section -->
    <section class="section-profile-cover section-shaped my-0" style="background-color: #1e73be">
      <div class="separator separator-bottom separator-skew">
        <svg x="0" y="0" viewBox="0 0 2560 100" preserveAspectRatio="none" version="1.1" xmlns="http://www.w3.org/2000/svg">
          <polygon class="fill-secondary" points="2560 0 2560 100 0 100"></polygon>
        </svg>
      </div>
    </section>

    <!-- Main Form Section -->
    <section class="section bg-secondary">
      <form class="container" action="../api/send_form" method="post" enctype="multipart/form-data" id="serviceForm">
        <div class="card card-profile shadow mt--200">
          <div class="px-4">

            <div class="container mt-3">
              <div class="row align-items-center">
                <!-- Primeira coluna -->
                <div class="col text-left">
                  <a  href="#" class="btn btn-secondary btn-sm" id="show-dados">Meus Dados</a>
                </div>

                <!-- Segunda coluna -->
                <div class="col text-center">
                  <h3>Eventos</h3>
                </div>

                <!-- Terceira coluna -->
                <div class="col text-right">
                  <a href="./logout" class="btn btn-danger btn-sm">Sair</a>
                </div>
              </div>
            </div>

            <table class="table table-bordered table-hover">
                <colgroup>
                  <col style="width: 15%">
                  <col>
                  <col style="width: 10%">
                  <col style="width: 15%">
                </colgroup>
              <thead class="thead-dark">
                  <tr>
                      <th>Data Final</th>
                      <th>Evento</th>
                      <th>Situação</th>
                      <th></th>
                  </tr>
              </thead>
              <tbody>
                <?php if (empty($events)): ?>
                  <tr>
                    <td colspan="5" class="text-center">Nenhum evento encontrado.</td>
                  </tr>
                <?php endif; ?>
                <?php foreach ($events as $event): ?>
                <tr>
                  <td><?= htmlspecialchars($event['data_fim']) ?></td>
                  <td><?= htmlspecialchars($event['titulo']) ?></td>
                  <td>
                    <?php if ($event['open']): ?>
                      <span class="badge badge-pill badge-success text-uppercase">Aberto</span>
                    <?php else: ?>
                      <span class="badge badge-pill badge-danger text-uppercase">Fechado</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <a href="#" 
                      class="btn btn-primary btn-sm show-event"
                      data-id="<?= htmlspecialchars($event['id']) ?>"
                      data-titulo="<?= htmlspecialchars($event['titulo']) ?>"
                      data-descricao="<?= htmlspecialchars($event['descricao'] ?? '') ?>"
                      data-data_inicio="<?= htmlspecialchars($event['data_inicio'] ?? '') ?>"
                      data-data_fim="<?= htmlspecialchars($event['data_fim'] ?? '') ?>"
                      data-enable="<?= $event['enable'] ? 'Aberto' : 'Fechado' ?>"
                      data-open="<?= $event['open'] ? 'Aberto' : 'Fechado' ?>"
                    >
                      Gerar Ticket
                    </a>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
            
          </div>
        </div>
      </form>
    </section>

    <!-- Footer -->
    <footer class="footer">
      <div class="container">
        <div class="row row-grid align-items-center mb-5">
          <div class="col-lg-6">
            <h3 class="text-primary font-weight-light mb-2">Guaçu Digital</h3>
            <h4 class="mb-0 font-weight-light">Inovação que aproxima</h4>
          </div>
          <div class="col-lg-6 text-lg-right btn-wrapper">
            <a href="https://www.instagram.com/prefeituramogiguacu/"
                    target="_blank"
                    type="button" class="btn btn-icon-only btn-twitter rounded-circle" 
                    data-toggle="tooltip" data-original-title="Siga">
              <span class="btn-inner--icon"><i class="fa fa-twitter"></i></span>
            </a>
            <a href="https://www.facebook.com/PrefeituradeMogiGuacu/?locale=pt_BR"
                    target="_blank"
                    type="button" class="btn-icon-only rounded-circle btn btn-facebook" 
                    data-toggle="tooltip" data-original-title="Curta">
              <span class="btn-inner--icon"><i class="fab fa-facebook"></i></span>
            </a>
          </div>
        </div>
        <hr>
        <div class="row align-items-center justify-content-md-between">
          <div class="col-md-6">
            <div class="copyright">
              &copy; 2025 Secretaria de Tecnologia e Inovação<br>
              Divisão de Tecnologia | STI/DT/CITYHUB/Eventos 1.0.0<br>
              <!--<small id="app-version"></small>-->
            </div>
          </div>
          <div class="col-md-6">
            <ul class="nav nav-footer justify-content-end">
              <li class="nav-item">
                <a href="mailto:dev@mogiguacu.sp.gov.br" class="nav-link" target="_blank">Divisão de Tecnologia</a>
              </li>
              <li class="nav-item">
                <a href="https://digital.mogiguacu.sp.gov.br" class="nav-link" target="_blank">Sobre</a>
              </li>
              <li class="nav-item">
                <a href="https://wiki.mogigguacu.sp.gov.br" class="nav-link" target="_blank">Wiki</a>
              </li>
              <li class="nav-item">
                <a href="https://mogiguacu.sp.gov.br" class="nav-link" target="_blank">Prefeitura</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </footer>
  </div>

    <!-- External Libraries -->
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" 
          integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <style>
    .swal2-fullscreen-container {
      background: #FFFFFF !important
    }
    @media (max-width: 768px) {
      .section-profile-cover {
        height: 135px !important
      }
    }
    @media (max-width: 991.98px) {
      .navbar-collapse {
        display: none !important
      }
    }
    #ticket > p { font-size: 12px !important; }
    #qrcode-container > img { width: 100% }
  </style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const buttons = document.querySelectorAll('.show-event');
  buttons.forEach(btn => {
    btn.addEventListener('click', async function(e) {
      e.preventDefault(); // não vai navegar
      
      const userData = await getUserData();
      
      let unidade = userData.unidade ? `Unidade..........: ${userData.unidade}<br>` : '';
      let cargo   = userData.cargo   ? `Cargo............: ${userData.cargo}<br>` : '';
      let codPessoa = userData.cod_pessoa ? `Código de Pessoa.: ${userData.cod_pessoa}<br>` : '';
      let vinculo = userData.vinculo ? `Vínculo..........: ${userData.vinculo}<br>` : '';

      Swal.fire({
        html: `
        <div id="ticket" style="text-align: left;
          font-family: monospace; line-height: 1.2; padding: 5mm;"
        >
          <p style="font-weight: bold; margin: 0 0 5px 0;">${btn.dataset.titulo}</p>
          <!-- Descrição do Evento -->
          <p style="margin: 0 0 5px 0;">${btn.dataset.descricao}</p>
          <hr style="border: none; border-top: 1px dashed #000; margin: 3px 0;">
          <!-- Datas e Status -->
          <p style="margin: 0 0 3px 0;">
            <strong>Data início......:</strong> ${btn.dataset.data_inicio.split("-").reverse().join("/")}<br>
            <strong>Data fim.........:</strong> ${btn.dataset.data_fim.split("-").reverse().join("/")}<br>
            <strong>Status...........:</strong> ${btn.dataset.open}
          </p>
          <hr style="border: none; border-top: 1px dashed #000; margin: 5px 0;">

          <!-- Dados do Servidor -->
          <p>
          <strong>Servidor.........:</strong> ${userData.nome}<br>
          <strong>RE...............:</strong> ${userData.re}<br>
          <strong>CPF..............:</strong> ${userData.cpf}<br>
                ${unidade}
                ${cargo}
                ${codPessoa}
                ${vinculo}
          <strong>Nascimento.......:</strong> ${userData.nascimento.split("-").reverse().join("/")}<br>
          </p>

          <hr style="border: none; border-top: 1px dashed #000; margin: 3px 0;">
          <!-- QR Code -->
          <div id="qrcode-container" style="text-align: center; margin: 5px 0;"></div>
          <p style="font-size: 10px !important;text-align: center;width: 100%;">STI - Divisão de Tecnologia - CITHUB/Eventos 1.0.0</p>
        </div>
        <button id="genImg" onClick="downloadTicket()" class="btn btn-outline-info btn-sm"><i class="fas fa-download"></i> Baixar Ticket</button>
        <button id="genImg" onClick="shareTicket()" class="btn btn-outline-info btn-sm"><i class="fas fa-share-alt"></i> Compartilhar Ticket</button>
        `,
        showConfirmButton: false
      });
      if (btn.dataset.open === "Aberto") {
        showQrCode(btn.dataset.id);
      } else {
        document.getElementById('qrcode-container').innerHTML = '<p style="color: red; font-weight: bold; font-size: 12px">Evento fechado. Não é possível gerar QR Code.</p>'; 
      }
    });
  });

  const dados = document.querySelector('#show-dados');

  dados.addEventListener('click', async function(e) {
    e.preventDefault(); // não vai navegar

    const userData = await getUserData();

    Swal.fire({
      title: 'Meus Dados',
      html: `
        <div id="ticket" style="text-align: left; font-family: monospace; font-size: 12px; line-height: 1.2; padding: 2mm;">
          <strong>Servidor.........:</strong> ${userData.nome}<br>
          <strong>RE...............:</strong> ${userData.re}<br>
          <strong>CPF..............:</strong> ${userData.cpf}<br>
          <strong>Unidade..........:</strong> ${userData.unidade}<br>
          <strong>Cargo............:</strong> ${userData.cod_cargo}<br>
          <strong>Código de Pessoa.:</strong> ${userData.cod_pessoa}<br>
          <strong>Vínculo..........:</strong> ${userData.vinculo}<br>
          <strong>Nascimento.......:</strong> ${userData.nascimento.split("-").reverse().join("/")}<br>
        </div>
      `,
      showConfirmButton: false
    });
  });
});

async function getUserData() {
  try {
    const response = await fetch('/api/user/dados', {
      headers: {
        'Authorization': 'Token <?=$_SESSION['token'] ?>'
      }
    });

    const data = await response.json();
    if (data.success) {
      return data.data;
    } else {
      return data.errors;
    }
  } catch (error) {
    console.error('Erro ao buscar dados do usuário:', error);
  }
}

async function showQrCode(eventId) {
  try {
    const response = await fetch(`/api/qrcode?id=${eventId}`, {
      headers: {
        'Authorization': 'Token <?=$_SESSION['token'] ?>'
      }
    });

    const data = await response.json();
    const qrCodeContainer = document.getElementById('qrcode-container');
    if (data.success) {
      // Exibe o QR Code
      qrCodeContainer.innerHTML = `<img src="data:image/png;base64,${data.qrcode}" alt="QR Code" />`;
      // document.querySelector('#genImg').style.display = "block";
    } else {
      // Exibe erros
      if (data.errors?.qrcode == "Já computado"){
        data_data = data.data
        const [dia, hora] = new Date(data_data.horario_registro).toISOString().split('T'); 
        retorno = `<br>
          <div class="swal2-icon swal2-info swal2-icon-show" style="display: flex;"><div class="swal2-icon-content">i</div></div>
          ${data.message}
          <div id="ticket" style="text-align: left; font-family: monospace; font-size: 12px; line-height: 1.2; padding: 2mm;">
          <hr style="border: none; border-top: 1px dashed #000; margin: 3px 0;">
          <strong>Retirado por.....:</strong>  ${data_data.retirado_por}<br>
          <strong>Data.............:</strong>  ${dia}<br>
          <strong>Horário..........:</strong>  ${hora}<br>
          <hr style="border: none; border-top: 1px dashed #000; margin: 3px 0;">
          <strong>Timestamp........:</strong>  ${data_data.horario_registro}<br>          
          </div> 
        `;
        qrCodeContainer.innerHTML = retorno;
      } else {
        qrCodeContainer.innerHTML = data.errors;
      }
    }
  } catch (error) {
    console.error('Erro ao buscar QR Code:', error);
  }
}

  function downloadTicket() {
    const ticket = document.getElementById('ticket');

    html2canvas(ticket, { scale: 2 }).then(canvas => {
      // Converte o canvas em imagem
      const imgData = canvas.toDataURL('image/png');

      // Cria um link para download
      const link = document.createElement('a');
      link.href = imgData;
      link.download = 'ticket.png';
      link.click();
    });
  };
  
async function shareTicket() {
    const ticket = document.getElementById('ticket');
    
    try {
        // Gera o canvas com a imagem do ticket
        const canvas = await html2canvas(ticket, { scale: 2 });
        
        // Converte para blob
        const blob = await new Promise(resolve => {
            canvas.toBlob(resolve, 'image/png');
        });
        
        // Verifica se a Web Share API está disponível
        if (navigator.share) {
            try {
                const file = new File([blob], 'ticket.png', { type: 'image/png' });
                
                // Verifica se pode compartilhar arquivos
                if (navigator.canShare && navigator.canShare({ files: [file] })) {
                    await navigator.share({
                        title: 'Meu Ticket',
                        text: 'Confira meu ticket!',
                        files: [file]
                    });
                    console.log('Compartilhado com sucesso!');
                } else {
                    // Tenta compartilhar só com URL (alguns navegadores não suportam files)
                    const imgData = canvas.toDataURL('image/png');
                    
                    // Fallback para download
                    downloadImage(imgData);
                }
            } catch (shareError) {
                // Usuário cancelou o compartilhamento ou erro ao compartilhar
                if (shareError.name !== 'AbortError') {
                    console.log('Erro ao compartilhar, fazendo download...', shareError);
                    const imgData = canvas.toDataURL('image/png');
                    downloadImage(imgData);
                }
            }
        } else {
            // Navegador não suporta Web Share API
            const imgData = canvas.toDataURL('image/png');
            downloadImage(imgData);
        }
    } catch (error) {
        console.error('Erro ao processar a imagem:', error);
        alert('Erro ao processar a imagem. Tente novamente.');
    }
    }
    
    function downloadImage(imgData) {
        const link = document.createElement('a');
        link.href = imgData;
        link.download = 'ticket.png';
        link.click();
        console.log('Download iniciado.');
    }
</script>

</body>
</html>