<?php
  include_once 'code/parameter.inc.php';
	include 'code/codesessao.php';
 	include 'code/codeconecta.php';
	include "code/sql.inc.php";
	function checkbox_value($name) {
		return (isset($_POST[$name]) ? 1 : 0);
	}	
	$ed_id = '';
	$ed_nome = '';
	$ed_link = '';
	$ed_target = '';
	$ed_image = '';
	$dirName = "images/sliders";
	$Tipo_Msg = "NCB";
	$Msg = 1;
	if(isset($_POST['btnEnviar'])) {
    if($_POST["btnEnviar"]){
      $nome = htmlentities($_POST['c_nome'],ENT_QUOTES);
			$nome = _noInjection2($nome);
			$link = htmlentities($_POST['c_link'],ENT_QUOTES);
			$target = checkbox_value('c_target');
			$image = trim($_FILES['c_image']['name']);
			$ativo = htmlentities($_POST['c_status'],ENT_QUOTES);
			$sql = mysql_query("SELECT * FROM sliders WHERE title='$nome'");
			$query = mysql_num_rows($sql);
			if($query != 0) {
				$Msg = 2;
				$Erro = "Slider já cadastrado!";
				header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
				exit;
			} else {			
				$sql = "INSERT INTO sliders (id, title, link, target, status, date_add) values ('', '$nome', '$link', '$target', '$ativo', now())";
				$sql = mysql_query($sql);
				if($sql) {
					$vId = mysql_insert_id();
				} else {
					$Msg = 2;
					$Erro = "Não foi possível salvar, erro: ".mysql_error().".";
					header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
					exit;
				}
				if(!empty($image)){
					if(!is_dir("../".$dirName)){
						mkdir("../".$dirName, 0755, true);
					}
					if(!copy($_FILES["c_image"]["tmp_name"], "../".$dirName."/".$image)) {
						$Msg = 2;
						$Erro = "Não foi possivel o upload da imagem, erro: ".mysql_error().".";
						header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
						exit;
					} else { 
						$query = mysql_query("UPDATE sliders SET image='$image' WHERE id='$vId'");
					}
				}
			}
    }
	}
	if(@$_REQUEST['action']=="del") {
		if (isset($_GET['id'])) { $idx = (int)$_GET['id']; } else { $idx = '0'; }
		$query = mysql_query("DELETE FROM sliders WHERE id='$idx'");
		header("Location: sliders.php");
		exit;
	}
	if(@$_REQUEST['action']=="edit") {
		if (isset($_GET['id'])) { $idx = (int)$_GET['id']; } else { $idx = '0'; }
		$sql_e = mysql_query("SELECT * FROM sliders WHERE id='$idx'");
		$query_e = mysql_num_rows($sql_e);
		if($query_e != 0) {
			$linha = mysql_fetch_object($sql_e);
			$ed_id = $linha->id;
			$ed_nome = html_entity_decode($linha->title,ENT_QUOTES);
			$ed_link = $linha->link;
			$ed_target = $linha->target;
			$ed_image = $linha->image;
			$target = array('','checked');			
		}				
	}
	if(isset($_POST['btnEditar'])) {
    if($_POST["btnEditar"]){
      $eid = (int)htmlentities($_POST['e_id'],ENT_QUOTES);
			$nome = htmlentities($_POST['e_nome'],ENT_QUOTES);
			$nome = _noInjection2($nome);
			$link = htmlentities($_POST['e_link'],ENT_QUOTES);
			$target = checkbox_value('e_target');
			$arqimg = htmlentities($_POST['e_image_a'],ENT_QUOTES);
			$image = trim($_FILES['e_image']['name']);
			$ativo = htmlentities($_POST['e_status'],ENT_QUOTES);
			$sql = mysql_query("SELECT * FROM sliders WHERE id='$eid'");
			$query = mysql_num_rows($sql);
			if($query != 0) {
				$sql = mysql_query("SELECT * FROM sliders WHERE title='$nome'");
				$query = mysql_num_rows($sql);
				if($query != 0) {
					$linha = mysql_fetch_object($sql);
					if($eid != $linha->id) {
						$Msg = 2;
						$Erro = "Nome do Slider já existe";
						header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
						exit;
					}
				} 
				$sql = "UPDATE sliders SET title='$nome', link='$link', target='$target', status='$ativo', date_edt=now() WHERE id='$eid'";
				$query = mysql_query($sql);
				if($query) {
					if(!empty($image)){
						if(!is_dir("../".$dirName)){
							mkdir("../".$dirName, 0755, true);
						}
						if(!copy($_FILES["e_image"]["tmp_name"], "../".$dirName."/".$image)) {
							$Msg = 2;
							$Erro = "Não foi possivel o upload da imagem, erro: ".mysql_error().".";
							header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
							exit;
						} else { 
							$arquivo = "../".$dirName."/".$arqimg;	
							if(file_exists($arquivo) && !empty($arqimg) && ($arqimg != $image) ) {
								if (!unlink($arquivo)) {
									$Msg = 2;
									$Erro = "Não excluiu o arquivo, erro: ".mysql_error().".";
									header("Location: code/notificar.php?Msg=$Msg&Erro=$Erro&Tipo_Msg=$Tipo_Msg");
									exit;
								}
							}
							$query = mysql_query("UPDATE sliders SET image='$image' WHERE id='$eid'");
						}
					}
					header("Location: sliders.php");
					exit;
				}
			}
    }
	}  
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
	<meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>CMS(<?=$company?>): Sliders</title>
  <meta name="description" content="Sistema de Gerenciamento de Conteúdo (CMS)" />
  <meta name="language" content="pt-br" />
  <meta name="author" content="Agência i9" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link type='image/ico' rel='shortcut icon' href='images/favicon.ico' />
  <link type='text/css' rel='stylesheet' href='css/cssmain.css' />
