<?php
// Inclui o arquivo do sidebar
include 'sidebar.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Cadastro Comunidade</title>
    <!-- Bootstrap -->
    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <!-- NProgress -->
    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">
    <!-- bootstrap-daterangepicker -->
    <link href="../vendors/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet">
    <!-- Custom Theme Style -->
    <link href="../build/css/custom.min.css" rel="stylesheet">
    <style>
        .alert-fixed {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1050;
            display: none;
        }
    </style>
</head>
<body class="nav-md">
<div class="container body">
    <div class="main_container">
        

        <!-- page content -->
        <div class="right_col" role="main">
            <div class="">
                <div class="page-title">
                    <div class="title_left">
                        <h3>Gerenciador de Comunidades</h3>
                    </div>
                    <div class="title_right">
                        <div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
                            <div class="input-group">
                                <input type="text" class="form-control" id="search-input" placeholder="Pesquisar no Banco de Dados...">
                                <span class="input-group-btn">
                                    <button class="btn btn-default" type="button">Buscar!</button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="clearfix"></div>
                <div class="row">
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class="x_panel">
                            <div class="x_title">
                                <h2>Cadastro de comunidade</h2>
                                <ul class="nav navbar-right panel_toolbox">
                                    <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                                    <li class="dropdown">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                                        <ul class="dropdown-menu" role="menu">
                                            <li><a href="#">Settings 1</a></li>
                                            <li><a href="#">Settings 2</a></li>
                                        </ul>
                                    </li>
                                    <li><a class="close-link"><i class="fa fa-close"></i></a></li>
                                </ul>
                                <div class="clearfix"></div>
                            </div>
                            <div class="x_content">
                                <form id="comunidade-form" class="form-horizontal form-label-left" novalidate>
                                    <div class="alert alert-success alert-fixed" id="success-alert">
                                        Comunidade inserida com sucesso!
                                    </div>
                                    <div class="alert alert-danger alert-fixed" id="error-alert">
                                        Erro ao inserir comunidade. O g.us já está cadastrado.
                                    </div>
                                    <div class="item form-group">
                                        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="website_redir">REDIR <span class="required">*</span></label>
                                        <div class="col-md-6 col-sm-6 col-xs-12">
                                            <input type="url" id="website_redir" name="website_redir" required="required" placeholder="https://link_da_landing_page.com/" class="form-control col-md-7 col-xs-12">
                                        </div>
                                    </div>
                                    <div class="item form-group">
                                        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="website_whatsapp">Link Whatsapp <span class="required">*</span></label>
                                        <div class="col-md-6 col-sm-6 col-xs-12">
                                            <input type="url" id="website_whatsapp" name="website_whatsapp" placeholder="https://chat.whatsapp.com/continuacao_do_link" class="form-control col-md-7 col-xs-12">
                                        </div>
                                    </div>
                                    <div class="item form-group">
                                        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Comunidade <span class="required">*</span></label>
                                        <div class="col-md-6 col-sm-6 col-xs-12">
                                            <input id="name" class="form-control col-md-7 col-xs-12" name="name" placeholder="Nome da Comuniade" required="required" type="text">
                                        </div>
                                    </div>
                                    <div class="item form-group">
                                        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="email">@g.us <span class="required">*</span></label>
                                        <div class="col-md-6 col-sm-6 col-xs-12">
                                            <input type="text" id="email" placeholder="00000000000" name="email" required="required" class="form-control col-md-7 col-xs-12">
                                        </div>
                                    </div>
                                    <div class="item form-group">
                                        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="opcoes">Status </label>
                                        <div class="col-md-6 col-sm-6 col-xs-12">
                                            <select id="opcoes" name="opcoes" class="form-control col-md-7 col-xs-12">
                                                <option value="Processar">Processar</option>
                                                <option value="Conectado">Conectado</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="ln_solid"></div>
                                    <div class="form-group">
                                        <div class="col-md-6 col-md-offset-3">
                                            <button type="reset" class="btn btn-primary">Cancel</button>
                                            <button id="send" type="submit" class="btn btn-success">Submit</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
              <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
                  <div class="x_title">
                    <h2>Tabela de comunidades</h2>
                    <button id="send" type="submit" class="btn btn-success">Submit</button>
                    <ul class="nav navbar-right panel_toolbox">
                      <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                      <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                        <ul class="dropdown-menu" role="menu">
                          <li><a href="#">Settings 1</a></li>
                          <li><a href="#">Settings 2</a></li>
                        </ul>
                      </li>
                      <li><a class="close-link"><i class="fa fa-close"></i></a></li>
                    </ul>
                    <div class="clearfix"></div>
                  </div>
                  <div class="x_content">
                    <div class="table-responsive">
                      <form id="comunidadesForm">
                      <table class="table table-striped jambo_table bulk_action">
                        <thead>
                          <tr class="headings">
                            <th>
                              <input type="checkbox" id="check-all" class="flat">
                            </th>
                            <th class="column-title column-nome">Nome</th>
                            <th class="column-title">G.US</th>
                            <th class="column-title">Redir</th>
                            <th class="column-title">Link Whatsapp</th>
                            <th class="column-title">Status </th>
                            <th class="column-title no-link last"><span class="nobr">Ação</span></th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                          // Conexão com o banco de dados
                          $servername = "br386.hostgator.com.br:3306";
                          $username = "onabet10_dashboardattax";
                          $password = "102030Bacon!";
                          $dbname = "onabet10_attaxnetwork";

                          // Cria conexão
                          $conn = new mysqli($servername, $username, $password, $dbname);

                          // Verifica conexão
                          if ($conn->connect_error) {
                              die("Connection failed: " . $conn->connect_error);
                          }

                          // Define o charset para suportar emojis
                          $conn->set_charset("utf8mb4");

                          // Consulta SQL
                          $sql = "SELECT id, nome_comunidade, g_us, dominio, url, status FROM comunidades";
                          $result = $conn->query($sql);

                          // Gera as linhas da tabela
                          if ($result->num_rows > 0) {
                              while($row = $result->fetch_assoc()) {
                                  echo "<tr class='even pointer'>";
                                  echo "<td class='a-center '><input type='checkbox' class='flat' name='table_records'></td>";
                                  echo "<td class='nome_comunidade_view column-nome'>" . htmlspecialchars($row["nome_comunidade"], ENT_QUOTES, 'UTF-8') . "</td>";
                                  echo "<td class='g_us_view'>" . htmlspecialchars($row["g_us"], ENT_QUOTES, 'UTF-8') . "</td>";
                                  echo "<td class='dominio_view'><a href='" . htmlspecialchars($row["dominio"], ENT_QUOTES, 'UTF-8') . "' target='_blank'>" . htmlspecialchars($row["dominio"], ENT_QUOTES, 'UTF-8') . "</a></td>";
                                  echo "<td class='url_view'><a href='" . htmlspecialchars($row["url"], ENT_QUOTES, 'UTF-8') . "' target='_blank'>" . htmlspecialchars($row["url"], ENT_QUOTES, 'UTF-8') . "</a></td>";
                                  echo "<td class='status_view'>" . htmlspecialchars($row["status"], ENT_QUOTES, 'UTF-8') . "</td>";

                                  echo "<td class='nome_comunidade_edit' style='display:none;'><input type='text' name='nome_comunidade[]' value='" . htmlspecialchars($row["nome_comunidade"], ENT_QUOTES, 'UTF-8') . "' disabled></td>";
                                  echo "<td class='g_us_edit' style='display:none;'><input type='text' name='g_us[]' value='" . htmlspecialchars($row["g_us"], ENT_QUOTES, 'UTF-8') . "' disabled></td>";
                                  echo "<td class='dominio_edit' style='display:none;'><input type='text' name='dominio[]' value='" . htmlspecialchars($row["dominio"], ENT_QUOTES, 'UTF-8') . "' disabled></td>";
                                  echo "<td class='url_edit' style='display:none;'><input type='text' name='url[]' value='" . htmlspecialchars($row["url"], ENT_QUOTES, 'UTF-8') . "' disabled></td>";
                                  echo "<td class='status_edit' style='display:none;'>
                                    <select name='status[]' disabled>
                                        <option value='Conectado'" . ($row["status"] == 'Conectado' ? ' selected' : '') . ">Conectado</option>
                                        <option value='Processar'" . ($row["status"] == 'Processar' ? ' selected' : '') . ">Processar</option>
                                    </select>
                                  </td>";
                                  echo "<td class=' '><button type='button' class='btn btn-primary edit-btn'>Editar</button> <button type='button' class='btn btn-success save-btn' data-id='" . $row["id"] . "' style='display:none;'>Salvar</button> <button type='button' class='btn btn-danger delete-btn' data-id='" . $row["id"] . "'>Deletar</button></td>";
                                  echo "</tr>";
                              }
                          } else {
                              echo "<tr><td colspan='7'>Nenhuma comunidade encontrada</td></tr>";
                          }

                          $conn->close();
                          ?>
                        </tbody>
                      </table>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- /page content -->
    </div>
