<?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'];?> - Importar Imóveis</title>
	<?php
		include 'estrutura/__css.php';
	?>
</head>
<body>
    <div class="app ">
        <div class="layout  ">
			<?php
				include 'estrutura/topo.php';
				include '_menu.php'; 
			?>
            <div class="page-container">
                <div class="main-content">
                     
                   <div class="card  ">
                        <div class="card-body"> 
							 
							<div class="row">
								<div class="col-xs-12 col-lg-12">
									<h1>Importar Imóveis</h1>
									 
									<hr>
								</div> 
							</div>

															
								<form class="form-horizontal" id="frmSaqueSolicita" method="POST" action="" enctype="multipart/form-data">
									<div class="row  ">
										<div class="col-sm-6 col-xs-12"> 
											<label >Token de Acesso a Gerencie Sistemas</label>

											<div class="input-group">
												<div class="input-group-prepend">
													<span class="input-group-text">Token:</span>
												</div>
												<?php
													$dadosUser = findItem($conectDB, 'usuario', ' gerenciador_imobiliario_token ', array("id"=>$_SESSION['userID']) );
												?>
												<input  type="text" id="token" name="token" value="<?=$dadosUser->gerenciador_imobiliario_token;?>" class="form-control" required required_m="" aria-label="">
											</div>
											<div class=" mb-3"><a href="#" target="_blank">Veja como obter o seu token</a></div>
										</div> 
									</div> 
										<div class="row">
											<div class="col-xs-12 col-sm-6">
												<div class="pack_custom_msg" style="color:red"></div>
												<div class="form-group ">
													<button type="submit" class=" btn btn-xs btn-primary">
														<i class="fa fa-search"></i> Buscar Informações
													</button> 
												</div>
												
											</div>
										</div>
								</form>
									<div class="row ">
										<div class="col-xs-12 col-sm-12">
											<?php
												if ($_SERVER['REQUEST_METHOD'] === 'POST') {
													$token  = stringInputCleaner($_POST['token']);

													$ch = curl_init($configSistema['apiBaseURL'].'importa');
													curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
													curl_setopt($ch, CURLOPT_HTTPHEADER, array(
													   'Content-Type: application/json',
													   'Authorization: '.$token
													 ));
													curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
													curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
													$data = curl_exec($ch);
													//print_r($data); 
													$retorno = json_decode($data);
 													
													if( (isset($retorno->status)) && ($retorno->status == 'error') )
													{
														echo mensagem("erro", $retorno->message);
													}
													else
													{
													 
												        $cadinsert = "
															UPDATE
																usuario
															SET
																gerenciador_imobiliario_token 	= :token
															WHERE
																code 	= :code
												        ";
												        $userCode	  		= $_SESSION['userCode'];
											            $cadresult = $conectDB->prepare($cadinsert);
											            $cadresult->bindParam(':code' , $userCode, PDO::PARAM_STR);
											            $cadresult->bindParam(':token' , $token, PDO::PARAM_STR);
											            $cadresult->execute();
												        

												        //display table with data
												     ?>	
														<form class="form-horizontal" id="formImport" method="POST" action="app/imoveis/importar" enctype="multipart/form-data"> 
															<table class="table  table-bordered table-hover " id="sample_lead" style="width: 100%">
																<thead>
																	<tr>
																		<th class="all"> </th>	
																		<th class="all"> Título</th>
																		<th class="all"> Tipo</th>
																		<th class="all"> Valor</th>
																		<th class="all"> Rua</th>
																		<th class="all"> Cadastrado </th>
																	</tr>
																</thead>
																<tbody>
																	<?php
																		//$dataRetorno = json_decode($data);
																		//print_r($data);

																		$dataRetorno = json_decode($data,true);//converts in array
																		foreach($dataRetorno['itens'] as $keys=>$value){
																			
																			//checasejafoiimportado
																			$jaImportado = '
																				<div class="checkbox">
																					<input id="checkbox'.$value['id'].'" type="checkbox" name="imovelID[]" value="'.$value['id'].'" checked="">
																					<label for="checkbox'.$value['id'].'"> </label>
																				</div>
																			';
																			$checaImovelImportado = findItem($conectDB, 'imovel', ' id ', array("gerencie_imovel_id" => $value['id']) );
																			if( !empty($checaImovelImportado->id))
																			{
																				$jaImportado = 'Já Importado';
																			}
																			echo 
																			'
																				<tr >
																					<td >
																						'.$jaImportado.'
																					</td>
																					<td >'.$value['titulo'].'</td>
																					<td >'.$value['categoria'].'</td>
																					<td >R$ '.currency($value['valor']).'</td>
																					<td >'.$value['rua'].'</td>
																					<td >'.date("d/m/Y H:i", strtotime($value['data_criacao'])).'</td>
																					
																				</tr>
																			';
																		}
																	?>
																</tbody>
															</table>
															<button type="button" class="submit btn btn-primary">
																<i class="fa fa-download"></i> Importar Imóveis Selecionados
															</button> 
														</form>
												     <?php
												        
													}
												}
											?>
										</div>
									</div>
								

						</div>
					</div>
                </div>
				
				<?php include 'estrutura/copy.php';?>	
            </div>
         </div>
    </div>
	<?php include 'estrutura/rodape.php';?>

	<script type="text/javascript">
		$(".importarImoveis").on("click", function()
		{
			var token	 		= jQuery("#token").val();
	        jQuery.post("app/imoveis/importar",
	        {
	            token: token
	        }, function(data)
	        {
				console.log(data);
                var retorno = $.parseJSON( data );
                if(retorno[0]=='erro')
                {
                    Notificacao('error', 'Houve algo de errado', retorno[1]); 
                }
                else if(retorno[0]=='sucesso')
                {
                    Notificacao('success','Sucesso', retorno[1]);
                }
                else if(retorno[0]=='info')
                {
                    Notificacao('info','InformaÃ§Ã£o', retorno[1]);
                }
                else
                {
                    //Notificacao('error',retorno[1]); 
                }
	        });
	 
		})
	</script>
</body>

</html>

