<?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 codigo_usuario = '".$dados_stm["porta"]."'"));
$total_avisos_exibir = ($total_avisos_ativos > $checar_status_aviso) ? $total_avisos_ativos-$checar_status_aviso : 0;

if(query_string('1') == "remover") {

@shell_exec("rm -Rf player/sites/".$dados_stm["porta"]."/");

mysqli_query($conexao,"Update streamings set site_adm_instalado = 'nao' where porta = '".$_SESSION["porta_logada"]."'");

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

header("Location: /site-administravel");
exit();
}

if($_POST["instalar"] && $dados_stm["site_adm"] == "sim") {

if(is_dir("player/sites/".$dados_stm["porta"]."")) {
@shell_exec("rm -Rf player/sites/".$dados_stm["porta"]."/");
}

$site_adm_dominio = str_replace("http://", "", $_POST["site_adm_dominio"]);
$site_adm_dominio = str_replace("https://", "", $site_adm_dominio);
$site_adm_dominio = str_replace("www.", "", $site_adm_dominio);
$site_adm_dominio = str_replace("/", "", $site_adm_dominio);

$ip_dominio_site_adm = gethostbyname($site_adm_dominio);
$ip_dominio_padrao = gethostbyname("player.".$dados_config["dominio_padrao"]);

if($ip_dominio_site_adm != $ip_dominio_padrao && !empty($_POST["site_adm_dominio"])) {

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = '<div class="alert alert-danger text-center" role="alert">Voc&ecirc; n&atilde;o configurou o DNS para seu dom&iacute;nio. Primeiro deve fazer a configura&ccedil;&atilde;o do DNS antes de instalar o site adm.</div>';

header("Location: /site-administravel");
exit();
}

mysqli_query($conexao,"Update streamings set site_adm_instalado = 'sim', site_adm_dominio = '".$site_adm_dominio."' where codigo = '".$dados_stm["codigo"]."'");

mkdir("player/sites/".$dados_stm["porta"]."", 0777);

shell_exec("tar -zxvf player/sites/site-adm.tar.gz --directory /home/painel/public_html/player/sites/".$dados_stm["porta"]."/");

if(empty($_POST["site_adm_dominio"])) {
shell_exec("replace PORTA ".$dados_stm["porta"]." -- player/sites/".$dados_stm["porta"]."/.htaccess");
} else {
shell_exec("replace '/sites/PORTA' '' -- player/sites/".$dados_stm["porta"]."/.htaccess");
}

shell_exec("replace '../../chat/' 'https://player.".$dados_config["dominio_padrao"]."/chat/' -- player/sites/".$dados_stm["porta"]."/home.php");

file_put_contents("player/sites/".$dados_stm["porta"]."/admin/bd/perfil.php","\n".'$pulse_pass = "'.$dados_stm["senha"].'";', FILE_APPEND);

shell_exec("find /home/painel/public_html/player/sites/".$dados_stm["porta"]." -type f | xargs replace 'http://fonts' 'https://fonts' --");

shell_exec("replace 'http://' 'https://' -- player/sites/".$dados_stm["porta"]."/player.php");

// Configura dominio primeiro e se der erro nao faz a instalação do site
if(!empty($_POST["site_adm_dominio"])) {

  if(file_exists("player/sites/lista_dominios_site_adm_configurar_ssl.txt")){
    file_put_contents("player/sites/lista_dominios_site_adm_configurar_ssl.txt","".$site_adm_dominio.":".$dados_stm["porta"]."", FILE_APPEND);
  } else {
    file_put_contents("player/sites/lista_dominios_site_adm_configurar_ssl.txt","".$site_adm_dominio.":".$dados_stm["porta"]."");
  }

  // Cria o sessão do status das ações executadas e redireciona.
  $_SESSION["status_acao"] = '<div class="alert alert-success text-center" role="alert">O dom&iacute;nio pr&oacute;prio ser&aacute; instalado em at&eacute; 5 minutos, enquanto isso o acesso n&atilde;o estar&aacute; dispo&iacute;vel.</div>';
} else {
shell_exec("replace 'admin' 'sites/".$dados_stm["porta"]."/admin' -- player/sites/".$dados_stm["porta"]."/config.php");
}

header("Location: /site-administravel");
exit();
}

