<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

	include_once '../class/auth.php';
    include_once '../config/database.php';
    include_once '../class/imoveis.php';
    include_once '../class/imoveis_imagens.php';


    $database = new Database();
    $db = $database->getConnection();

	//autenticação
	$token = null;
	$headers = apache_request_headers();
	if(isset($headers['Authorization'])){
		$matches = array();
		$token = $headers['Authorization'];
  
		$item = new userGerencieImobiliario($db);
		$item->token = $token;
		$item->getUserToken();
		if($item->users_id != null){
			//$emp_arr = array("usuarioID" =>  $item->users_id);
			http_response_code(200);
			//setcookie('gerenciadorImobiliarioUsuarioID', $item->users_id, time() + (60 * 2), "/");
			$gerenciadorImobiliarioUsuarioID = $item->users_id;
			//echo json_encode($emp_arr);
		}
		else
		{
			http_response_code(404);
			echo json_encode(
				array("status" => "error", "message" => "404 - N&atilde;o autorizado.")
			);
			die();
		}
	}
	else
	{
		http_response_code(401);
        echo json_encode(
            array("status" => "error", "message" => "401 - N&atilde;o autorizado.")
        );
		die();
	}
	

	if(!isset($_GET['imovelID'])){
		http_response_code(404);
        echo json_encode(
            array("status" => "error", "message" => "404 - Imovel inexistente.")
        );
		die();
	}
		if ( filter_var($_GET['imovelID'], FILTER_VALIDATE_INT) === false ) {
			http_response_code(404);
			echo json_encode(
				array("status" => "error", "message" => "404 - Imovel inexistente.")
			);
			die();
		}


		    $itemImagensA = new ImoveisImagens($db);
		    $itemImagensA->id = isset($_GET['imovelID']) ? (int)$_GET['imovelID'] : die();
		   // $itemImagens->getImovelImagensID();
		    $itemImagens = $itemImagensA->getImovelImagensID();

		    $itemCount = $itemImagens->rowCount();
		    if($itemCount > 0){
		        
		        $employeeArr = array();
		        $employeeArr["itens"] = array();
		        $employeeArr["totalItens"] = $itemCount;

		        while ($row = $itemImagens->fetch(PDO::FETCH_ASSOC)){
		            extract($row);
		            $e = array(
						'id' => $id,
						'imagem' => 'https://meusistemas.com.br/gerenciador-imobiliario/assets/storage/'.$gerenciadorImobiliarioUsuarioID.'/imoveis/'.$_GET['imovelID'].'/imagens/'.$imagem,
						'posicao' => $posicao,
	 				);
		            array_push($employeeArr["itens"], $e);
			    }
			      	
			        //http_response_code(200);
			        echo json_encode($employeeArr);
		    }
		    else{
		        http_response_code(404);
				echo json_encode(
					array("status" => "error", "message" => "404 - Registro inexistente.")
				);
				die();
		    }
?>