<?php
require 'app/bootstrap.php';
$conectDB = connectDB();
$conectDB->exec("set names utf8mb4");
include '__valida_login.php';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <title><?=$configSistema['sistema'];?> - Design da Página Inicial</title>
	<?php
		include 'estrutura/__css.php';
	?>
	<style type="text/css">
		#userActions {
			height: 250px;
			width: 500px;
			object-fit: contain;
		}
		#userActions .title{
			margin-top: 260px;
		}
	</style>
</head>
<body>
    <div class="app  ">
        <div class="layout ">
			<?php
				include 'estrutura/topo.php';
				include '_menu.php';
				
				$titulo = 'Edição de Login'; 
			?>
            <div class="page-container">
                <div class="main-content">
                   <div class="card  ">
                        <div class="card-body"> 
                            <h4 class=" ">Design da Página Inicial</h4>
                            <div class="">
								<div class="m-t-15">
									<?php

					  					$userCode	  		= $_SESSION['userCode'];

										if (!file_exists('assets/storage/'.$userCode)) {
										    mkdir('assets/storage/'.$userCode, 0777, true);
										}
										$pastaAnuncio = 'assets/storage/'.$userCode.'/';

										if ($_SERVER['REQUEST_METHOD'] === 'POST')
										{
											//print_r($_POST);exit;
											$home_header_titulo    	  = stringInputCleaner($_POST['home_header_titulo']);
											$home_header_descricao    = stringInputCleaner($_POST['home_header_descricao']);
											$home_imoveis_destaque_total    = stringInputCleaner($_POST['home_imoveis_destaque_total']);
											$home_imoveis_total    		= stringInputCleaner($_POST['home_imoveis_total']);
											$home_exibir_corretores     = stringInputCleaner($_POST['home_exibir_corretores']);
  
									        $cadinsert = "
												UPDATE
													site
												SET
													home_header_titulo = :home_header_titulo,
													home_header_descricao = :home_header_descricao,
													home_imoveis_destaque_total = :home_imoveis_destaque_total,
													home_imoveis_total = :home_imoveis_total,
													home_exibir_corretores = :home_exibir_corretores
												WHERE
													usuario_id 	= :userID
									        ";
									            $cadresult = $conectDB->prepare($cadinsert);
									            $cadresult->bindParam(':home_header_titulo' , $home_header_titulo, PDO::PARAM_STR);
									            $cadresult->bindParam(':home_header_descricao' , $home_header_descricao, PDO::PARAM_STR);
									            $cadresult->bindParam(':home_imoveis_destaque_total' , $home_imoveis_destaque_total, PDO::PARAM_STR);
									            $cadresult->bindParam(':home_imoveis_total' , $home_imoveis_total, PDO::PARAM_STR);
									            $cadresult->bindParam(':home_exibir_corretores' , $home_exibir_corretores, PDO::PARAM_STR);
									            $cadresult->bindParam(':userID' , $_SESSION['userID'], PDO::PARAM_STR);
									            if($cadresult->execute()){

									            	//upload image profile
									            	if (!empty($_FILES['fileProfile']))
									            	{
														$error 		= array();
														$extension 	= array("jpeg","jpg","png","gif","webp");
														
														$file_name =$_FILES["fileProfile"]["name"];
														$file_tmp  =$_FILES["fileProfile"]["tmp_name"];
														if(!empty($_FILES['fileProfile']['name'])){
															if($_FILES['fileProfile']['size'] > 0)
															{
																$ext=pathinfo($file_name,PATHINFO_EXTENSION);
																if(in_array($ext,$extension))
																{
																	$filename 		= basename($file_name,$ext);
																	$newFileName 	= $userCode.'.headerBG.'.uniqid(time(), true).".". $ext;
																	
																	if(move_uploaded_file($file_tmp, $pastaAnuncio.$newFileName))
																	{
																        $cadinsert = "
																			UPDATE
																				site
																			SET
																				home_header_imagem 	= :home_header_imagem
																			WHERE
																				usuario_id 	= :usuario_id
																        ";
																         
																            $cadresult = $conectDB->prepare($cadinsert);
																            $cadresult->bindParam(':usuario_id' , $_SESSION['userID'], PDO::PARAM_STR);
																            $cadresult->bindParam(':home_header_imagem' , $newFileName, PDO::PARAM_STR);
																            if( $cadresult->execute() )
																            {
																            	 
																            }
																    }
																}
															}
														}
									            	}
										            	//upload image profile

									                echo mensagem('sucesso', 'Registro atualizado com sucesso', '', '');
									            }
									            else
									            {
									            	 echo mensagem('sucesso', 'Alterações realizadas ou sem alterações', '', '');
									            }
										}

										$configuracoesSite = findItem($conectDB, 'site', ' * ', array("usuario_id"=>$_SESSION['userID']) );
									?>
									<form method="post" action="" id="" enctype="multipart/form-data">
										<div class="card"> 
											<div class="card-body">
 												<div class="upload-file mb-16 text-center">
												  	<div id="userActions" class="m-auto px-6 mb-7"  style="background: url(<?=$pastaAnuncio.@$configuracoesSite->home_header_imagem;?>)">
														<label for="fileUpload" class="title mb-0 font-size-4 text-smoke">Selecionar Capa - 2000 x 1000 px</label>
														<input type="file" id="fileUpload" name="fileProfile" class="sr-only" />
												  	</div>
 												  	<img id="imgPrime" src="" alt="">
												  	<!-- <input type="file" id="upfile"> -->
												</div>
												
												<div class="row mb-xl-1 mb-9 m-t-25">
													<div class="col-lg-12">
														<h4>Textos da Página Inicial</h4>
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Título</label>
															<input type="text" maxlength="40" class="form-control h-px-48" name="home_header_titulo" value="<?=@$configuracoesSite->home_header_titulo;?>" required required_m="Nome Obrigatório">
														</div>
													</div>
													<div class="col-lg-12">
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Texto Descritivo</label>
															<input type="text"  maxlength="200" class="form-control h-px-48" name="home_header_descricao" value="<?=@$configuracoesSite->home_header_descricao;?>">
														</div>
													</div>
												</div>

												<div class="row mb-xl-1 mb-9 m-t-25">
														<div class="col-lg-12">
															<h4>Imóveis na página inicial</h4>
														</div>
													<div class="col-lg-4">
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Exibir quantos imóveis em Destaque na página inicial</label>
															<select  class="form-control h-px-48" name="home_imoveis_destaque_total">
																<option value="0" <?= ($configuracoesSite->home_imoveis_destaque_total == '0') ? ("selected") : ("");?>>0</option>
																<option value="3" <?= ($configuracoesSite->home_imoveis_destaque_total == '3') ? ("selected") : ("");?>>3</option>
																<option value="6" <?= ($configuracoesSite->home_imoveis_destaque_total == '6') ? ("selected") : ("");?>>6</option>
																<option value="12" <?= ($configuracoesSite->home_imoveis_destaque_total == '12') ? ("selected") : ("");?>>12</option>
															</select>
														</div>
													</div>
													<div class="col-lg-4">
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Exibir quantos imóveis na página inicial</label>
															<select  class="form-control h-px-48" name="home_imoveis_total">
																<option value="0"  <?= ($configuracoesSite->home_imoveis_total == '0') ? ("selected") : ("");?>>0</option>
																<option value="3" <?= ($configuracoesSite->home_imoveis_total == '3') ? ("selected") : ("");?>>3</option>
																<option value="6" <?= ($configuracoesSite->home_imoveis_total == '6') ? ("selected") : ("");?>>6</option>
																<option value="12" <?= ($configuracoesSite->home_imoveis_total == '12') ? ("selected") : ("");?>>12</option>
															</select>
														</div>
													</div>

													<div class="col-lg-4">
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Exibir Corretores na página inicial</label>
															<select  class="form-control h-px-48" name="home_exibir_corretores">
																<option value="1"  <?= ($configuracoesSite->home_exibir_corretores == '1') ? ("selected") : ("");?>>Sim</option>
																<option value="2"  <?= ($configuracoesSite->home_exibir_corretores == '2') ? ("selected") : ("");?>>Não</option>
															</select>
														</div>
													</div>
												</div>

													<div class="row">
														<div class="col-sm-3 text-left">
															<button type="submit" class="btn  btn-primary m-r-5">
																<i class="anticon anticon-loading m-r-5"></i>
																<i class="anticon anticon-check m-r-5"></i>
																<span>Salvar</span>
															</button>
														</div>
													</div>
											</div>
										</div>
									</form> 
								
								</div>
							</div>
						</div>
					</div>
                </div>
				
				<?php include 'estrutura/copy.php';?>	
            </div>
         </div>
    </div>
	<?php include 'estrutura/rodape.php';?>
	<?php include 'estrutura/_modal_admin.php';?>

	<link href="assets/vendors/izoColorPicker_1.0/izoColorPicker.css" rel="stylesheet">    
	<script src="assets/vendors/izoColorPicker_1.0/izoColorPicker.js"></script>

	<style type="text/css">
		 
	</style>
	
	<?php //include '_rodape.php';?>
  </div>

   
  <link rel="stylesheet" href="https://www.jqueryscript.net/demo/Bootstrap-4-Chosen-Plugin/dist/css/component-chosen.css" />
	 

  <?php include 'estrutura/__js.php';?>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js" integrity="sha512-rMGGF4wg1R73ehtnxXBt5mbUfN9JUJwbk21KMlnLZDJh7BkPmeovBuddZCENJddHYYMkCh9hPFnPmS9sspki8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script type="text/javascript">
  	 
    $(".estados, .selectCidade").chosen( {
        width: "100%",
        placeholder_text_multiple: "Selecione",
        placeholder_text_single: "Selecione"
    });

	    $("#disciplinas, #curso_superior").chosen( {
	        width: "100%",
	        placeholder_text_multiple: "Selecione",
	        placeholder_text_single: "Selecione"
	    });


    $('.selectEstado').on('change', function(){
        var estado = $(this).val();
        $elementCitie = $(".selectCidade");

        $('.selectCidade option').prop('selected', false).trigger('chosen:updated');
        $elementCitie.html("");    
        $elementCitie.chosen().trigger('chosen:updated');

        $.getJSON('app/get/cities', {
                estadoID: estado,
                ajax: 'true'
            }, function(j){
            var options = '<option value=""></option>';
            for (var i = 0; i < j.length; i++) {

                $elementCitie.append('<option value="'+j[i].cityID+'">' + j[i].cityName + '</option>');
                 
            }
            
            $elementCitie.trigger("chosen:updated");
             
        });
    });

 
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#userActions').css('background', ' url('+e.target.result+')');
            $(".imageUpTextDemo").fadeIn(200);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

	$("#fileUpload").change(function(){
	    readURL(this);
	});

  	
    $(function(){
        $('.colorPicker').izoColorPicker({
            buttonApplyTitle:'Selecionar',
            buttonCancelTitle:'Cancelar',
            myColors: '',
            onApply: (color)=>{ 
                console.log('Selected color: '+color) 
            },
            onSave: (color,colors)=>{ 
                console.log('Saved color: '+color)
                console.log('Saved color list: '+ colors.join())
            },
            onRemove: (color,colors)=>{ 
                console.log('Removed color: '+color)
                console.log('Saved color list: '+ colors.join())
            }
        })                	
    })
  </script>

</body>
</html>