$dominio_padrao = (empty($dados_revenda["dominio_padrao"])) ? $dados_config["dominio_padrao"] : $dados_revenda["dominio_padrao"];
$url_site_adm = (empty($dados_stm["site_adm_dominio"])) ? "https://player.".$dominio_padrao."/sites/".$dados_stm["porta"]."" : "https://".$dados_stm["site_adm_dominio"]."/";
$url_site_adm_admin = (empty($dados_stm["site_adm_dominio"])) ? "https://player.".$dominio_padrao."/sites/".$dados_stm["porta"]."/admin" : "https://".$dados_stm["site_adm_dominio"]."/admin";
?>
<!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["porta"]; ?></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="/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"><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>
        <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 $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> Streaming</a>
              <a class="dropdown-item text-danger" href="javascript:desligar_streaming('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_desligar']; ?> Streaming</a>
              <?php if($dados_stm["autodj"] == "sim") { ?>
              <div class="dropdown-divider"></div>              
              <a class="dropdown-item text-success" href="javascript:carregar_opcoes_ligar_autodj('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> AutoDJ</a>
              <a class="dropdown-item text-danger" href="javascript:desligar_autodj('<?php echo $porta_code; ?>');"> <?php echo $lang['lang_botao_titulo_desligar']; ?> AutoDJ</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 $porta_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>

    <!-- 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="playlists-autodj" 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">AutoDJ</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body text-center" id="playlists-autodj-conteudo" style="text-align: center;"><img src="/img/ajax-loader.gif" /></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 class="container-fluid page-body-wrapper">      
    <?php require_once("menu.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">   

          <?php if($dados_stm["site_adm"] == 'nao') { ?>
          <div class="alert alert-danger text-center" role="alert">Voc&ecirc; n&atilde;o tem acesso a este recurso, por favor entre em contato com nosso atendimento.</div>
          <?php } ?>         
          <?php if($dados_stm["site_adm"] == 'sim' && $dados_stm["site_adm_instalado"] == 'nao') { ?>
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header>Site Administr&aacute;vel</header>
                  </div>
                  <div class="card-body">
                  <form method="post" action="/site-administravel" style="padding:0px; margin:0px" name="site_adm">
                    <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                      <tr>
                        <td width="150" height="35" align="left" style="padding-left:5px;font-weight:bold;">Dom&iacute;nio Pr&oacute;prio</td>
                        <td align="left">
                        <input name="site_adm_dominio" type="text" class="form-control" id="site_adm_dominio" value="" placeholder="exemplo.com" data-toggle="tooltip" data-placement="bottom" title="Se voc&ecirc; possuir um dom&igrave;nio pr&oacute;prio, poder&aacute; informa-lo aqui para usar em seu site. Caso n&atilde;o tenha um dominio pr&oacute;prio, deixe em branco este campo para usar dom&iacute;nio gratis." /></td>
                      </tr>
                      <tr>
                        <td width="150" height="35" align="left" style="padding-left:5px;font-weight:bold;">Configura&ccedil;&atilde;o DNS</td>
                        <td align="left" class="texto_padrao_vermelho">Apontar o dominio <strong><?php echo $dados_stm["site_adm_dominio"]; ?></strong> para <strong>player.<?php echo $dominio_padrao; ?></strong> com tipo <strong>CNAME</strong></td>
                      </tr>
                      <tr>
                        <td height="45" align="left"></td>
                        <td align="left"><button type="button" class="btn btn-info" onClick="document.site_adm.submit();">Instalar</button><input name="instalar" type="hidden" id="instalar" value="<?php echo time(); ?>" /></td>
                      </tr>
                    </table>
                  </form>
                  </div>
              </div>
            </div>  
            <?php } ?>          
            <?php if($dados_stm["site_adm_instalado"] == 'sim') { ?>
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header>Site Administr&aacute;vel</header>
                  </div>
                  <div class="card-body">
                      <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                      <tr>
                        <td width="150" height="35" align="left" style="padding-left:5px;font-weight:bold;">URL Site</td>
                        <td align="left"><?php echo $url_site_adm; ?>&nbsp;<i class='ik ik-info f-16' data-toggle="tooltip" data-placement="right" title="Este &eacute; o endere&ccedil;o do seu site administr&aacute;vel."></i></td>
                      </tr>
                      <tr>
                        <td width="150" height="35" align="left" style="padding-left:5px;font-weight:bold;">URL Admin</td>
                        <td align="left"><?php echo $url_site_adm_admin; ?>&nbsp;<i class='ik ik-info f-16' data-toggle="tooltip" data-placement="right" title="Este &eacute; o endere&ccedil;o da p&aacute;gina de administra&ccedil;&atilde;o do seu site administr&aacute;vel."></i></td>
                      </tr>
                      <tr>
                        <td width="150" height="35" align="left" style="padding-left:5px;font-weight:bold;">Senha Admin</td>
                        <td align="left"><?php include_once("player/sites/".$dados_stm["porta"]."/admin/bd/perfil.php");echo $pulse_pass; ?>&nbsp;<i class='ik ik-info f-16' data-toggle="tooltip" data-placement="right" title="Esta &eacute; a seha da p&aacute;gina de administra&ccedil;&atilde;o do seu site administr&aacute;vel, voc&ecirc; poder&agrave; altera-la em seu primeiro acesso."></i></td>
                      </tr>
                      <tr>
                        <td width="150" height="45" align="left" style="padding-left:5px;font-weight:bold;"></td>
                        <td align="left"><button type="button" class="btn btn-danger" onClick="window.location = '/site-administravel/remover';">Remover</button></td>
                      </tr>
                  </table>
                  </div>
              </div>
            </div>
            <?php } ?>  
          </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 $porta_code; ?>');
  setInterval("status_streaming('<?php echo $porta_code; ?>')",60000);
  </script>
</body>
</html>