<?php
require_once("inc/protecao-admin.php");

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Administra&ccedil;&atilde;o</title>
  <link rel="stylesheet" href="/inc/materialdesignicons.min.css">
  <link rel="stylesheet" href="/inc/font-awesome.min.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.base.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.addons.css">
  <link rel="stylesheet" href="/inc/theme.css">
  <link rel="shortcut icon" href="/img/favicon.ico">
  <script type="text/javascript" src="/admin/inc/ajax.js"></script>
  <script type="text/javascript" src="/admin/inc/javascript.js"></script>
</head>

<body>
  <div class="container-scroller">
      <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
        <a class="navbar-brand brand-logo" href="/admin/admin-configuracoes"><span>Administra&ccedil;&atilde;o</span></a>
        <a class="navbar-brand brand-logo-mini" href="/admin/admin-configuracoes"><img src="/img/icones/img-icone-logo.png" title="Painel" width="32" height="32" border="0"></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end justify-content-lg-start">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
        <li class="nav-item nav-search d-none d-lg-block">
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text" id="search">
                  <i class="mdi mdi-magnify"></i>
                </span>
              </div>
              <input type="text" class="form-control" id="busca_chave" placeholder="Busca" aria-label="search" aria-describedby="search">
            </div>
          </li>
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item">
            <a class="nav-link" href="/admin/sair"><i class="mdi mdi-logout f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="Sair/logout"></i></a>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
      </div>
    </nav>

    <!-- modal -->                
      <div class="modal fade" id="log-sistema" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body" id="log-sistema-conteudo" style="text-align:center"><img src="/img/ajax-loader.gif" /></div>
            </div>
        </div>
      </div>
      
    <div class="container-fluid page-body-wrapper">      
    <?php require_once("menu-admin.php"); ?>
      <div class="main-panel">
        <div class="content-wrapper">
          <div id="local-status-acoes"><?php echo $_SESSION['status_acao'];unset($_SESSION['status_acao']); ?></div>
          <div class="row">            

            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header><?php echo lang_pagina_streamings_titulo; ?></header>
                                        <div class="card-header-right">
                                            <button type="button" class="btn btn-success" onClick="ligar_streamings();" data-toggle="tooltip" data-placement="bottom" title="<?php echo lang_pagina_streamings_acao_ligar_streamings; ?>"><i class="fa fa-play"></i>Streamings</button>
                                            <button type="button" class="btn btn-success" onClick="ligar_autodjs();" data-toggle="tooltip" data-placement="bottom" title="<?php echo lang_pagina_streamings_acao_ligar_autodjs; ?>"><i class="fa fa-play"></i>AutoDJs</button>
                                            <button type="button" class="btn btn-info" onClick="window.location = '/admin/admin-cadastrar-streaming';"><i class="fa fa-file-plus"></i><?php echo lang_botao_titulo_cadastrar; ?></button>
                                        </div>
                  </div>
                <div class="card-body">
                    <table id="data_table" class="table dataTable no-footer table-hover" role="grid" aria-describedby="data_table_info">
                                                <thead>
                                                    <tr role="row">
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_porta; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_servidor; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_plano; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_uso_ftp; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_status; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo lang_pagina_streamings_responsavel; ?></th>
                                                        <th><?php echo lang_pagina_streamings_acoes; ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
<?php
if(query_string('2') == 'resultado') {
    $query = "SELECT * FROM streamings WHERE porta LIKE '%".query_string('3')."%' OR porta_dj LIKE '%".query_string('3')."%'";
} elseif(query_string('2') == 'resultado-revenda') {
    $query = "SELECT * FROM streamings WHERE codigo_cliente = '".code_decode(query_string('3'),"D")."'";
} elseif(query_string('2') == 'resultado-servidor') {
    $query = "SELECT * FROM streamings WHERE codigo_servidor = '".code_decode(query_string('3'),"D")."'";
} else {
    $query = "SELECT * FROM streamings";
}

