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

if($_POST["configurar"]) {

// Função para conectar a uma URL
function criar_entrada_dns_cpanel($dominio, $usuario, $senha, $servidor) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$dominio.":2083/json-api/cpanel?cpanel_jsonapi_user=".$usuario."&cpanel_jsonapi_apiversion=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=add_zone_record&domain=".$dominio."&name=".$servidor."&type=CNAME&cname=".$servidor.".".$dados_config["dominio_padrao"]."&ttl=900&class=IN");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)');
$header[0] = "Authorization: Basic " . base64_encode($usuario.":".$senha) . "\n\r";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$resultado = curl_exec($ch);
curl_close($ch);

if($resultado === false) {
return "Error connection, try again.";
} else {

$xml = json_decode($resultado,true);
$status = $xml["cpanelresult"]["data"][0]["result"]["status"];

if($status == 1) {
return "OK";
} else {
return "Error: ".$xml["cpanelresult"]["data"][0]["result"]["statusmsg"];
}

}

}

$dados_revenda = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM revendas WHERE codigo = '".$_SESSION["code_user_logged"]."'"));

// Colocar contador de 1 a 100 pra adicionar as zonas e resultado individual
$resultado = "";

for ($i = 1; $i <= 100; $i++) {
$resultado_requisicao = criar_entrada_dns_cpanel($dados_revenda["dominio_padrao"], $_POST["usuario_cpanel"], $_POST["senha_cpanel"], "stm".$i);
$resultado_final .= "[".$resultado_requisicao."] stm".$i.".".$dados_revenda["dominio_padrao"]." -> stm".$i.".xradios.com.br<br>";
}

$resultado_requisicao_api = criar_entrada_dns_cpanel($dados_revenda["dominio_padrao"], $_POST["usuario_cpanel"], $_POST["senha_cpanel"], "api");
$resultado_final .= "[".$resultado_requisicao_api."] api.".$dados_revenda["dominio_padrao"]." -> api.xradios.com.br<br>";

$resultado_requisicao_player = criar_entrada_dns_cpanel($dados_revenda["dominio_padrao"], $_POST["usuario_cpanel"], $_POST["senha_cpanel"], "player");
$resultado_final .= "[".$resultado_requisicao_player."] player.".$dados_revenda["dominio_padrao"]." -> player.xradios.com.br<br>";


// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["resultado"] = $resultado_final;
header("Location: /admin/revenda-dominio-cpanel");
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>Revenda <?php echo $dados_revenda["id"]; ?></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-revenda.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">
        <?php if($dados_revenda["url_logo"]) { ?>
        <a class="navbar-brand brand-logo" href="/admin/revenda-configuracoes"><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="/admin/revenda-configuracoes"><span>Painel Revenda</span></a>
        <?php } ?>
        <a class="navbar-brand brand-logo-mini" href="/admin/revenda-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 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_info_pagina_informacoes_revenda_tab_avisos; ?></p>
              </a>
              <div class="dropdown-divider"></div>
              <?php carregar_avisos_revenda($conexao); ?>
            </div>
          </li>
          <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="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-revenda.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(empty($_SESSION['resultado'])) { ?>
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_tab_titulo; ?></header>
                  </div>
                <div class="card-body">
                    <form method="post" action="/admin/revenda-dominio-cpanel" name="configurar">
                                            <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                            <tr>
                                              <td width="150" height="30" align="left" style="padding-left:5px;"><strong><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_dominio; ?></strong></td>
                                              <td align="left"><?php echo ($dados_revenda["dominio_padrao"]) ? '<small>'.$dados_revenda["dominio_padrao"].'</small>' : '<span  class="text-danger">'.lang_info_pagina_dominio_proprio_ferramenta_cpanel_status.'</span><br><a href="#" onclick="abrir_log_sistema();window.open(\'/admin/revenda-configuracoes\',\'conteudo\');"><small>'.lang_info_pagina_dominio_proprio_ferramenta_cpanel_status_botao.'</small></a>'; ?></td>
                                            </tr>
                                            <tr>
                                              <td height="50" align="left" style="padding-left:5px;"><strong><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_usuario; ?></strong></td>
                                              <td align="left"><input name="usuario_cpanel" type="text" class="form-control" id="usuario_cpanel" style="width:100%;" /></td>
                                            </tr>
                                            <tr>
                                              <td height="50" align="left" style="padding-left:5px;"><strong><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_senha; ?></strong></td>
                                              <td align="left"><input name="senha_cpanel" type="password" class="form-control" id="senha_cpanel" style="width:100%;" /></td>
                                            </tr>
                                            <tr>
                                              <td height="50" colspan="2" align="right"><input name="alterar" type="hidden" id="alterar" value="<?php echo time(); ?>" /><button type="button" class="btn btn-info" onClick="document.configurar.submit();" <?php if(empty($dados_revenda["dominio_padrao"])) { echo 'disabled="disabled"'; } ?>><?php echo lang_botao_titulo_configurar; ?></button></td>
                                          </tr>
                                          </table>
                                        </form>
                </div>
              </div>
            </div>
            <?php } else { ?>
            <div class='alert alert-info text-center' role='alert'><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_info_erro; ?></div>
            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header><?php echo lang_info_pagina_dominio_proprio_ferramenta_cpanel_tab_titulo_resultado; ?></header>
                  </div>
                <div class="card-body">
                    <div id="resultado_requisicao" style="width:100%; height:200px; border:#999999 1px solid; text-align:left; overflow-y:scroll; padding:5px; background-color:#F4F4F7"><?php echo $_SESSION['resultado'];unset($_SESSION["resultado"]); ?></div>
                </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>
  $('#busca_chave').keypress(function (e) {
    if (e.which == 13) {
       window.location = "/admin/revenda-streamings/resultado/porta/"+document.getElementById("busca_chave").value;
    }
  }); 
  </script>
</body>
</html>