<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php");

if (isset($_GET['info_perf']) && is_numeric($_GET['info_perf'])) {

    $id_perf = $_GET['info_perf'];

    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT * FROM cmum_profiles WHERE id='{$id_perf}'";
    $rs = mysql_query($SQL);
    if (mysql_num_rows($rs) > 0) {
        $ret['perf'] = mysql_fetch_assoc($rs);
        echo json_encode($ret);
    }
    exit();
}



if (!empty($_POST)) {

    /*
      -- cmum_urls_rev --
      id	int(11)	Não
      id_rev	int(11)	Não
      id_profiles	int(11)	Não
      url	varchar(255)	Não
      portas	varchar(255)	Não
      data_cad	timestamp	Não 	CURRENT_TIMESTAMP
      data_atual	timestamp	Não 	CURRENT_TIMESTAMP
     */


    //Inserindo novos dados

    $perfis = array_keys($_POST['url']);
    $urls = $_POST['url'];
    $portas = $_POST['porta'];
    foreach ($perfis as $perfil) {
        /* if ($urls[$perfil] != "" && !filter_var($urls[$perfil], FILTER_VALIDATE_URL)) {
          $erro = "Campo url inválido -> " . $urls[$perfil];
          break;
          } */
        /* if ($urls[$perfil] == "") {
          $erro = "Um mais campos urls não são válidos";
          break;
          } */
        /* if ($portas[$perfil] == "") {
          $erro = "Um mais campos portas não foram preenchidos.";
          break;
          } */
        //"/[,]{2}|,$|^,/"
        if ($urls[$perfil] != "" && $portas[$perfil] == "") {
            $erro = "Para url preenchida deve preencher a porta também.";
            break;
        }
        if ($portas[$perfil] != "" && preg_match('/[^0-9\-]/', $portas[$perfil]) || preg_match('/[\-]{2}|\-$|^\-/', $portas[$perfil])) {
            $erro = "O campo porta deve apenas numeros e hifens (-) para separar mais de uma porta e não pode começar e nem terminar com hifen. -> " . $portas[$perfil];
            break;
        }
    }

    if (!isset($erro)) {
        $id_rev = $_SESSION['adminid'];

        //deletando dados existentes
        $SQL = "DELETE FROM cmum_urls_rev WHERE id_rev='{$id_rev}'";
        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        $rs = $conn->query($SQL);

        $SQL = "INSERT INTO cmum_urls_rev(id,"
                . "id_rev,"
                . "id_profiles,"
                . "url,"
                . "portas)VALUES";
        foreach ($perfis as $perfil) {
            if ($urls[$perfil] != "" && $portas[$perfil] != "") {
                $SQL .= "(null,'{$id_rev}',"
                        . "'{$perfil}',"
                        . "'{$urls[$perfil]}',"
                        . "'{$portas[$perfil]}'),";
            }
        }
        $SQL = substr($SQL, 0, -1);
        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        $rs = $conn->query($SQL);
        if ($rs === true) {
            header('Refresh: 0; url=urls.php?sucesso');
        }
    }
}
if (isset($_GET['sucesso'])) {
    $sucesso = "Dados salvos com sucesso";
}

$profiles_pm = unserialize($_SESSION['_profiles_pm']);
$str_id_profiles = implode(',', $profiles_pm);
$urls_sistema = array();
$urls_pai = array();
$urls_rev = array();
//pega id pai
$id_rev = $_SESSION['adminid'];
$SQL = "SELECT addedby FROM cmum_admins WHERE id='{$id_rev}'";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$rs = $conn->query($SQL);
if ($rs->num_rows > 0) {
    while ($row = $rs->fetch_assoc()) {
        $id_pai = $row['addedby'];
    }
}
//pega urls do sistema
$SQL = "SELECT * FROM cmum_profiles WHERE id IN({$str_id_profiles})";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$rs = $conn->query($SQL);
if ($rs->num_rows > 0) {
    while ($row = $rs->fetch_assoc()) {
        $urls_sistema[$row['id']] = $row;
    }
}
//pega urls pai revenda
$SQL = "SELECT * FROM cmum_urls_rev WHERE id_rev='{$id_pai}' AND id_profiles IN({$str_id_profiles})";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$rs = $conn->query($SQL);
if ($rs->num_rows > 0) {
    while ($row = $rs->fetch_assoc()) {
        $urls_pai[$row['id_profiles']] = $row;
    }
}
// pega urls revenda atual
// pega urls pai revenda
$SQL = "SELECT * FROM cmum_urls_rev WHERE id_rev='{$id_rev}' AND id_profiles IN({$str_id_profiles})";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$rs = $conn->query($SQL);
if ($rs->num_rows > 0) {
    while ($row = $rs->fetch_assoc()) {
        $urls_rev[$row['id_profiles']] = $row;
    }
}

foreach ($profiles_pm as $id_perf) {
    $urls_final[$id_perf]['nome_perfil'] = $urls_sistema[$id_perf]['name'];
    $urls_final[$id_perf]['obs'] = $urls_sistema[$id_perf]['obs'];
    $urls_final[$id_perf]['url'] = isset($urls_rev[$id_perf]['url']) ? $urls_rev[$id_perf]['url'] : (isset($urls_pai[$id_perf]['url']) ? $urls_pai[$id_perf]['url'] : $urls_sistema[$id_perf]['url_ip']);
    $urls_final[$id_perf]['porta'] = isset($urls_rev[$id_perf]['portas']) ? $urls_rev[$id_perf]['portas'] : (isset($urls_pai[$id_perf]['portas']) ? $urls_pai[$id_perf]['portas'] : $urls_sistema[$id_perf]['porta']);
}