$sql = mysqli_query($conexao,"".$query." ORDER by porta ASC");
while ($dados_stm = mysqli_fetch_array($sql)) {

$dados_servidor = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM servidores where codigo = '".$dados_stm["codigo_servidor"]."'"));
$dados_servidor_aacplus = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM servidores where codigo = '".$dados_stm["codigo_servidor_aacplus"]."'"));
$dados_revenda = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM revendas WHERE codigo = '".$dados_stm["codigo_cliente"]."'"));
$total_playlists = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM playlists where codigo_stm = '".$dados_stm["codigo"]."'"));

if($dados_stm["codigo_cliente"] == 0) {
$responsavel = (strlen($dados_stm["identificacao"]) > 45) ? substr($dados_stm["identificacao"], 0, 43)."..." : $dados_stm["identificacao"];
} else {
$responsavel = (strlen($dados_revenda["nome"]) > 45) ? substr($dados_revenda["nome"], 0, 43)."..." : $dados_revenda["nome"];
}

$porcentagem_uso_espaco_ftp = ($dados_stm["espaco_usado"] == 0 || $dados_stm["espaco"] == 0) ? "0" : $dados_stm["espaco_usado"]*100/$dados_stm["espaco"];

$status_conexao = status_streaming($dados_servidor["ip"],$dados_stm["porta"]);

if($dados_stm["tipo_servidor"] == "icecast") {
$status_conexao_transmissao = status_streaming_transmissao_icecast($dados_servidor["ip"],$dados_stm["porta"],$dados_stm["senha_admin"]);
} else {
$status_conexao_transmissao = status_streaming_transmissao($dados_servidor["ip"],$dados_stm["porta"],$dados_stm["senha_admin"]);
}

if($status_conexao == "ligado") {
$status = "<i class='fa fa-check-circle text-green'>&nbsp;".lang_info_status_ligado."</i>";
// Adiciona na lista para botao de ligar autodj
if($total_playlists > 0) {
    $array_autodjs .= "".code_decode($dados_stm["porta"],"E")."|";
}
} else {
$status = "<i class='fa fa-info'>&nbsp;".lang_info_status_desligado."</i>";
// Adiciona na lista para botao de ligar streaming
$array_streamings .= "".code_decode($dados_stm["porta"],"E")."|";
}

if($status_conexao_transmissao == "relay") {
$status = "<i class='fa fa-check-circle text-pink'>&nbsp;".lang_info_status_relay."</i>";
} elseif($status_conexao_transmissao == "autodj") {
$status = "<i class='fa fa-check-circle text-green'>&nbsp;".lang_info_status_autodj."</i>";
} elseif($status_conexao_transmissao == "aovivo") {
$status = "<i class='fa fa-check-circle text-red'>&nbsp;".lang_info_status_aovivo."</i>";
}

list($ano,$mes,$dia) = explode("-",$dados_stm["data_cadastro"]);
$data_cadastro = $dia."/".$mes."/".$ano;

$servidor = ($dados_revenda["dominio_padrao"]) ? strtolower($dados_servidor["nome"]).".".$dados_revenda["dominio_padrao"] : strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"];

if($dados_stm["status"] > 1) {
$cor_status = "class='table-danger'";
} else {
$cor_status = "";
}

$porta_code = code_decode($dados_stm["porta"],"E");

echo "<tr id='".$porta_code."' ".$cor_status.">
<td height='25' align='left' scope='col' data-toggle='tooltip' data-placement='bottom' title='Identificação: ".$dados_stm["identificacao"]." | Data Cadastro: ".$data_cadastro."'>&nbsp;".$dados_stm["porta"]."&nbsp;<small>".$dados_stm["porta_dj"]."</small></td>
<td height='25' align='left' scope='col' data-toggle='tooltip' data-placement='bottom' title='Servidor ".$dados_servidor["nome"]." - ".$dados_servidor["ip"]."'>&nbsp;".$servidor." <small>(".$dados_servidor["ip"].")</small></td>
<td height='25' align='left' scope='col'>&nbsp;".$dados_stm["ouvintes"]." ouvin. | ".$dados_stm["bitrate"]." Kbps | ".tamanho($dados_stm["espaco"])."</td>
<td height='25' align='center' scope='col'><div class='progress progress-sm'><div class='progress-bar bg-info' role='progressbar' aria-valuenow='".$porcentagem_uso_espaco_ftp."' aria-valuemin='0' aria-valuemax='100' style='width: ".$porcentagem_uso_espaco_ftp."%;'></div></div></td>
<td height='25' align='center' scope='col'>".$status."</td>
<td height='25' align='left' scope='col'>&nbsp;".$responsavel."</td>
<td height='25' align='left' scope='col'><a href='javascript:acessar_painel_streaming(\"".$porta_code."\");' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_acessar_painel."'><i class='fa fa-home f-16 text-blue'></i></a>&nbsp;
<a href='/admin/admin-configurar-streaming/".$porta_code."' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_alterar_configuracao."'><i class='fa fa-pencil f-16 text-blue'></i></a>&nbsp;
<a href='javascript:alterar_senha_streaming(\"".$porta_code."\");' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_alterar_senha."'><i class='fa fa-lock f-16 text-yellow'></i></a>&nbsp;
<a href='javascript:bloquear_streaming(\"".$porta_code."\");' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_bloquear."'><i class='fa fa-ban f-16 text-red'></i></a>&nbsp;
<a href='javascript:desbloquear_streaming(\"".$porta_code."\");' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_desbloquear."'><i class='fa fa-check-circle f-16 text-green'></i></a>&nbsp;
<a href='http://".$dados_servidor["ip"].":".$dados_stm["porta"]."/' data-toggle='tooltip' data-placement='bottom' title='ShoutCast' target='_blank'><i class='fa fa-flash f-16 text-yellow'></i></a>&nbsp;
<a href='http://".$dados_servidor["ip"].":".$dados_stm["porta"]."/admin.cgi?pass=".$dados_stm["senha_admin"]."' data-toggle='tooltip' data-placement='bottom' title='ShoutCast Admin' target='_blank'><i class='fa fa-flash f-16 text-orange'></i></a>&nbsp;
<a href='javascript:remover_streaming(\"".$porta_code."\");' data-toggle='tooltip' data-placement='bottom' title='".lang_pagina_streamings_acao_remover."'><i class='fa fa-trash-o f-16 text-red'></i></a>&nbsp;</td>
</tr>";

unset($status);
unset($cor_status);
}

