<?php
	@session_start();
	if (empty($page)) header("Location: index.php");
	if (!isset($_SESSION["admin"]["id"])) {
		echo "<script>location.href='index.php';</script>";
	}

	if ($table == "configuracao") $id = 1;

	$tt = $_SESSION["admin"]["tipo"];

	if (file_exists("pages/".$table.".php")) {
		include "pages/".$table.".php";
	} else {
	
	$sql = "select TABLE_NAME,COLUMN_NAME,DATA_TYPE,
		CHARACTER_MAXIMUM_LENGTH,
		COLUMN_KEY,EXTRA,COLUMN_COMMENT,IS_NULLABLE
		from COLUMNS 
		where TABLE_SCHEMA = ? 
		AND TABLE_NAME = ?";
    $consulta = $is->prepare($sql); 
	$consulta->bindParam(1, $banco); 
	$consulta->bindParam(2, $table); 
	$consulta->execute();
	$row = $consulta->fetch(PDO::FETCH_OBJ);

	if (empty($row->TABLE_NAME)) {

		?>
<h1 class="page-header">
	Cadastro não encontrado!
</h1>
<div class="alert alert-danger">O cadastro não existe!</div>
		<?php


	} else {

		$sql = "select * from TABLES where TABLE_SCHEMA = ? and TABLE_NAME = ? limit 1 ";
        $consulta2 = $is->prepare($sql); 
		$consulta2->bindParam(1, $banco); 
		$consulta2->bindParam(2, $table); 
		$consulta2->execute();
		$r = $consulta2->fetch(PDO::FETCH_OBJ);	

		$dados = explode(",",$r->TABLE_COMMENT);
		$i = $dados[3];
		$icone = $icons[$i];


?>

<h1 class="page-header">
    
    	<div class="row">
    		<div class="col-md-7 col-sm-6">
    			Cadastrar <?=$dados[1];?>
    		</div>
    		<?php if ($table != "configuracao") { ?>
    		<div class="col-md-2 col-sm-2">	
    			<a href="cadastro/<?php echo $table; ?>" title="<?php echo $table; ?>" class="btn btn-success m">
    				<i class="glyphicon glyphicon-file"></i> Novo Registro
    			</a>
    			
    		</div>
    		<div class="col-md-3 col-sm-4">
    			
    			<form name="form1" method="get" action="listar/<?php echo $table; ?>">
		    		<div class="input-group">
				      <input type="text" name="palavra" class="form-control" placeholder="Buscar por...">
				      <span class="input-group-btn">
				        <button class="btn btn-default" type="submit">
				        	<i class="glyphicon glyphicon-search"></i>
				        </button>
				      </span>
				    </div><!-- /input-group -->
		    	</form>
		    	
    		</div>
    		<?php } ?>
    	</div>
    
</h1>
<ol class="breadcrumb">
    <li>
        <i class="fa fa-dashboard"></i>  <a href="home">Dashboard</a>
    </li>
    <li class="active">
        <i class="<?=$icone;?>"></i> Cadastrar <?=$dados[1];?>
    </li>
</ol>

<form name="form1" novalidate method="post" action="salvar/<?php echo $table; ?>" enctype="multipart/form-data" >
	<fieldset>
		<legend>Preencha todos os dados corretamente:</legend>
		<?php
			if (!empty($id)) {
				
				$sql = "select * from $table where id = ".(int)$id." limit 1";
				$consulta_t = $db->prepare($sql); 
				$consulta_t->execute();
				$rt = $consulta_t->fetch(PDO::FETCH_OBJ);
											
			} 
			//vai guardar os script para selecionar as chaves dos selects
			$script2 =	$script = "";
			$sql = "select TABLE_NAME,COLUMN_NAME,DATA_TYPE,
				CHARACTER_MAXIMUM_LENGTH,
				COLUMN_KEY,EXTRA,COLUMN_COMMENT,IS_NULLABLE
				from COLUMNS 
				where TABLE_SCHEMA = ? 
				AND TABLE_NAME = ?";
			$consulta = $is->prepare($sql); 
			$consulta->bindParam(1, $banco); 
			$consulta->bindParam(2, $table); 
			$consulta->execute();

			while ($row = $consulta->fetch(PDO::FETCH_OBJ)) {
				
				$coluna = codifica($row->COLUMN_NAME);
                $max = $row->CHARACTER_MAXIMUM_LENGTH;
                $key = $row->COLUMN_KEY;
                $com = $row->COLUMN_COMMENT;
				$nn = $row->IS_NULLABLE;
				$rid = "";
				if (!empty($rt->id)) $rid = $rt->id;

				//*****************************
				$c = explode(",",$com);
				$label = ($c[0]);
				echo "<div class=\"control-group\">
							<label for='$coluna' class=\"control-label\" >$label :</label>
							<div class=\"controls\">";
				
				//*****************************
				$x = $m = $b = $v ="";
				
				//****** regras null
				if ($nn == "NO") {
					$b = "required
					data-validation-required-message='Por favor preencha corretamente o $label' ";
				}
				//****** regras mascaras
				if (@$c[1] == "mk") {
					
					if ($c[2] == "data") {
						
						$v = "value='".date("d/m/Y")."' ";
						
						$m = " data-mask=\"99/99/9999\"	 ";

					}  else if ($c[2] == "datahora") {
						
						$v = "value='".date("d/m/Y H:i:s")."' ";
						
						$m = " data-mask=\"99/99/9999 99:99:99\" ";

					} else if ($c[2] == "datetime") {
						$m = " data-mask=\"99/99/9999 99:99\"	 ";
					} else if ($c[2] == "nr") {
						$m = " data-mask=\"99\"	 ";
					} else if ($c[2] == "hr") {
						$m = " data-mask=\"99:99 às 99:99\"	 ";
					} else if ($c[2] == "telefone") {
						$m = " data-mask=\"(99) 9999-9999?9\"	 ";
					} else if ($c[2] == "cep") {
						$m = " data-mask=\"99999-999\"	 ";
					} else if ($c[2] == "cpf") {
						$m = " data-mask=\"999.999.999-99\"	 ";
					} else if ($c[2] == "hora") {
						$m = " data-mask=\"99:99\"	 ";
					} else if ($c[2] == "cnpj") {
						$m = " data-mask=\"99.999.999/9999-99\"	 ";
					} else if ($c[2] == "number") {
						$m = " data-mask=\"9?9999\"	 ";
					} else if ($c[2] == "porcent") {
						$m = " data-mask=\"9?99\"	 ";
					}  else if ($c[2] == "valor") {
						$script2 .= "<script>
						$(function(){
					        $(\"#".$coluna."\").maskMoney({symbol:'R$ ', 
								showSymbol:true, thousands:'.', decimal:',', symbolStay: true});
						
					    })
						</script>";
					}
					
				}
				
				
				
				if (!empty($id)) { 
					
					if (@$c[1] == "mk") {
						if ($c[2] == "data") {
							$d = explode("-",$rt->$coluna);
							$d = $d[2]."/".$d[1]."/".$d[0];
							$rt->$coluna = $d;
						} else if ($c[2] == "datahora") {
							$d1 = explode(" ",$rt->$coluna);

							$d = explode("-",$d1[0]);


							$d = $d[2]."/".$d[1]."/".$d[0];
							$rt->$coluna = $d." ".$d1[1];
						} 
					
					} else if ((@$c[1] == "file") and (@$c[2] == "imagem")) {
						
						if (!empty($rt->$coluna))
							$im = "<img src='$pastaFotos/".$rt->$coluna."p.jpg' title='$coluna' class='thumbnail' width='120'/>";
						
					}
				
					if ($coluna != "senha") {
						$v = " value = '".$rt->$coluna."' "; $x = $rt->$coluna;
					}
				} 
				if ($key == "PRI") {
					echo "
								<input type='text' name='$coluna' id='$coluna'
								class='form-control' $v readonly />
							";	
				} else if ($coluna == "senha") {

					if ( empty( $rt->id ) )
						echo "<input type='password' name='$coluna' id='$coluna' 
						class='form-control' maxlenght='$max' $v $b $m
						placeholder='Digite a senha'
						data-validation-required-message='Digite uma senha' />";
					else 
						echo "<input type='password' name='$coluna' id='$coluna' 
						class='form-control' maxlenght='$max' 
						placeholder='Digite a senha'
						>";
					$s2 = "";
						
						"<div class=\"control-group\">
							<label for='$coluna' class=\"control-label\" >Digite a senha novamente :</label>
							<div class=\"controls\">
								<input type='password' id='senha2'
								placeholder='Digite a senha' class='form-control'
								data-validation-match-match='senha'
								data-validation-required-message='Redigite a senha'
								data-validation-match-message='A senha redigitada não é igual a senha'>
							";
					
				} else if (@$c[3] == "ajax") {
					$dados = explode(";",$c[4]);
					$campo = $dados[0];
					$tabela = $dados[1];

					echo "<input type='text' name='$coluna' id='$coluna' 
					class='form-control' maxlenght='$max'  $v $b $m
					placeholder='Digite o(a) $coluna' onblur=\"getAjax(this,'$campo','$tabela','$rid')\">";

                } else if (@$c[1] == "") {
                    echo "<input type='text' name='$coluna' id='$coluna' 
					class='form-control' maxlenght='$max'  $v $b $m
					placeholder='Digite o(a) $coluna' >";
                } else if (@$c[1] == "file") {
					
					if (!empty($id))  $b = "";

					if (!empty($v)) $b = "";
					
                	echo "<input type='file' name='$coluna' id='$coluna' 
					maxlenght='$max'  $v class='form-control' $b />";
                	if (!empty($id)) {
						$img = $rt->$coluna;
						
						if (file_exists($pastaFotos.$img."p.jpg")) {
						
							echo "<div class='img".$coluna."'>
								<img src='$base2".$img."p.jpg' alt='Imagem' width='100' />
								<a href=\"javascript:deletarImagem('$pastaFotos".$img."','$coluna','$table','$id')\" title='Apagar Imagem' class='btn btn-danger glyphicon glyphicon-trash'>
								</a>
							</div>";	
							
						}
					}
                } else if ($c[1] == "select") {
					
					if (($tt == "Colunista") and ($coluna == "ativo")) {

						$ativo = "Não";
						if (isset($rt->$coluna)) $ativo = $rt->$coluna;

						echo "<input type='text' readonly name='ativo' value='$ativo' class='form-control'>";

					} else {
					
	                	echo "<select name='$coluna' id='$coluna' class='form-control' $b>";
	                    echo "<option value=''>Selecione um(a) $coluna</option>";
	                    $op = explode(";",$c[2]);
	                    foreach ($op as $o) {
	                    	$s = ""; 
							if (!empty($id)) if ($rt->$coluna == $o) $s = "selected=\"selected\" " ;
							echo "<option $s>$o</option>";
	                    }
	                    echo "</select><!-- //select $coluna //-->
	                    ";
						
						$script .= "$('#".$coluna."').val('".@$rt->$coluna."');";

					}
					
					
                } else if ($c[1] == "fk") {
                    $fk = explode("_",$coluna);
                    $fk = $fk[0];
                    
                    /*if ($fk == "funcionario") {


                    	if (empty($rt->$coluna)) {
                    		$uid = $_SESSION["admin"]["id"];
                    		$user = $_SESSION["admin"]["nome"];
                    	} else {
                    		$uid = $rt->$coluna;

                    		$sql5 = "select * from funcionario where id = ? limit 1";
                    		$consulta5 = $db->prepare($sql5); 
							$consulta5->bindParam(1, $uid); 
							$consulta5->execute();
							$row5 = $consulta5->fetch(PDO::FETCH_OBJ);

							$user = $row5->nome;
                    	}

                    	echo "<input type='hidden' name='funcionario_id' 
                    	value='".$uid."'>
                    	<input type='text' value='".$user."' class='form-control'
                    	readonly>";

                    	

                    } else if ( $fk == "cliente") {

                    	$sql_fk = "select * from $fk order by 2";
	                    $consulta_fk = $db->prepare($sql_fk); 
						$consulta_fk->bindParam(1, $fk); 
						$consulta_fk->execute();
						

	                    echo "<select name='$coluna'  id='$coluna' class='form-control' $b>
	                    <option value=''>$label</option>";
	                    
	                    while ($r = $consulta_fk->fetch(PDO::FETCH_NUM)) {

	                    
	                        $i1 = $r[0];
	                        $i2 = $r[1];
	                        $i3 = $r[3];
							
							$s = "";
							
							
	                        echo "<option value='$i1' $s>$i2 ($i3)</option>";
	                    
	                    }
	                    echo "</select>";

                    	$script .= " $('#".$coluna."').val(".@$rt->$coluna."); ";


                    } else {*/

                    if ($fk == "funcionario") {

                    	$sql_fk = "select * from funcionario order by 2";
	                    $consulta_fk = $db->prepare($sql_fk); 
						$consulta_fk->bindParam(1, $fk); 
						$consulta_fk->execute();
						

	                    echo "<select name='$coluna'  id='$coluna' class='form-control' $b>
	                    <option value=''>$label</option>";
	                    
	                    while ($r = $consulta_fk->fetch(PDO::FETCH_NUM)) {

	                    
	                        $i1 = $r[0];
	                        $i2 = $r[1];
	                        $email = $r[4];
							
							$s = "";
							/*if (!empty($id)) {
								if ($rt->$coluna == $i1) $s = "selected=\"selected\" ";		
							}*/
							
	                        echo "<option value='$i1' $s>$i2 ($email)</option>";
	                    
	                    }
	                    echo "</select>";

                    	$script .= " $('#".$coluna."').val(".@$rt->$coluna."); ";
                    

                    } else {	
                    	
                    	$sql_fk = "select * from $fk order by 2";
	                    $consulta_fk = $db->prepare($sql_fk); 
						$consulta_fk->bindParam(1, $fk); 
						$consulta_fk->execute();
						

	                    echo "<select name='$coluna'  id='$coluna' class='form-control' $b>
	                    <option value=''>$label</option>";
	                    
	                    while ($r = $consulta_fk->fetch(PDO::FETCH_NUM)) {

	                    
	                        $i1 = $r[0];
	                        $i2 = $r[1];
							
							$s = "";
							/*if (!empty($id)) {
								if ($rt->$coluna == $i1) $s = "selected=\"selected\" ";		
							}*/
							
	                        echo "<option value='$i1' $s>$i2</option>";
	                    
	                    }
	                    echo "</select>";

                    	$script .= " $('#".$coluna."').val(".@$rt->$coluna."); ";
                   
                    }

				} else if ($c[1] == "text") {
					
				
					echo "<textarea class=\"textarea form-control\" style='height:250px;width:700px'
					placeholder=\"Digite seu texto\" name='$coluna'  $b $m>$x</textarea>";
					//echo "<textarea class=\"form-control\" style='height:250px;width:700px'
					//placeholder=\"Digite seu texto\" name='$coluna'  $b $m>$x</textarea>";
					
				} else if ($coluna == "email") {
					echo "<input type='text' name='$coluna' id='$coluna' 
					class='form-control' maxlenght='$max' $v $b $m
					placeholder='Digite um e-mail válido'
					data-validation-email-message='Digite um endereço válido'>";
				} else {
					echo "<input type='text' name='$coluna' id='$coluna' 
					class='form-control' maxlenght='$max'  $v $b $m
					placeholder='Digite o(a) $label'>";
				}
				
				
				
				echo "</div>
			</div> <!--// control-group //-->"; //fim do control-group
			echo @$s2;	
			}

		?>
		<button type="submit" class="btn btn-primary pull-right">
			<i class="glyphicon glyphicon-ok"></i> Salvar/Atualizar Registro</button>
		</button>
	</fieldset>

	

	<script>
		$(function () { $("input,select,textarea").not("[type=submit]").jqBootstrapValidation(); } );
		
		function deletarImagem(img,coluna,tabela,id) {
			if (confirm("Deseja mesmo excluir esta imagem?")) {
				$(".img"+coluna).html("<img src='images/loading.gif' title='Aguarde' alt='Aguarde'/> Aguarde...");
				$.post("pages/excluirImagem.php",{img:img,coluna:coluna,tabela:tabela,id:id},function(data) {
					$(".img"+coluna).html("<br>"+data);
				})
			}
		}
		function getAjax(sub,campo,table,id) {
			
			var s = sub.value;
			if (campo != "") {
				$.get("pages/ajax.php",{id:id,sub:s,campo:campo,table:table},function(data) {
					if (data != "") {
						alert(data);
						$("#"+campo).focus();
					}
				})
			}
		}
		function excluirFoto(id,tabela,cid) {
			if (confirm("Deseja mesmo excluir esta imagem?")) {
				$("#foto"+id).html("<img src='images/loading.gif' title='Aguarde' alt='Aguarde'/> Aguarde...");
				$.post("pages/excluirFoto.php",{id:id},function(data) {
					//location.href='cadastro/'+tabela+'/'+cid;
					$("#foto"+id).html(data);
				})
			}
		}
		function gravarDescricao(id,descricao) {
			
				$.post("pages/descricao.php",{id:id,descricao:descricao},function(data) {
					alert(data);
				})
			
		}
	</script>
	<?php echo $script2; ?>
	<script type="text/javascript" charset="utf-8">
		<?php echo $script; ?>
		
			$('.textarea').summernote();
		
	</script>
</form>



<?php 
		if ((isset($dados[5])) and ($dados[5] == "foto") and (!empty($id))) {
			echo "<h2 id='fotos'>Inserir Fotos:</h2>
				<form name='formFoto' method='post' target='iframe' enctype='multipart/form-data' action='pages/inserirFoto.php'>

				<input type='hidden' name='id' value='$id'>
				<input type='hidden' name='tabela' value='$table'>
				<div class='control-group'>
					<label for='imagem' class='form-label'>Imagens (selecione até 5 imagens JPG por vez):</label>
					<div class='controls'>
						<input type='file' name='fotos[]' class='form-control' required multiple data-validation-required-message='Selecione ao menos um arquivo JPG'>
					</div>
				</div>
				<button type='submit' class='btn btn-success pull-right'><i class='glyphicon glyphicon-picture'></i> Enviar Fotos</button>
				</form>
				<iframe name='iframe' width='100%' height='100px' style='display:none'></iframe>
				<h3>Fotos Inseridas:</h3>
				<div class='thumbnail'>";
					

					$sql = "select * from foto where ".$table."_id = ".(int)$id;
					$consulta = $db->prepare($sql);
					$consulta->execute();

					$c = (int)$consulta->rowCount();

					echo "<p>Existem $c fotos:</p>
					<br>
					<div class='row'>";
					while ($row = $consulta->fetch(PDO::FETCH_OBJ)) {

						$foto = $base2.$row->foto.'p.jpg';
						$descricao = $row->descricao;
						$i = $row->id;

						echo "<div class='col-md-3 col-sm-3 col-xm-6 text-center' id='foto".$i."'>
							<img src='$foto' alt='$descricao' title='$descricao' height='80px'>
							<br><br>
							<div class=\"input-group\">
									<input type='text' class='form-control' placeholder='Adicione uma descrição'
									onblur='gravarDescricao($i,this.value)' value='$descricao'>
									<span class=\"input-group-btn\">
										<button type='button' class='btn btn-danger' onclick=\"excluirFoto($i,'$table',$id)\"
										title='Apagar imagem'>
										<i class='glyphicon glyphicon-trash'></i>
										</button>
									</span>
							</div>
							<br><br>					
						</div>";

					}

			echo "</div>
			</div>";	
		}

	}
} ?>