<?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;

if($dados_stm["idioma_painel"] == "pt-br") {
$lang_sortable = "Portuguese-Brasil";
} elseif($dados_stm["idioma_painel"] == "en-us") {
$lang_sortable = "English";
} else {
$lang_sortable = "Spanish";
}

if($_POST["cadastrar"]) {

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

list($hora,$minuto) = explode(":",$_POST["hora"]);
list($ano,$mes,$dia) = explode("-",$_POST["data"]);
$data_execussao = $ano."-".$mes."-".$dia;

if(@count($_POST["dias"]) > 0){
    $dias = implode(",",$_POST["dias"]);
}

if($_POST["tipo"] == "relay") {
    // Envia para o FTP o arquivo de stream do relay
    // Conexão FTP
    $ftp = new FTP();
    $ftp->conectar($dados_servidor["ip"]);
    $ftp->autenticar($dados_stm["login"],$dados_stm["senha"]);
    
    file_put_contents("temp/".$dados_stm["login"]."-relay-".md5($_POST["servidor_relay"]).".stream",$_POST["servidor_relay"]);
    
    if(!$ftp->enviar_arquivo("temp/".$dados_stm["login"]."-relay-".md5($_POST["servidor_relay"]).".stream","relay-".md5($_POST["servidor_relay"]).".stream")) {
    
    unlink("temp/".$dados_stm["login"]."-relay-".md5($_POST["servidor_relay"]).".stream");
    
    // Cria o sessão do status das ações executadas e redireciona.
    $_SESSION["status_acao"] = '<div class="alert alert-danger text-center" role="alert">'.$lang['lang_info_remover_agendamento_salvar_stream_resultado_erro'].'</div>';

    header("Location: /gerenciar-agendamentos");
    exit();
    }
    unlink("temp/".$dados_stm["login"]."-relay-".md5($_POST["servidor_relay"]).".stream");
}

mysqli_query($conexao,"INSERT INTO playlists_agendamentos (codigo_stm,codigo_playlist,servidor_relay,frequencia,data,hora,minuto,dias,tipo) VALUES ('".$dados_stm["codigo"]."','".$_POST["codigo_playlist"]."','".$_POST["servidor_relay"]."','".$_POST["frequencia"]."','".$data_execussao."','".sprintf("%02d",$hora)."','".sprintf("%02d",$minuto)."','".$dias.",','".$_POST["tipo"]."')");

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = '<div class="alert alert-success text-center" role="alert">'.$lang['lang_acao_gerenciador_agendamentos_resultado_ok'].'</div>';

header("Location: /gerenciar-agendamentos");
exit();
}