// Adiciona na lista de checagem do status apenas se estiver ativo
$array_streamings = rtrim($array_streamings, "|");
$array_autodjs = rtrim($array_autodjs, "|");

?>
                                                </tbody>
                                            </table>
                                            <input id="lista_streamings" type="hidden" value="<?php echo $array_streamings; ?>" /><input id="lista_autodjs" type="hidden" value="<?php echo $array_autodjs; ?>" />
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>      

    </div>
  </div>
  <script src="/inc/vendor.bundle.base.js"></script>
  <script src="/inc/vendor.bundle.addons.js"></script>
  <script src="/inc/theme.js"></script>
  <script>
  $('#busca_chave').keypress(function (e) {
    if (e.which == 13) {
       window.location = "/admin/admin-streamings/resultado/"+document.getElementById("busca_chave").value;
    }
  }); 
        $(document).ready(function() {

            var table = $('#data_table').DataTable({
                responsive: true,
                "aaSorting": [],
                "order": [],
                "lengthMenu": [[25, 50, 100, 200, -1], [25, 50, 100, 200, "Todos/All"]],
                language: {
                    "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/<?php echo $lang_sortable; ?>.json"
                },
                select: true,
                'aoColumnDefs': [{
                    'bSortable': false,
                    'aTargets': ['nosort']
                }]
            });
            $('#data_table tbody').on( 'click', 'tr', function() {
                if ( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected');
                }
                else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
            });

        });
  </script>
</body>
</html>