<?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 do Site</title>
	<?php
		include 'estrutura/__css.php';
	?>
</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 do Site</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;
											$nome    	 = stringInputCleaner($_POST['nome']);
											$telefone    = stringInputCleaner($_POST['telefone']);
											$whatsapp    = stringInputCleaner($_POST['whatsapp']);
											$email    	 = stringInputCleaner($_POST['email']);
											$link_segunda_via    	 = stringInputCleaner($_POST['header_link_segunda_via']);
											
											$facebook    = stringInputCleaner( str_replace("@", "", $_POST['facebook']));
											$instagram   = stringInputCleaner( str_replace("@", "", $_POST['instagram']));
											
											if(!preg_match('/^[a-zA-Z0-9]{5,}$/', $facebook)) {
												$facebook = '';
												echo mensagem('erro', 'O nome de usuário do Facebook é inválido', '', '');
											}
												if(!preg_match('/^[a-zA-Z0-9]{5,}$/', $instagram)) {
													$instagram = '';
													echo mensagem('erro', 'O nome de usuário do instagram é inválido', '', '');
												}


											$cor_base    = stringInputCleaner($_POST['corBase']);
  
									        $cadinsert = "
												UPDATE
													site
												SET
													nome = :nome,
													telefone = :telefone,
													celular = :whatsapp,
													email = :email,
													facebook = :facebook,
													instagram = :instagram,
													cor_base = :cor_base,
														header_link_segunda_via = :link_segunda_via
												WHERE
													usuario_id 	= :userID
									        ";
									            $cadresult = $conectDB->prepare($cadinsert);
									            $cadresult->bindParam(':nome' , $nome, PDO::PARAM_STR);
									            $cadresult->bindParam(':telefone' , $telefone, PDO::PARAM_STR);
									            $cadresult->bindParam(':whatsapp' , $whatsapp, PDO::PARAM_STR);
									            $cadresult->bindParam(':email' , $email, PDO::PARAM_STR);
									            $cadresult->bindParam(':facebook' , $facebook, PDO::PARAM_STR);
									            $cadresult->bindParam(':instagram' , $instagram, PDO::PARAM_STR);
									            $cadresult->bindParam(':cor_base' , $cor_base, PDO::PARAM_STR);
									            $cadresult->bindParam(':link_segunda_via' , $link_segunda_via, 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.'.'.uniqid(time(), true).".". $ext;
																	
																	if(move_uploaded_file($file_tmp, $pastaAnuncio.$newFileName))
																	{
																		 
																		//cria ícone do logotipo
																			require 'app/libs/RDSImage.php';
																			
																			$imagePath 	= $pastaAnuncio.$newFileName;
																			$newPath 	= $pastaAnuncio;
																			$ext 		= '.jpg';
																			$newName  = "resized.".$newFileName;
																			$copied = copy($imagePath , $newPath.$newName);
																			
																			//redimensiona  
																				sleep(1);
																				$maxDim = 100;
																				$arquivoRedimensiona = $newPath.$newName;
																				list($width, $height, $type, $attr) = getimagesize( $arquivoRedimensiona );
																				if ( $width > $maxDim || $height > $maxDim ){
																					$target_filename = $arquivoRedimensiona;
																					$ratio = $width/$height;
																					if( $ratio > 1) {
																						$new_width = $maxDim;
																						$new_height = $maxDim/$ratio;
																					} else {
																						$new_width = $maxDim*$ratio;
																						$new_height = $maxDim;
																					}
																					$src = imagecreatefromstring( file_get_contents( $arquivoRedimensiona ) );
																					$dst = imagecreatetruecolor( $new_width, $new_height );
																					imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
																					imagedestroy( $src );
																					imagepng( $dst, $target_filename ); // adjust format as needed
																					imagedestroy( $dst );
																				}
																			//redimensiona  
																			/*
																			$image = new RDSImage();
																			$image->setSourceImage($pastaAnuncio.$newFileName);
																			$image->setNewWidth(100);
																			$image->setDestination($pastaAnuncio);
																			$image->create('resized.'.$newFileName);
																			*/
																		//cria ícone do logotipo
																		
																        $cadinsert = "
																			UPDATE
																				site
																			SET
																				logo 	= :logo,
																				logo_menor 	= :logo_menor
																			WHERE
																				usuario_id 	= :usuario_id
																        ";
																            $cadresult = $conectDB->prepare($cadinsert);
																            $cadresult->bindParam(':usuario_id' , $_SESSION['userID'], PDO::PARAM_STR);
																            $cadresult->bindParam(':logo' , $newFileName, PDO::PARAM_STR);
																			$cadresult->bindParam(':logo_menor' , $newName, PDO::PARAM_STR);
																            if( $cadresult->execute() )
																            {
																            	$_SESSION['userFoto'] = $newFileName;

																            }
																    }
																}
															}
														}
									            	}
										            	//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="square-144 m-auto px-6 mb-7"  style="background: url(<?=$pastaAnuncio.@$configuracoesSite->logo;?>)">
														<label for="fileUpload" class="title mb-0 font-size-4 text-smoke">Selecionar Logotipo</label>
														<input type="file" id="fileUpload" name="fileProfile" class="sr-only" />
												  	</div>
												  	<span class="text-muted font-size-2 imageUpTextDemo">Clique em Salvar Alterações</span>
												  	<img id="imgPrime" src="" alt="">
												  	<!-- <input type="file" id="upfile"> -->
												</div>
												
												<div class="row mb-xl-1 mb-9">
													<div class="col-lg-12">
														<h4>Dados de Contato</h4>
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Nome da Empresa</label>
															<input type="text" class="form-control h-px-48" name="nome" value="<?=@$configuracoesSite->nome;?>" required required_m="Nome Obrigatório">
														</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 ">Telefone</label>
															<input type="text" class="form-control h-px-48 celular" name="telefone" value="<?=@$configuracoesSite->telefone;?>">
														</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 ">WhatsApp</label>
															<input type="text" class="form-control h-px-48 celular" name="whatsapp" value="<?=@$configuracoesSite->celular;?>">
														</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 ">E-mail</label>
															<input type="email" class="form-control h-px-48" name="email" value="<?=@$configuracoesSite->email;?>">
														</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 ">Facebook: @nomeUsuario</label>
															<input type="text" class="form-control h-px-48" name="facebook" value="<?=@$configuracoesSite->facebook;?>">
														</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 ">Instagram: @nomeUsuario</label>
															<input type="text" class="form-control h-px-48" name="instagram" value="<?=@$configuracoesSite->instagram;?>">
														</div>
													</div>
												</div>
												<div class="row mb-xl-1 mb-9">
													<div class="col-lg-12">
														<h4></h4>
														<div class="form-group">
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Link para 2º Via de Boletos</label>
															<input type="text" maxlength="40" class="form-control h-px-48" name="header_link_segunda_via" value="<?=@$configuracoesSite->header_link_segunda_via;?>">
														</div>
													</div>
												</div>
												<div class="row mb-xl-1 mb-9">
													<div class="col-lg-4">
														<h4>Design</h4> 
															<label for="namedash" class="d-block text-black-2 font-size-4 font-weight-semibold ">Cor base do site</label>
															<div class="input-group  colorPicker" data-color="<?=@$configuracoesSite->cor_base;?>">
															    <input type="text" class="form-control"  name="corBase" value="<?=@$configuracoesSite->cor_base;?>">
															    <button class="btn btn-default" type="button">&nbsp;</button>
															</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>