if($_POST["remover_logs"]) {
mysqli_query($conexao,"Delete From playlists_agendamentos_logs Where codigo_stm = '".$dados_stm["codigo"]."'");

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = '<div class="alert alert-success text-center" role="alert">'.$lang['lang_info_remover_agendamento_remover_logs_resultado_ok'].'</div>';

header("Location: /gerenciar-agendamentos");
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="row">            

            <div class="col-md-12">
                                <div class="card table-card">
                                    <div class="card-header">
                                        <header><?php echo $lang['lang_info_gerenciador_agendamentos_aba_agendamentos']; ?></header>
                                    </div>
                                    <div class="card-block">
                                        <div class="table-responsive">
                                            <table id="data_table1" class="table dataTable no-footer" 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['lang_info_gerenciador_agendamentos_playlist']; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo $lang['lang_info_gerenciador_agendamentos_horario_agendado']; ?></th>
                                                        <th class="nosort sorting_disabled" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo $lang['lang_info_gerenciador_agendamentos_executar_acao']; ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
<?php
$sql = mysqli_query($conexao,"SELECT * FROM playlists_agendamentos where codigo_stm = '".$dados_stm["codigo"]."' ORDER by data");
while ($dados_agendamento = mysqli_fetch_array($sql)) {

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

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

if($dados_agendamento["frequencia"] == "1") {
$descricao = "".$lang['lang_info_gerenciador_agendamentos_info_frequencia1']." ".$data." ".$dados_agendamento["hora"].":".$dados_agendamento["minuto"]."";
} elseif($dados_agendamento["frequencia"] == "2") {
$descricao = "".$lang['lang_info_gerenciador_agendamentos_info_frequencia2']." ".$dados_agendamento["hora"].":".$dados_agendamento["minuto"]."";
} else {

$array_dias = explode(",",$dados_agendamento["dias"]);

foreach($array_dias as $dia) {

if($dia == "1") {
$dia_nome = "<font color='#003399'>".$lang['lang_label_segunda']."</font>";
} elseif($dia == "2") {
$dia_nome = "<font color='#FF0000'>".$lang['lang_label_terca']."</font>";
} elseif($dia == "3") {
$dia_nome = "<font color='#FF9900'>".$lang['lang_label_quarta']."</font>";
} elseif($dia == "4") {
$dia_nome = "<font color='#CC0066'>".$lang['lang_label_quinta']."</font>";
} elseif($dia == "5") {
$dia_nome = "<font color='#009900'>".$lang['lang_label_sexta']."</font>";
} elseif($dia == "6") {
$dia_nome = "<font color='#663300'>".$lang['lang_label_sabado']."</font>";
} elseif($dia == "7") {
$dia_nome = "<font color='#663399'>".$lang['lang_label_domingo']."</font>";
} else {
$dia_nome = "";
}

$lista_dias .= "".$dia_nome.", ";

}

$descricao = "".$lang['lang_info_gerenciador_agendamentos_info_frequencia3']." ".substr($lista_dias, 0, -2)." ".$dados_agendamento["hora"].":".$dados_agendamento["minuto"]."";
}

if($dados_agendamento["tipo"] == "playlist") {
$tipo = $dados_playlist["nome"];
} else {
$tipo = $dados_agendamento["servidor_relay"];
}

$agendamento_code = code_decode($dados_agendamento["codigo"],"E");

echo "<tr id='".$agendamento_code."'>
<td height='25' align='left' scope='col'>&nbsp;".$tipo."</td>
<td height='25' align='left' scope='col'>&nbsp;".$descricao."</td>
<td height='25' align='left' scope='col'><a href='javascript:remover_agendamento(\"".$agendamento_code."\");' data-toggle='tooltip' data-placement='bottom' title='".$lang['lang_info_gerenciador_agendamentos_acao_remover']."'><i class='fa fa-trash-o f-16 text-red'></i></a></td>
</tr>";

unset($lista_dias);
unset($dia_nome);
}
?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header">
                                        <header><?php echo $lang['lang_info_gerenciador_agendamentos_aba_cadastrar_agendamento']; ?></header>
                                    </div>
                                    <div class="card-body">
                                        <form method="post" action="/gerenciar-agendamentos" name="agendamentos">
                                        <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                          <tr>
                                            <td width="160" height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_tipo']; ?></td>
                                            <td align="left">
                                            <select name="tipo" id="tipo" style="width:100%;" class="form-control" onchange="validar_tipo_agendamento(this.value);">
                                            <option value="playlist">Playlist</option>
                                            <option value="relay">Relay RTMP</option>
                                            </select>
                                            </td>
                                          </tr>
                                          <tr>
                                            <td width="160" height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_playlist']; ?></td>
                                            <td width="730" align="left">
                                            <select name="codigo_playlist" id="codigo_playlist" class="form-control" style="width:100%;">
                                            <?php
                                            $query_playlists = mysqli_query($conexao,"SELECT * FROM playlists where codigo_stm = '".$dados_stm["codigo"]."' ORDER by codigo ASC");
                                            while ($dados_playlist = mysqli_fetch_array($query_playlists)) {
                                        
                                            $total_videos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM playlists_videos where codigo_playlist = '".$dados_playlist["codigo"]."'"));
                                            $duracao = mysqli_fetch_array(mysqli_query($conexao,"SELECT *,SUM(duracao_segundos) as total FROM playlists_videos where codigo_playlist = '".$dados_playlist["codigo"]."'"));

                                            if($total_videos > 0) {
                                            echo '<option value="'.$dados_playlist["codigo"].'">'.$dados_playlist["nome"].' ('.gmdate("H:i:s", $duracao["total"]).')</option>';
                                            } else {
                                            echo '<option value="'.$dados_playlist["codigo"].'" disabled="disabled">'.$dados_playlist["nome"].' ('.$lang['lang_info_sem_videos'].')</option>';
                                            }
                                            }
                                            ?>
                                            </select>        </td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;">Relay RTMP</td>
                                            <td align="left"><input name="servidor_relay" type="text" class="form-control" id="servidor_relay" style="width:100%;" placeholder="rtmp://dominio:1935/login/login" disabled="disabled" /></td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_frequencias']; ?></td>
                                            <td align="left">
                                            <select name="frequencia" id="frequencia" class="form-control" style="width:100%;" onchange="valida_opcoes_frequencia_agendamento(this.value);">
                                              <option value="1" selected="selected"><?php echo $lang['lang_info_gerenciador_agendamentos_frequencia1']; ?></option>
                                              <option value="2"><?php echo $lang['lang_info_gerenciador_agendamentos_frequencia2']; ?></option>
                                              <option value="3"><?php echo $lang['lang_info_gerenciador_agendamentos_frequencia3']; ?></option>
                                            </select>
                                            </td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_data_inicio']; ?></td>
                                            <td align="left"><input class="form-control" id="data" name="data" type="date" style="width:200px;"></td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_horario_inicio']; ?></td>
                                            <td align="left"><input class="form-control" id="hora" name="hora" type="time" style="width:200px;"></td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><?php echo $lang['lang_info_gerenciador_agendamentos_dias_especificos']; ?></td>
                                            <td align="left" valign="middle">
                                            <input name="dias[]" type="checkbox" value="1" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_segunda']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="2" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_terca']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="3" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_quarta']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="4" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_quinta']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="5" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_sexta']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="6" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_sabado']; ?>&nbsp;
                                            <input name="dias[]" type="checkbox" value="7" id="dias" style="vertical-align:middle" /><?php echo $lang['lang_label_domingo']; ?></td>
                                          </tr>
                                          <tr>
                                            <td height="50" colspan="2" align="right"><input name="cadastrar" type="hidden" id="cadastrar" value="sim" /><button type="button" class="btn btn-info" onClick="document.agendamentos.submit();"><?php echo $lang['lang_botao_titulo_cadastrar']; ?></button></td>
                                          </tr>
                                        </table>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-12">
                                <div class="card table-card">
                                    <div class="card-header">
                                        <header><?php echo $lang['lang_info_gerenciador_agendamentos_aba_logs']; ?></header>
                                        <div class="card-header-right">
                                            <ul class="list-unstyled card-option">
                                                <a href='javascript:document.form_remover_logs.submit();' data-toggle='tooltip' data-placement='left' title='<?php echo $lang['lang_info_gerenciador_agendamentos_acao_remover_logs']; ?> Logs'><i class='fa fa-trash-o f-16 text-red'></i></a>
                                                <form action="/gerenciar-agendamentos" method="post" name="form_remover_logs"><input name="remover_logs" type="hidden" value="sim" /></form>
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="card-block">
                                        <div class="table-responsive">
                                            <table id="data_table2" class="table dataTable no-footer" 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['lang_info_gerenciador_agendamentos_logs_data']; ?></th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending"><?php echo $lang['lang_info_gerenciador_agendamentos_logs_playlist']; ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
<?php
$sql = mysqli_query($conexao,"SELECT * FROM playlists_agendamentos_logs WHERE codigo_stm = '".$dados_stm["codigo"]."' ORDER by data DESC LIMIT 100");
while ($dados_log_agendamento = mysqli_fetch_array($sql)) {

echo "<tr>
<td height='25' align='left' scope='col'>&nbsp;".formatar_data($dados_stm["formato_data"], $dados_log_agendamento["data"], $dados_stm["timezone"])."</td>
<td height='25' align='left' scope='col'>&nbsp;".$dados_log_agendamento["playlist"]."</td>
</tr>";

}
?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </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); 
        $(document).ready(function() {

            var table = $('#data_table1').DataTable({
                responsive: true,
                "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');
                }
            });

            var table = $('#data_table2').DataTable({
                responsive: true,
                "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>