/*
  -- cmum_urls_rev --
  id	int(11)	Não
  id_rev	int(11)	Não
  id_profiles	int(11)	Não
  url	varchar(255)	Não
  portas	varchar(255)	Não
  data_cad	timestamp	Não 	CURRENT_TIMESTAMP
  data_atual	timestamp	Não 	CURRENT_TIMESTAMP
 */
//var_dump($_SESSION);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title><?php print($longtitle); ?></title>
            <link rel="shortcut icon" href="favicon.ico"/>
            <link rel="apple-touch-icon" href="favicon.png"/>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css" />           
            <!--<link href="media/css/jquery.dataTables.css" rel="stylesheet" type="text/css"/>-->

            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>            
            <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
            <style>
                ul{
                    border: solid 1px green; 
                }
                li{
                    border: solid 1px red; 
                }                
            </style>
    </head>
    <body>
        <?php require_once 'topo.php'; ?>        
        <div style="width: 1000px; margin: auto; margin-top: 10px; margin-bottom: 10px">
            <?php if ($_SESSION['adminlevel'] == "1"): ?>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Lista de Urls</h3>
                    </div>
                    <div class="panel-body">
                        <ul style="border: solid 0px green; " class="clearfix lista-urls">
                            <?php foreach ($urls_final as $key => $url) : ?>
                                <li style="display: inline; float: left; border: solid 0px red; margin-left: 10px">
                                    <h3><?php echo $url['nome_perfil'] ?>&nbsp;<a href="#" pid="<?php echo $key ?>" title="<?php echo $url['obs'] ?>" class="info-perf"><img src="images/help.png"></a></h3>
                                    <p><strong>Url:</strong>&nbsp;<?php echo $url['url'] ?><br/>
                                        <strong>Portas:</strong>&nbsp;<?php echo $url['porta'] ?>
                                    </p> 
                                </li>
                            <?php endforeach; ?>          
                        </ul>

                    </div>
                </div>  
                <fieldset>
                    <legend style="font-size: 8pt">Adicione suas próprias urls</legend>
                    <form method="post">  
                        <?php if (isset($sucesso)): ?>
                            <div class="alert alert-success"><?php echo $sucesso; ?></div>
                        <?php endif; ?>
                        <?php if (isset($erro)): ?>
                            <div class="alert alert-danger"><?php echo $erro; ?></div>
                        <?php endif; ?>
                        <?php foreach ($urls_final as $key => $url) : ?>
                            <div style="clear: both">                        
                                <div class="form-group">
                                    <div class="col-sm-2" style="border: solid 0px red;">
                                        <h4 style="border: solid 0px green"><?php echo $url['nome_perfil'] ?></h4>
                                    </div>
                                    <div class="col-sm-5">
                                        <label>Url:</label>
                                        <input class="form-control" name="url[<?php echo $key ?>]" value="<?php echo isset($_POST['url'][$key]) ? $_POST['url'][$key] : (isset($urls_rev[$key]['url']) ? $urls_rev[$key]['url'] : ""); ?>"/>      
                                    </div>
                                    <div class="col-sm-3">
                                        <label>Portas:</label>
                                        <input class="form-control" name="porta[<?php echo $key ?>]" value="<?php echo isset($_POST['porta'][$key]) ? $_POST['porta'][$key] : (isset($urls_rev[$key]['portas']) ? $urls_rev[$key]['portas'] : ""); ?>"/>
                                    </div>
                                </div>
                            </div>                    
                        <?php endforeach; ?>
                        <div style="clear: both">
                            &nbsp;                     
                        </div>
                        <div style="clear: both">

                            <div class="form-group">
                                <div class="col-sm-2">
                                </div>
                                <div class="col-sm-2">
                                    <button class="btn btn-primary">Salvar</button>
                                </div>

                            </div>                        
                        </div>

                    </form>
                </fieldset>
            <?php else: ?>
                <div class="alert alert-warning">Esta página não tem efeito no user administrador, para adicionar modificar as urls globais do sistema, <a href="profiles.php">clique aqui</a>.</div>
            <?php endif; ?>
        </div>
        <div class="modal modal-info-perf" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <!--<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>-->
                        <h4 class="modal-title title-info-perf">...</h4>
                    </div>
                    <div class="modal-body body-info-perf" style="text-align: center">
                        ...
                    </div>
                    <div class="modal-footer">
                        <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                        <button type="button" class="btn btn-primary btn-info-perf">Ok</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <?php require("includes/footer.php"); ?>
        <script>
            $(document).ready(function () {
                $('.info-perf').on('click', this, function () {
                    var id = $(this).attr('pid');
                    $.ajax({
                        type: "GET",
                        url: "urls.php?info_perf=" + id,
                        dataType: "json"
                    })
                            .done(function (r) {
                                $('.title-info-perf').html('Informações do perfil: ' + r.perf.name);
                                $('.body-info-perf').html(r.perf.obs);
                                $('.modal-info-perf').modal('show');
                                $('.btn-info-perf').on('click', this, function () {
                                    $('.modal-info-perf').modal('hide');
                                });
                            });



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

