<?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'];?> - Sistema</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="row">
						<?php
							$totalizadorQuery  = query($conectDB, '', "
								select
									COUNT(id) AS totalImoveis,
									(SELECT COUNT(id) from imovel_galeria WHERE usuario_id = '{$_SESSION['userID']}') AS totalImoveisFotos,
									(SELECT COUNT(id) from imovel_visualizacao WHERE usuario_id = '{$_SESSION['userID']}') AS totalVisitas
								from
									imovel
								WHERE
									usuario_id = '{$_SESSION['userID']}'
							"); 
							$totalizador['totalImoveis'] = $totalizadorQuery[0]->totalImoveis;
							$totalizador['totalImoveisFotos'] = $totalizadorQuery[0]->totalImoveisFotos;
							$totalizador['totalVisitas'] = $totalizadorQuery[0]->totalVisitas;
							
							
							//teste
							$dadosUser = findItem($conectDB, 'usuario', ' gerenciador_imobiliario_token ', array("id"=>$_SESSION['userID']) );
							$token  = $dadosUser->gerenciador_imobiliario_token;
							$ch = curl_init($configSistema['apiBaseURL'].'buscaItem/47');
							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);
							//echo '<pre>';print_r($data); echo '</pre>';
 						?>
 				 
                        <div class="col-md-4 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="media align-items-center">
                                        <div class="avatar avatar-icon avatar-lg avatar-blue">
											<i class="fas fa-home"></i>
                                        </div>
                                        <div class="m-l-15">
                                            <h2 class="m-b-0"><?=$totalizador['totalImoveis'];?></h2>
                                            <p class="m-b-0 text-muted">Total de Imóveis</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="media align-items-center">
                                        <div class="avatar avatar-icon avatar-lg avatar-cyan">
											<i class="fas fa-images"></i>
                                        </div>
                                        <div class="m-l-15">
                                            <h2 class="m-b-0"><?=$totalizador['totalImoveisFotos'];?></h2>
                                            <p class="m-b-0 text-muted">Fotos em Imóveis</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="media align-items-center">
                                        <div class="avatar avatar-icon avatar-lg avatar-orange">
											<i class="fas fa-users"></i>
                                        </div>
                                        <div class="m-l-15">
                                            <h2 class="m-b-0"><?=$totalizador['totalVisitas'];?></h2>
                                            <p class="m-b-0 text-muted">Visitas</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
							 
                    

						<div class="col-lg-12">
							<div class="card">
								<div class="card-body text-center">
									<h5>Visualizações em seus imóveis</h5>
									<div id="chartdiv"></div>	 
								</div>
							</div>
						</div>
                    </div>
                </div>
				<?php include 'estrutura/copy.php';?>	
            </div>
         </div>
    </div>

    

	<?php include 'estrutura/rodape.php';?>
    <style>
		#chartdiv, #chartdivDias {
		  width: 100%;
		  height: 350px;
		}
	</style>
 
	<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/geodata/germanyLow.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/fonts/notosans-sc.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/percent.js"></script>
	<script src="https://cdn.amcharts.com/lib/5/locales/pt_BR.js"></script>


	<script>
 
	<?php
		setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
		date_default_timezone_set('America/Sao_Paulo');
 	?>

 

		 
		var root = am5.Root.new("chartdiv"); 

		root.setThemes([
		  am5themes_Animated.new(root)
		]);
			root.locale = am5locales_pt_BR;
			root.dateFormatter.set("dateFormat", "dd/MM/yyyy");


		var chart = root.container.children.push( 
		  am5xy.XYChart.new(root, {
		    panY: false,
		    wheelY: "zoomX",
		    layout: root.verticalLayout,
		    maxTooltipDistance: 0
		  }) 
		);

		// Define data
		var data = [
			<?php
				setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
				date_default_timezone_set('America/Sao_Paulo');

				$listaTotalVisualizacao = all($conectDB, ' imovel_visualizacao ', ' COUNT(id) AS total, cadastro  ', " group BY DATE(cadastro)");
				//ECHO $listaUsuariosCadastro;
				foreach($listaTotalVisualizacao as $elemento)
				{
					$data = date("Y, m, d", strtotime ($elemento->cadastro));
		 
					$ano = date("Y", strtotime ($elemento->cadastro));
					$dia = date("d", strtotime ($elemento->cadastro));
					$mes = date("m", strtotime ($elemento->cadastro)) - 1;
					echo 
					'
						{
							date: new Date('.$ano.', '.$mes.', '.$dia.').getTime(),
							value: '.$elemento->total.'
						},
					';
				}
		 	?>
		];

		var yAxis = chart.yAxes.push(
		  am5xy.ValueAxis.new(root, {
		    extraTooltipPrecision: 1,
		    renderer: am5xy.AxisRendererY.new(root, {})
		  })
		);

		// Create X-Axis
		let xAxis = chart.xAxes.push(
		  am5xy.DateAxis.new(root, {
		    baseInterval: { timeUnit: "day", count: 1 },
		    renderer: am5xy.AxisRendererX.new(root, {})
		  })
		);

		xAxis.get("dateFormats")["day"] = "MM/dd";
		xAxis.get("periodChangeDateFormats")["day"] = "MMMM";

		// Create series
		function createSeries(name, field) {
		  var series = chart.series.push( 
		    am5xy.LineSeries.new(root, { 
		      name: name,
		      xAxis: xAxis, 
		      yAxis: yAxis, 
		      valueYField: field, 
		      valueXField: "date",
		      tooltip: am5.Tooltip.new(root, {})
		    }) 
		  );
		  
		  series.bullets.push(function() {
		    return am5.Bullet.new(root, {
		      sprite: am5.Circle.new(root, {
		        radius: 5,
		        fill: series.get("fill")
		      })
		    });
		  });
		  
		  series.strokes.template.set("strokeWidth", 2);
		  
		  series.get("tooltip").label.set("text", "[bold]{name}[/]\n{valueX.formatDate()}: {valueY}")
		  series.data.setAll(data);
		}

		createSeries("Visualizações", "value");

		// Add cursor
		chart.set("cursor", am5xy.XYCursor.new(root, {
		  behavior: "zoomXY",
		  xAxis: xAxis
		}));

		xAxis.set("tooltip", am5.Tooltip.new(root, {
		  themeTags: ["axis"]
		}));

		yAxis.set("tooltip", am5.Tooltip.new(root, {
		  themeTags: ["axis"]
		}));


</script>
</body>

</html>