<?php include('fncr-geral/configuracao_geral.php');
$pagina = "planos";
$blq_pag = "planos";
include('fncr-geral/permissoes_restricao.php');

// ************************************** SISTEMAS **************************************
$id_sistema = isset($_GET['s']) ? $_GET['s'] : false;

$sql = $bd->getConexao()->prepare('SELECT * FROM planos_sistemas');
if($sql->execute()){$sistemas = $sql->fetchall(PDO::FETCH_ASSOC);}


// ************************************** REGIÕES / GRUPOS **************************************
$id_grupo = isset($_GET['g']) ? $_GET['g'] : false;

if($id_sistema){
  $sql = $bd->getConexao()->prepare('
  SELECT pg.id, pr.descricao
  FROM planos_grupos pg
    LEFT JOIN planos_regiao pr ON pr.id = pg.id_plano_regiao
  WHERE pg.id_plano_sistema = :id_plano_sistema AND pr.id is not null');
  $sql->bindValue(':id_plano_sistema', $id_sistema, PDO::PARAM_STR);
  if($sql->execute()){$regioes = $sql->fetchall(PDO::FETCH_ASSOC);}

  $id_grupo = !$id_grupo ? $regioes[0]['id'] : $id_grupo;
}


// ************************************** NÍVEIS **************************************
$id_nivel = isset($_GET['n']) ? $_GET['n'] : false;

if($id_grupo){
  $sql = $bd->getConexao()->prepare('
  SELECT *
  FROM planos_niveis
  WHERE id_plano_grupo = :id_plano_grupo
  ORDER BY ordem');
  $sql->bindValue(':id_plano_grupo', $id_grupo, PDO::PARAM_STR);
  if( $sql->execute() ) { $niveis = $sql->fetchall(PDO::FETCH_ASSOC);}

  $id_nivel = !$id_nivel ? $niveis[0]['id'] : $id_nivel;
}


// ************************************** CONFIGURAÇÕES DOS NÍVEIS **************************************
if($id_nivel){

  // Informações do Nìvel
  $sql = $bd->getConexao()->prepare('
  SELECT
    n.*,
    s.id as sistema
  FROM planos_niveis n
    LEFT JOIN planos_grupos g ON g.id = n.id_plano_grupo
    LEFT JOIN planos_sistemas s ON s.id = g.id_plano_sistema
  WHERE n.id = :id');
  $sql->bindValue(':id', $id_nivel, PDO::PARAM_STR);
  if( $sql->execute() ) { $nivel = $sql->fetch(PDO::FETCH_ASSOC);}


  // Configurações
  if(isset($_POST['configs']) && $_POST['configs'] == 'salvar') {
    $update = array();
    foreach($_POST['valor'] as $id=>$valor){
      $update[] = '("'.$id.'", "'.$valor.'")';
    }
    if(count($update)>0){
      $sql = $bd->getConexao()->prepare('INSERT INTO planos_niveis_configs
      (id, valor) VALUES '.implode(',', $update).' ON DUPLICATE KEY UPDATE
      valor = VALUES (valor)');
      if ($sql->execute()) ;
    }
  }

  // Valores
  if(isset($_POST['valores']) && $_POST['valores'] == 'salvar') {
    $update = array();
    foreach($_POST['valor'] as $id=>$valor){
      $update[] = '("'.$id.'", "'.moeda($valor).'")';
    }
    if(count($update)>0){
      $sql = $bd->getConexao()->prepare('INSERT INTO planos_valores
      (id, valor) VALUES '.implode(',', $update).' ON DUPLICATE KEY UPDATE
      valor = VALUES (valor)');
      if ($sql->execute()) ;
    }
  }

  // CONFIGURAÇÕES DO NÍVEL
  $sql = $bd->getConexao()->prepare('
  SELECT
    l.id,
    l.valor,
    cf.site_titulo,
    cf.site_descricao,
    cf.controle,
    cf.tipo,
    cf.id as id_cf,
    m.nome as modulo
  FROM planos_niveis_configs l
    LEFT JOIN planos_configs cf ON cf.id = l.id_plano_config
    LEFT JOIN modulos m ON m.id = cf.id_modulo
  WHERE l.id_plano_nivel = :id_plano_nivel AND cf.id is not null
  ORDER BY l.id_plano_nivel is null, m.ordem, cf.site_ordem=0, cf.site_ordem');
  $sql->bindValue(':id_plano_nivel', $id_nivel, PDO::PARAM_STR);
  if( $sql->execute() ) { $configs_nivel = $sql->fetchall(PDO::FETCH_ASSOC);}

  // Se não existir configuração, criar a base
  if($id_nivel>0 && count($configs_nivel)==0){

    $sql = $bd->getConexao()->prepare('SELECT * FROM planos_configs WHERE id_plano_sistema = :id_plano_sistema');
    $sql->bindValue(':id_plano_sistema', $nivel['sistema'], PDO::PARAM_STR);
    if( $sql->execute() ) { $configs = $sql->fetchall(PDO::FETCH_ASSOC);}

    $inserts = array();
    foreach($configs as $l){
      $inserts[] = '("'.$id_nivel.'", "'.$l['id'].'")';
    }
    if(count($inserts)>0){
      $sql = $bd->getConexao()->prepare('INSERT INTO planos_niveis_configs
      (id_plano_nivel, id_plano_config) VALUES '.implode(',', $inserts));
      if($sql->execute());
    }
  }

  // VALORES DO NÍVEL
  $sql = $bd->getConexao()->prepare('
  SELECT
    v.id,
    v.valor,
    p.descricao,
    m.id as id_modulo,
    m.nome as modulo
  FROM planos_valores v
    LEFT JOIN produtos p ON p.id = v.id_produto
    LEFT JOIN modulos m ON m.id = p.id_modulo
  WHERE v.id_plano_nivel = :id_plano_nivel');
  $sql->bindValue(':id_plano_nivel', $id_nivel, PDO::PARAM_STR);
  if( $sql->execute() ) { $valores_produtos = $sql->fetchall(PDO::FETCH_ASSOC);}

  // Se não existir registros de valores
  if($id_nivel>0 && count($valores_produtos)==0){

    $sql = $bd->getConexao()->prepare('SELECT * FROM produtos WHERE id_plano_sistema = :id_plano_sistema');
    $sql->bindValue(':id_plano_sistema', $nivel['sistema'], PDO::PARAM_STR);
    if( $sql->execute() ) { $produtos = $sql->fetchall(PDO::FETCH_ASSOC);}

    $inserts = array();
    foreach($produtos as $l){
      $inserts[] = '("'.$id_nivel.'", "'.$l['id'].'", "0")';
    }
    if(count($inserts)>0){
      $sql = $bd->getConexao()->prepare('INSERT INTO planos_valores
      (id_plano_nivel, id_produto, valor) VALUES '.implode(',', $inserts));
      if($sql->execute());
    }
  }

  if(count($configs_nivel)==0 || count($valores_produtos)==0){
    //header("Refresh:0"); exit;
  }

}











// ************************************** GERAL **************************************

$sql = $bd->getConexao()->prepare('
SELECT g.*, ps.sistema, pr.descricao as regiao
FROM planos_grupos g
  LEFT JOIN planos_sistemas ps ON ps.id = g.id_plano_sistema
  LEFT JOIN planos_regiao pr ON pr.id = g.id_plano_regiao
  ');
if($sql->execute()){$grupos = $sql->fetchall(PDO::FETCH_ASSOC);}


?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
  <?php include('fncr-geral/html-head.php');?>

  <style>
    .tr_selected td{
      background-color: #b7e7c0 !important;
    }
  </style>

</head>
<body>

<!-- BARRA SUPERIOR -->
<?php include('barra-sup.php');?>
<!-- MENU PRINCIPAL -->
<?php include('menu.php');?>

<section id="content">
<!-- MENSAGENS DE ALERTA -->
<?php include('fncr-geral/mensagens.php');?>
<div class="clearfix padder bg-fncr-clearfix">
<h3 class="m-b">Planos</h3>
</div>

<section id="content" class="content-sidebar bg-white">
<section class="main">

<br>

  <div class="col-lg-12" style="padding: 0">
    <div class="col-lg-2">
      <section class="panel">
        <header class="panel-heading">
          Sistemas
        </header>
        <div class="table-responsive">
          <table class="table table-striped b-t text-small">
            <thead>
            <tr>
              <th class="text-center" width="25"></th>
              <th>Sistema</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($sistemas as $l){?>
              <tr class="<?php echo $l['id']==$id_sistema ? "tr_selected":""; ?>">
                <td class="text-info">
                  <a href="planos_painel.php?s=<?php echo $l['id']?>"><i class="fa fa-folder-open fa-lg" data-toggle="tooltip" data-placement="top"></i></a>
                </td>
                <td><?php echo $l['sistema']?></td>
              </tr>
            <?php } ?>
            </tbody>
          </table>
        </div>
      </section>
    </div>
    <?php if($id_sistema){ ?>
      <div class="col-lg-2">
        <section class="panel">
          <header class="panel-heading">
            Região
          </header>
          <div class="table-responsive">
            <table class="table table-striped b-t text-small">
              <thead>
              <tr>
                <th class="text-center" width="25"></th>
                <th>Região/Grupo</th>
              </tr>
              </thead>
              <tbody>
              <?php foreach ($regioes as $l){?>
                <tr class="<?php echo $l['id']==$id_grupo ? "tr_selected":""; ?>">
                  <td class="text-info">
                    <a href="planos_painel.php?s=<?php echo $id_sistema?>&g=<?php echo $l['id']?>"><i class="fa fa-folder-open fa-lg" data-toggle="tooltip" data-placement="top"></i></a>
                  </td>
                  <td><?php echo $l['descricao']?></td>
                </tr>
              <?php } ?>
              </tbody>
            </table>
          </div>
        </section>
      </div>
    <?php } ?>
    <?php if($id_grupo){ ?>
      <div class="col-lg-2">
        <section class="panel">
          <header class="panel-heading">
            Níveis
          </header>
          <div class="table-responsive">
            <table class="table table-striped b-t text-small">
              <thead>
              <tr>
                <th class="text-center" width="25"></th>
                <th>Nível</th>
              </tr>
              </thead>
              <tbody>
              <?php foreach ($niveis as $l){?>
                <tr class="<?php echo $l['id']==$id_nivel ? "tr_selected":""; ?>">
                  <td class="text-info">
                    <a href="planos_painel.php?s=<?php echo $id_sistema?>&g=<?php echo $id_grupo?>&n=<?php echo $l['id']?>"><i class="fa fa-folder-open fa-lg" data-toggle="tooltip" data-placement="top"></i></a>
                  </td>
                  <td><?php echo $l['nome']?></td>
                </tr>
              <?php } ?>
              </tbody>
            </table>
          </div>
        </section>
      </div>
    <?php } ?>
  </div>



  <?php if($id_nivel){ ?>
    <div class="col-lg-6">
      <form class="m-b-none" method="post" action="" data-validate="parsley" enctype="multipart/form-data">
        <input type="hidden" name="configs" value="salvar" />
        <section class="panel">
          <header class="panel-heading">
            <button type="submit" class="btn btn-xs btn-inverse text-center pull-right" style="margin: 0">Salvar</button>
            Configurações do Nível
          </header>
          <div class="table-responsive">
            <table class="table table-striped b-t text-small">
              <thead>
              <tr>
                <th width="25">CF</th>
                <th width="25">ID</th>
                <th width="100">Módulo</th>
                <th>Título</th>
                <th width="125">Valor</th>
                <th width="100">Descrição</th>
                <th width="150">Controle</th>
              </tr>
              </thead>
              <tbody>
              <?php foreach($configs_nivel as $l){?>
                <tr>
                  <td><?php echo $l['id_cf']?></td>
                  <td><?php echo $l['id']?></td>
                  <td><?php echo $l['modulo']?></td>
                  <td><?php echo $l['site_titulo']?></td>
                  <td style="padding: 0">
                    <?php if($l['tipo']=="boolean"){ ?>
                      <select class="form-control" name="valor[<?php echo $l['id']?>]">
                        <option value="0" <?php echo $l['valor']==0 ? "selected" : ""?>>Bloqueado</option>
                        <option value="1" <?php echo $l['valor']==1 ? "selected" : ""?>>Liberado</option>
                      </select>
                    <?php }elseif($l['tipo']=="qtd" || $l['tipo']=="valor"){ ?>
                      <input type="text" class="form-control" name="valor[<?php echo $l['id']?>]" value="<?php echo $l['valor']?>">
                    <?php } ?>
                  </td>
                  <td><?php echo $l['site_descricao']?></td>
                  <td><?php echo $l['controle']?></td>
                </tr>
              <?php } ?>
              </tbody>
            </table>
          </div>
        </section>
      </form>
    </div>

    <div class="col-lg-6">
      <form method="post" action="" data-validate="parsley" enctype="multipart/form-data">
        <input type="hidden" name="valores" value="salvar"/>
        <section class="panel">
          <header class="panel-heading">
            <button type="submit" class="btn btn-xs btn-inverse text-center pull-right">Salvar</button>
            <div style="margin-top: 5px">Produtos - Valores</div>
          </header>
          <div class="table-responsive">
            <table class="table table-striped b-t text-small">
              <thead>
              <tr>
                <th width="80">Módulo</th>
                <th width="300">Descrição</th>
                <th class="text-center" width="100">Valor</th>
              </tr>
              </thead>
              <tbody>
              <?php $id_mod = 0; foreach($valores_produtos as $k => $l){

                $modulo_nome = $id_mod!=$l['id_modulo'] ? $l['modulo'] : '';
                $id_mod = $l['id_modulo'];

                if(isset($valores_produtos[$k+1]['id_modulo']) && $valores_produtos[$k+1]['id_modulo']!=$id_mod){
                  $border_modulo = 'style="border-bottom: solid 2pt #aaa"';
                }else{ $border_modulo = ''; }

                ?>
                <tr <?php echo $border_modulo?>>
                  <td><?php echo $modulo_nome?></td>
                  <td><?php echo $l['descricao']?></td>
                  <td style="padding: 1px">
                    <input type="text" name="valor[<?php echo $l['id']?>]" class="form-control text-center" value="<?php echo echomoeda($l['valor'])?>">
                  </td>
                </tr>
              <?php } ?>
              </tbody>
            </table>
          </div>
        </section>
      </form>
    </div>
  <?php } ?>

</section>
<!-- /.main -->
</section>

<!-- FOOTER -->
<?php include('footer.php');?>

<!-- app -->
<script src="js/app.js"></script>
<script src="js/app.plugin.js"></script>
<script src="js/app.data.js"></script>

</body>
</html>
<?php $bd = null; $bd_fn = null;?>