</head>
<body>
	<?php include_once 'common/header.inc.php'; ?>
  <section>
    <article>
      <div class="breadcrumb"> <a href="index.php">Início</a> » <span>Galeria de Sliders</span></div>
      <div class="b-content">
        <div id="ad" style="display:none;" class="content left">
          <form class="fbase fpadrao_1" id="formadd" name="formadd" action="" method="post" enctype="multipart/form-data" onsubmit="javascript:return validaAddForm();">
            <fieldset>
              <h2 class="title-form">Novo Slider</h2>
              <div><span class="inputRequirement right">* Preenchimento Obrigatório</span></div>
              <label class="clear" for="c_nome">Nome do Slider <span class="red">*</span></label>
              <input type="text" id="c_nome" name="c_nome" maxlength="200" size="60" autofocus />
              <hr />
              <label for="c_link">Link</label>
              <input class="left" type="text" id="c_link" name="c_link" maxlength="99" size="50" value="#" />
              <label for="c_target"><input type="checkbox" id="c_target" name="c_target" value="1" checked="checked" /> Abrir em nova página</label>
              <hr />
              <label class="clear" for="c_image">Imagem do Slider <span class="red">*</span></label>
              <input type="file" id="c_image" name="c_image" />
              <div class="infoform1">* <em>Tamanho usado na imagem (<span><?=$image_banner;?></span>)px.</em></div>
              <hr />
              <label class="left mg10_t" for="c_status">Desativar/Esconder: </label>
              <label class="left mg10_t" for="sim"><input type="radio" id="sim" name="c_status" value="1" />Sim</label>
              <label class="left mg10_t" for="nao"><input type="radio" id="nao" name="c_status" value="0" checked="checked" />Não</label>
              <hr />
              <div class="qbotoes">
                <input class="botao_1" type="submit" id="btnEnviar" name="btnEnviar" value="Incluir" />
              </div>
            </fieldset>
          </form>
        </div>
        <div id="ed" style="display:none;" class="content left">
          <p class="clear txt_l mg5_t left"><a class="btn_title cor-head" href="sliders.php">Novo Slider</a></p>
          <p class="txt_r mg5_t mg10_r right"><a class="btn_title cor-head" href="sliders.php"><img src="images/icons_unshare.png" width="16" height="16" alt="Botão Voltar" /> Voltar</a></p>
          <form class="fbase fpadrao_1 clear" id="formedt" name="formedt" action="" method="post" enctype="multipart/form-data" onsubmit="javascript:return validaEdtForm();">
            <fieldset>
              <h2 class="title-form">Editar Slider</h2>
              <input type="hidden" id="e_id" name="e_id" value="<?php echo $ed_id;?>" />
              <input type="hidden" id="e_image_a" name="e_image_a" value="<?php echo $ed_image;?>" />
              <div><span class="inputRequirement right">* Preenchimento Obrigatório</span></div>
              <label class="clear" for="e_nome">Nome do Slider <span class="red">*</span></label>
              <input type="text" id="e_nome" name="e_nome" maxlength="200" size="60" value="<?php echo $ed_nome;?>" />
              <hr />
              <label for="e_link">Link</label>
              <input class="left" type="text" id="e_link" name="e_link" maxlength="99" size="50" value="<?php echo $ed_link;?>" />
              <label for="e_target"><input type="checkbox" id="e_target" name="e_target" value="1" <?php echo $target[$ed_target];?> /> Abrir em nova página</label>
              <hr />
              <label for="e_image">Imagem do Slider</label>
              <input type="file" id="e_image" name="e_image" class="left" />
              <input type="text" id="x_image_a" name="x_image_a" value="<?php echo $ed_image;?>" disabled="disabled" />
              <div class="infoform1">* <em>Tamanho usado na imagem (<span><?=$image_banner;?></span>)px.</em></div>
              <hr />
              <?php
                $ativo_sim = ($linha->status == 1) ? "checked" : " ";
                $ativo_nao = ($linha->status == 0) ? "checked" : " ";
              ?>
              <label class="left mg10_t" for="e_status">Desativar/Esconder: </label>
              <label class="left mg10_t" for="sim"> <input type="radio" id="sim" name="e_status" value="1" <?php echo $ativo_sim;?> />Sim</label>
              <label class="left mg10_t" for="nao"> <input type="radio" id="nao" name="e_status" value="0" <?php echo $ativo_nao;?> />Não</label>
              <hr />
              <div class="qbotoes">
                <input class="botao_2" type="submit" id="btnEditar" name="btnEditar" value="Alterar" />
              </div>
            </fieldset>
          </form>
          <p class="txt_l mg10_t">* Se NÃO editar a imagem do Slider, permanece a imagem atual!</p>
          <p class="txt_l">* Ao editar a imagem do Slider, a anterior será excluída!!</p>
        </div>
        <?php include_once 'common/atencao.inc.php'; ?>
        <script type="text/javascript">
          <!--
          d = document.formedt;
          if (d.e_nome.value == "") {
            document.getElementById('ad').style.display='block';
            document.getElementById('ed').style.display='none';
            document.formadd.c_nome.focus();
          } else {
            document.getElementById('ad').style.display='none';
            document.getElementById('ed').style.display='block';
            d.e_nome.focus();
          }
          //-->
        </script>
        <div class="galeria">
          <?php
            $sql = mysql_query("SELECT * FROM sliders ORDER BY id DESC");
            $query = mysql_num_rows($sql);
            if($query != 0) {
              while($linha = mysql_fetch_object($sql)) {
                $status = ($linha->target == 0) ? "Local" : "Outro site";
                $modo = ($linha->status == 0) ? "Ativo" : "Desativado";
          ?>
          <div class="box-banner">
            <h3 class="cor-head title-box"><?php echo $linha->id;?><strong>:</strong> <?php echo html_entity_decode($linha->title,ENT_QUOTES);?></h3>
            <div class="qb-img">
              <div class="b-img imgLiquidFill imgLiquid">
                <img src="<?php echo '../'.$dirName.'/'.$linha->image;?>" width="300" height="120" alt="<?php echo '../'.$dirName.'/'.$linha->image;?>" />
              </div>
            </div>
            <div class="b-txt">
              <p class="mg10_t"><strong>Link abre:</strong> <?php echo $status;?>, <strong>Status:</strong> <?php echo $modo;?></p>
              <p><strong>Link:</strong> <?php echo $linha->link;?></p>
              <p class="mg10_b"><strong>Imagem:</strong> <?php echo $linha->image;?></p>
            </div>
            <div class="qbotoes">
              <a class="botao_2" href="sliders.php?action=edit&id=<?php echo $linha->id;?>"><img src="images/icons_edit.png" width="16" height="16" alt="Botão Editar" /> Editar</a>
              <a class="botao_3" onclick="return confirm('Tem certeza que deseja excluir o Slider?');" href="sliders.php?action=del&id=<?php echo $linha->id;?>"><img src="images/icons_delete.png" width="16" height="16" alt="Botão Apagar" /> Apagar</a>
            </div>
          </div>
          <?php
              }
            } else {
              echo "<p class='cor1'>Não tem nenhum Slider cadastrado até o momento. Aqui será listado os sliders de imagens cadastrados.</p>";
            } 
          ?>
          <br />
        </div>
      </div>
    </article>
    <aside>
      <div class="box-content">
      	<?php
				  require_once('common/menu.inc.php');
        	menu("sliders");
        ?>
      </div>
    </aside>
  </section>
  <?php include_once 'common/footer.inc.php'; ?>
</body>
<script type='text/javascript' src='js/jquery-1.8.3.js'></script>
<script type='text/javascript' src='js/imgLiquid-min.js'></script>
<script type="text/javascript">
	$(function() {
		$(".imgLiquidFill").imgLiquid({fill:true});
		$(".imgLiquidNoFill").imgLiquid({fill:false});
	});
</script>
<script type='text/javascript' src='js/validador.js' charset='ISO-8859-1'></script>
<?php mysql_close($conn); ?>
</html>