</div>
<!-- AJAX Script -->
<script>
    $(document).ready(function() {
        $('#comunidade-form').on('submit', function(event) {
            event.preventDefault(); // Impede o envio padrão do formulário

            var formData = $(this).serialize(); // Serializa os dados do formulário

            $.ajax({
                type: 'POST',
                url: 'process_form.php',
                data: formData,
                dataType: 'json', // Espera uma resposta JSON
                success: function(response) {
                    if(response.status === 'success') {
                        $('#success-alert').text(response.message).fadeIn().delay(3000).fadeOut();
                    } else {
                        $('#error-alert').text(response.message).fadeIn().delay(3000).fadeOut();
                    }
                },
                error: function() {
                    $('#error-alert').text('Erro ao enviar o formulário.').fadeIn().delay(3000).fadeOut();
                }
            });
        });

        // Função para filtrar a tabela com base no texto de entrada
        $('#search-input').on('keyup', function() {
            var value = $(this).val().toLowerCase();
            $("#comunidadesForm tbody tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });
    });
</script>
<script>
$(document).ready(function(){
    $('.edit-btn').click(function(){
        var row = $(this).closest('tr');
        row.find('.nome_comunidade_view, .g_us_view, .dominio_view, .url_view, .status_view').hide();
        row.find('.nome_comunidade_edit, .g_us_edit, .dominio_edit, .url_edit, .status_edit').show().find('input, select').prop('disabled', false);
        row.find('.edit-btn').hide();
        row.find('.save-btn').show();
    });

    $('.save-btn').click(function(){
        var id = $(this).data('id');
        var row = $(this).closest('tr');
        var nome_comunidade = row.find('input[name="nome_comunidade[]"]').val();
        var g_us = row.find('input[name="g_us[]"]').val();
        var dominio = row.find('input[name="dominio[]"]').val();
        var url = row.find('input[name="url[]"]').val();
        var status = row.find('select[name="status[]"]').val();

        $.ajax({
            url: 'update_comunidade.php',
            type: 'POST',
            data: {
                id: id,
                nome_comunidade: nome_comunidade,
                g_us: g_us,
                dominio: dominio,
                url: url,
                status: status
            },
            success: function(response){
                alert('Dados atualizados com sucesso!');
                row.find('.nome_comunidade_view').text(nome_comunidade).show();
                row.find('.g_us_view').text(g_us).show();
                row.find('.dominio_view').html('<a href="'+ dominio +'" target="_blank">'+ dominio +'</a>').show();
                row.find('.url_view').html('<a href="'+ url +'" target="_blank">'+ url +'</a>').show();
                row.find('.status_view').text(status).show();
                row.find('.nome_comunidade_edit, .g_us_edit, .dominio_edit, .url_edit, .status_edit').hide().find('input, select').prop('disabled', true);
                row.find('.edit-btn').show();
                row.find('.save-btn').hide();
            },
            error: function(){
                alert('Erro ao atualizar os dados.');
            }
        });
    });

    $('.delete-btn').click(function(){
        var id = $(this).data('id');
        var row = $(this).closest('tr');
        if (confirm('Deseja realmente deletar esta comunidade?')) {
            $.ajax({
                url: 'delete_comunidade.php',
                type: 'POST',
                data: { id: id },
                success: function(response){
                    alert('Comunidade deletada com sucesso!');
                    row.remove();
                },
                error: function(){
                    alert('Erro ao deletar a comunidade.');
                }
            });
        }
    });
});
</script>
</body>
</html>
