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

$total_avisos_ativos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos WHERE area = 'streaming'"));
$checar_status_aviso = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos_desativados WHERE area = 'streaming' AND login = '".$dados_stm["login"]."'"));
$total_avisos_exibir = ($total_avisos_ativos > $checar_status_aviso) ? $total_avisos_ativos-$checar_status_aviso : 0;
$dados_playlist_selecionada = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM playlists where codigo = '".code_decode(query_string('1'),"D")."'"));
$total_videos_playlist = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM playlists_videos where codigo_playlist = '".$dados_playlist_selecionada["codigo"]."'"));
$duracao = mysqli_fetch_array(mysqli_query($conexao,"SELECT SUM(duracao_segundos) as total FROM playlists_videos where codigo_playlist = '".$dados_playlist_selecionada["codigo"]."'"));

if($_POST["playlist"] != "" && $_POST["pastas"] == "") {

$_SESSION["status_acao"] =  "<div class='alert alert-success text-center' role='alert'>".$lang['lang_acao_gerenciador_playlists_basico_resultado_alerta']."</div>";

header("Location: /gerenciar-playlists-basico/".query_string('1')."");
exit();

}

// Salva a Playlist
if($_POST["playlist"]) {

$dados_playlist = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM playlists where codigo = '".$_POST["playlist"]."'"));

foreach($_POST["pastas"] as $pasta) {

$xml_videos = @simplexml_load_file("http://".$dados_servidor["ip"].":55/listar-videos.php?login=".$dados_stm["login"]."&pasta=".$pasta."&ordenar=nao");
    
$total_videos_pasta = count($xml_videos->video);

if($total_videos_pasta > 0) {

    for($i=0;$i<$total_videos_pasta;$i++){
    
        $path_separacao = ($pasta == "/" || $pasta == "") ? "" : "/";
        
        if($xml_videos->video[$i]->bitrate < $dados_stm["bitrate"]) { // Verifica limite bitrate
        
        if(!preg_match('/[^A-Za-z0-9\_\-\. ]/',$xml_videos->video[$i]->nome)) { // Verifica caracteres especiais nome video
        
            $array_videos[] = $pasta.$path_separacao.utf8_decode($xml_videos->video[$i]->nome)."|".utf8_decode($xml_videos->video[$i]->nome)."|".$xml_videos->video[$i]->width."|".$xml_videos->video[$i]->height."|".$xml_videos->video[$i]->bitrate."|".$xml_videos->video[$i]->duracao."|".$xml_videos->video[$i]->duracao_segundos."|".$xml_videos->video[$i]->thumb;
        }
        
        }
        
    }
}

}

if($_POST["misturar"] == 'sim') {
shuffle($array_videos);
} else {
sort($array_videos);
}


$total_videos_atuais_playlist = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM playlists_videos where codigo_playlist = '".$dados_playlist_selecionada["codigo"]."'"));

$contagem = $total_videos_atuais_playlist;

// Adiciona as videos da playlist ao banco de dados
foreach($array_videos as $dados) {

list($path, $video, $width, $height, $bitrate, $duracao, $duracao_segundos, $thumb) = explode("|",$dados);

$path = str_replace("%20"," ",$path);
$video = str_replace("%20"," ",$video);

// Adiciona vídeo na playlist
mysqli_query($conexao,"INSERT INTO playlists_videos (codigo_playlist,path_video,video,width,height,bitrate,duracao,duracao_segundos,tipo,ordem) VALUES ('".$dados_playlist["codigo"]."','".addslashes($path)."','".addslashes($video)."','".$width."','".$height."','".$bitrate."','".$duracao."','".$duracao_segundos."','video','".$contagem."')") or die("Ooops! Ocorreu um erro no mysql: ".mysqli_error($conexao));

$contagem++;
}

$_SESSION["status_acao"] =  "<div class='alert alert-success text-center' role='alert'>".$lang['lang_acao_gerenciador_playlists_basico_resultado_ok']."</div>";

header("Location: /playlists");
exit();
}
?>
<!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>Streaming <?php echo $dados_stm["login"]; ?></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">  
  <?php if($dados_stm["tema_dark"] == "sim") { ?>
  <link rel="stylesheet" href="/inc/theme-dark.css">
  <?php } else { ?>
  <link rel="stylesheet" href="/inc/theme.css">
  <?php } ?>
  <link rel="shortcut icon" href="/img/favicon.ico" />
  <script type="text/javascript" src="/inc/ajax-streaming.js"></script>
  <script type="text/javascript" src="/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">
        <?php if($dados_revenda["url_logo"]) { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><img id="logo" src="<?php echo $dados_revenda["url_logo"]; ?>" title="Painel" height="60" border="0"></a>
        <?php } else { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><span>Painel Streaming</span></a>
        <?php } ?>
        <a class="navbar-brand brand-logo-mini" href="/dashboard"><i class="fa fa-video-camera text-muted"></i></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>
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item nav-profile dropdown show">
            <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" id="profileDropdown" aria-expanded="true">
              <i class="fa fa-power-off f-18 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_botao_titulo_ligar']; ?>/<?php echo $lang['lang_botao_titulo_desligar']; ?>"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="profileDropdown">
              <a class="dropdown-item text-success" href="javascript:ligar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> Streaming</a>
              <a class="dropdown-item text-warning" href="javascript:reiniciar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> Streaming</a>
              <?php if($dados_stm["srt_status"] == 'sim') { ?>
              <a class="dropdown-item text-primary" href="javascript:reiniciar_srt('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> SRT</a>
              <?php } ?>
            </div>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown" aria-expanded="false">
              <i class="mdi mdi-bell f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?>"></i>
              <?php if($total_avisos_exibir > 0) { ?><span class="count bg-success"><?php echo $total_avisos_exibir; ?></span><?php } ?>           
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
              <a class="dropdown-item">
                <p class="mb-0 font-weight-normal float-left"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></p>
              </a>
              <div class="dropdown-divider"></div>
              <?php carregar_avisos_streaming($conexao,$dados_stm["porta"],$dados_servidor["codigo"]); ?>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/sair"><i class="mdi mdi-logout f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="Sair/logout"></i></a>
          </li>
          <li>
            <button type="button" class="btn btn-info" id="status-streaming" onClick="status_streaming('<?php echo $login_code; ?>');" style="margin: 10px;min-width: 150px; min-height: 40px"><i class="fa fa-refresh"></i></button>
          </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>
    <div class="container-fluid page-body-wrapper">
      <?php require_once("menu.php"); ?>
      <!-- partial -->
      <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="col-12">
              <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                  <div class="card">
                    <div class="card-body">
                      <h4 class="card-title">Playlist</h4>
                      <div class="d-flex justify-content-between">
                        <i class="fa fa-file-audio-o f-32 text-blue"></i>
                        <?php echo $dados_playlist_selecionada["nome"]; ?>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                  <div class="card">
                    <div class="card-body">
                      <h4 class="card-title">Playlists</h4>                      
                      <div class="d-flex justify-content-between">
                        <i class="fa fa-external-link f-32 text-yellow"></i>
                        <div class="dropdown show">
                                                                  <button class="btn btn-light btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">&nbsp;&nbsp;&nbsp;<?php echo $lang['lang_info_gerenciador_playlists_lista_acao_playlists']; ?>&nbsp;</button>

                                                                  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                                                                    <?php

                                                                    $query = mysqli_query($conexao,"SELECT * FROM playlists where codigo_stm = '".$dados_stm["codigo"]."' ORDER by nome ASC");
                                                                    while ($dados_playlist_gerenciar = mysqli_fetch_array($query)) {

                                                                    $total_videos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM playlists_videos where codigo_playlist = '".$dados_playlist_gerenciar["codigo"]."'"));

                                                                    $playlist_gerenciar_code = code_decode($dados_playlist_gerenciar["codigo"],"E");

                                                                    echo '<a class="dropdown-item" href="/gerenciar-playlists-basico/' . $playlist_gerenciar_code . '">' . $dados_playlist_gerenciar["nome"] . ' (' . $total_videos . ')</a>';
                                                                    
                                                                    }
                                                                    ?>
                                                                  </div>
                                                                </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                  <div class="card">
                    <div class="card-body">
                      <h4 class="card-title"><?php echo $lang['lang_info_gerenciador_playlists_basico_videos_playlist']; ?></h4>
                      <div class="d-flex justify-content-between">
                        <i class="fa fa-file-video-o f-32 text-dribbble"></i>
                        <?php echo $total_videos_playlist; ?>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                  <div class="card">
                    <div class="card-body">
                      <h4 class="card-title"><?php echo $lang['lang_info_gerenciador_playlists_basico_tempo_execucao']; ?></h4>
                      <div class="d-flex justify-content-between">
                        <i class="fa fa-clock-o f-32 text-green"></i>
                        <?php echo gmdate("H:i:s", $duracao["total"]); ?><input name="tempo" type="hidden" id="tempo" value="0" /></p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
         

                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-body">
                                        <form method="post" action="/gerenciar-playlists-basico/<?php echo query_string('1'); ?>" name="gerenciador" enctype="multipart/form-data">
                                        <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                            <tr>
                                            <td height="210" colspan="2" align="left" class="texto_padrao_destaque" style="padding-left:5px;padding-right:5px;">
                                                <select name="pastas[]" multiple="multiple" class="input" id="pastas" style="width:100%; height:230px">
                                                    <optgroup label="<?php echo $lang['lang_info_gerenciador_playlists_basico_opcao_pastas']; ?>">
                                                    <?php
                                                        $xml_pastas = @simplexml_load_file("http://".$dados_servidor["ip"].":55/listar-pastas.php?login=".$dados_stm["login"]."");
                                                            
                                                        $total_pastas = @count($xml_pastas->pasta);

                                                        if($total_pastas > 0) {

                                                            for($i=0;$i<$total_pastas;$i++){
                                                            
                                                                echo '<option value="' . $xml_pastas->pasta[$i]->nome . '">' . $xml_pastas->pasta[$i]->nome . ' (' . $xml_pastas->pasta[$i]->total . ')</option>';
                                                            
                                                            }
                                                            
                                                        }
                                                        ?>
                                                    </optgroup>
                                                </select>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td width="50%" height="50" align="left" class="texto_padrao" style="padding-left:5px;">
                                                    <input name="misturar" type="checkbox" id="misturar" value="sim" checked="checked" />&nbsp;<?php echo $lang['lang_info_gerenciador_playlists_basico_misturar_videos']; ?>
                                                </td>
                                                <td width="50%" align="right" class="texto_padrao" style="padding-right:5px;">
                                                    <button type="button" class="btn btn-success" onClick="document.gerenciador.submit();"><i class="fa fa-save"></i> <?php echo $lang['lang_info_gerenciador_playlists_basico_botao_salvar_playlists']; ?></button>
                                                    <button type="button" class="btn btn-secondary" onClick="location.reload();"><i class="fa fa-refresh"></i> <?php echo $lang['lang_info_gerenciador_playlists_basico_botao_recarregar_pastas']; ?></button><input name="playlist" type="hidden" id="playlist" value="<?php echo $dados_playlist_selecionada["codigo"]; ?>" />
                                                </td>
                                            </tr>
                                        </table>
                                        </form>
                                    </div>
                                </div>
                            </div>
        </div>
      </div>
      <!-- modal -->
      <div class="modal fade" id="avisos" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body" id="avisos-conteudo"><img src="/img/ajax-loader.gif" align="center" /></div>
            </div>
        </div>
        </div>
                
        <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>
  </div>
  <script src="/inc/vendor.bundle.base.js"></script>
  <script src="/inc/vendor.bundle.addons.js"></script>
  <script src="/inc/theme.js"></script>
  <script>
  status_streaming('<?php echo $login_code; ?>');
  setInterval("status_streaming('<?php echo $login_code; ?>')",60000);
        // Swithces
        $(document).ready(function() {
            var elemsingle = document.querySelector('#misturar');
            var switchery = new Switchery(elemsingle, {
                color: '#633e77',
                jackColor: '#fff',
                size: 'small'
            });
        });
  </script>
</body>
</html>