<!DOCTYPE html>
<html>
	<head>

		<!-- Page Title -->
		<title>Mi Huella por la Paz - Yucatán - Dashboard</title>
		<!-- Favicon -->
		<link rel="shortcut icon" href="favicon.ico?v3">

		<!-- Page Options -->
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		
		<!-- Page Info -->		
		<meta name="description" content="">
		<meta name="author" content="">

	<!-- Custom fonts for this template-->
	<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

	<!-- Custom styles for this template-->
	<link href="css/sb-admin-2.css" rel="stylesheet">

	<style>

		.sidebar-logo{
			height: 40px;
			margin-bottom: 5px;
		}
	
	</style>
	
		<!-- WordCloud -->		
		<script src="../Clouds/js/wordcloud2.js"></script>
		<script src="../Clouds/js/jquery-3.4.1.min.js"></script>
		<script src="../Clouds/R/Data/Data.js?v<?php echo rand(11111,99999); ?>"></script>	


		<!-- Consultas SQL -->
		<?php

			include '../conexion.php';

			$sql = 'SELECT * FROM respuesta INNER JOIN Inicial ON clave_escuela=CV_CCT';
			$result = $conn->query($sql);
			$Inicial = $result->num_rows;

			$sql = 'SELECT * FROM respuesta INNER JOIN Media ON clave_escuela=CV_CCT';
			$result = $conn->query($sql);
			$Media = $result->num_rows;
			
			$sql = 'SELECT * FROM respuesta INNER JOIN Preescolar ON clave_escuela=CV_CCT';
			$result = $conn->query($sql);
			$Preescolar = $result->num_rows;
			
			$sql = 'SELECT * FROM respuesta INNER JOIN Primaria ON clave_escuela=CV_CCT';
			$result = $conn->query($sql);
			$Primaria = $result->num_rows;
			
			$sql = 'SELECT * FROM respuesta INNER JOIN Secundaria ON clave_escuela=CV_CCT';
			$result = $conn->query($sql);
			$Secundaria = $result->num_rows;

			$sql = 'SELECT * FROM respuesta INNER JOIN Superior ON clave_escuela=CV_CCT WHERE clave_escuela != "99MSU99999"';
			$result = $conn->query($sql);
			$Superior = $result->num_rows;

			$sql = 'SELECT * FROM respuesta INNER JOIN Superior ON clave_escuela=CV_CCT WHERE clave_escuela = "99MSU99999"';
			$result = $conn->query($sql);
			$Otros = $result->num_rows;
			
			$Total = $Otros + $Superior + $Secundaria + $Primaria + $Preescolar + $Media + $Inicial;
			
			echo '<script>var myPCLabels = ["Inicial", "Preescolar", "Primaria", "Secundaria", "Media", "Superior", "Otros"];';
			echo 'var myPCData = ['.$Inicial.', '.$Preescolar.', '.$Primaria.', '.$Secundaria.', '.$Media.', '.$Superior.', '.$Otros.'];</script>';
			
			$Otros = (int)floor(100 * $Otros / $Total);
			$Superior = (int)floor(100 * $Superior / $Total);
			$Secundaria = (int)floor(100 * $Secundaria / $Total);
			$Primaria = (int)floor(100 * $Primaria / $Total);
			$Preescolar = (int)floor(100 * $Preescolar / $Total);
			$Media = (int)floor(100 * $Media / $Total);
			$Inicial = (int)floor(100 * $Inicial / $Total);
			
			$Otros = 100 - ($Superior + $Secundaria + $Primaria + $Preescolar + $Media + $Inicial);
			
			$Espa=0;
			$Maya=0;
            $Total=0;
            $Last="";

			$sql = 'SELECT * FROM respuesta;';
			$result = $conn->query($sql);

			for($A=1; $A<100; $A++)
				$ageArray[$A]=0;
			
			foreach ($result as $respuesta) {
                $Total++;
				if($respuesta["idioma"]=="Español")
					$Espa++;
				else
					$Maya++;
				$ageArray[$respuesta["edad"]]++;
				$last = $respuesta["fecha"];
			}
			
			$Espa = 100 * $Espa / $Total;
			$Maya = 100 * $Maya / $Total;
			

			$now  = new DateTime();
			$old  = DateTime::createFromFormat('Y-m-d H:i:s', $last);
			$lapse = $now->diff($old);
			$mLast="Hace ";
			if($lapse->y>0) if($lapse->y==1) $mLast.=$lapse->y." año, "; else $mLast.=$lapse->y." años, ";
			if($lapse->m>0) if($lapse->m==1) $mLast.=$lapse->m." mes, "; else $mLast.=$lapse->m." meses, ";
			if($lapse->d>0) if($lapse->d==1) $mLast.=$lapse->d." día, "; else $mLast.=$lapse->d." días, ";
			if($lapse->h>0) if($lapse->h==1) $mLast.=$lapse->h." hora, "; else $mLast.=$lapse->h." horas, ";
			if($lapse->i>0) if($lapse->i==1) $mLast.=$lapse->i." minuto, "; else $mLast.=$lapse->i." minutos, ";
			if($lapse->s==1) $mLast.=$lapse->s." segundo."; else $mLast.=$lapse->s." segundos.";


			$sql = "select DATE_FORMAT(fecha, '%d-%m-%Y') as Date, COUNT(*) as Count from respuesta GROUP BY DATE_FORMAT(fecha, '%Y%m%d');";
			$result = $conn->query($sql);
			
			if (!empty($result)){
				$myACLabels = "var myACLabels = [";
				$myACData = "var myACData = [";
				$Counter=0;
				foreach ($result as $respuesta){
					$myACLabels .= '"'.$respuesta["Date"].'"';
					$myACData .= $respuesta["Count"];
					if($Counter++ < $result->num_rows){
						$myACLabels .= ", ";
						$myACData .= ", ";
					}
			
				}
			
				$myACLabels .= "];";
				$myACData .= "];";			

				echo '<script>'.$myACLabels.' '.$myACData.' </script>';
			}
			
		?>
		
</head>

<body id="page-top" onload="CreatCharts();">

	<!-- Page Wrapper -->
	<div id="wrapper">

		<!-- Sidebar -->
		<ul class="navbar-nav bg-gradient-primary-light sidebar sidebar-dark accordion" id="accordionSidebar">

			<!-- Sidebar - Brand -->
			<a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.php">
				<div class="sidebar-brand-icon">
					<img src="img/logos/Mi_Huella_I_SL.png" width="90px" />
				</div>
				<div class="sidebar-brand-text mx-2">
					<img src="img/logos/Mi_Huella_T_SL.png" width="90px" />
				</div>
			</a>

			<!-- Divider -->
			<hr class="sidebar-divider my-0">

			<!-- Heading -->
			<div class="sidebar-heading">
				Main
			</div>
			
			<!-- Nav Item - Dashboard -->
			<li class="nav-item active">
				<a class="nav-link" href="index.php">
					<i class="fas fa-fw fa-tachometer-alt"></i>
					<span>Proyect Overview</span></a>
			</li>

			<!-- Divider -->
			<hr class="sidebar-divider d-none d-md-block">

			<!-- Sidebar Toggler (Sidebar) -->
			<div class="text-center d-none d-md-inline">
				<button class="rounded-circle border-0" id="sidebarToggle"></button>
			</div>
			
	
				<!-- Client Logos -->
			
			<li class="nav-item">
				<a class="nav-link" style="text-align: center;">
					<span>Designed for:</span></a>
			</li>

			<a class="sidebar-brand d-flex align-items-center justify-content-center">
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/Yuc-2018-2024_I_SL.png"  />
				</div>
				<div class="sidebar-brand-text mx-2">
					<img class="sidebar-logo" src="img/logos/Yuc-2018-2024_T_SL.png"  />
				</div>
			</a>
			
			<a class="sidebar-brand d-flex align-items-center justify-content-center">
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/SIIES-2018-2024_T_SL.png"  />
				</div>
			</a>
			
			<a class="sidebar-brand d-flex align-items-center justify-content-center" >
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/SEGEY-2018-2024_T_SL.png"  />
				</div>
			</a>						

			<!-- Institutional Logos -->
			
			<li class="nav-item">
				<a class="nav-link" style="text-align: center;">
					<span>Powered by:</span></a>
			</li>

			<a class="sidebar-brand d-flex align-items-center justify-content-center" target="_blank" href="http://www.geoint.mx">
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/GeoInt_I_SL.png"  />
				</div>
				<div class="sidebar-brand-text mx-2">
					<img class="sidebar-logo" src="img/logos/GeoInt_T_SL.png"  />
				</div>
			</a>

			<a class="sidebar-brand d-flex align-items-center justify-content-center" target="_blank" href="http://www.centrogeo.org.mx">
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/CentroGeo_I_SL.png"  />
				</div>
				<div class="sidebar-brand-text mx-2">
					<img class="sidebar-logo" src="img/logos/CentroGeo_T_SL.png"  />
				</div>
			</a>
			
			<a class="sidebar-brand d-flex align-items-center justify-content-center" target="_blank" href="https://www.conacyt.gob.mx">
				<div class="sidebar-brand-icon">
					<img class="sidebar-logo" src="img/logos/CONACYT_I_SL.png"  />
				</div>
				<div class="sidebar-brand-text mx-2">
					<img class="sidebar-logo" src="img/logos/CONACYT_T_SL.png"  />
				</div>
			</a>


		</ul>
		<!-- End of Sidebar -->

		<!-- Content Wrapper -->
		<div id="content-wrapper" class="d-flex flex-column">

			<!-- Main Content -->
			<div id="content">

				<!-- Topbar -->
				<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

					<!-- Sidebar Toggle (Topbar) -->
					<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
						<i class="fa fa-bars"></i>
					</button>

					<h1 class="h3 mb-0 text-gray-800">Dashboard of: <a target="_blanl" href="http://www.huellaporlapaz.mx"<b>Huellaporlapaz.mx</b></a></h1>
					
					<!-- Topbar Search -->
					<!--form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
						<div class="input-group">
							<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
							<div class="input-group-append">
								<button class="btn btn-primary" type="button">
									<i class="fas fa-search fa-sm"></i>
								</button>
							</div>
						</div>
					</form--!>

					<!-- Topbar Navbar -->
					<ul class="navbar-nav ml-auto">

						<!-- Nav Item - Search Dropdown (Visible Only XS) -->
						<!--li class="nav-item dropdown no-arrow d-sm-none">
							<a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
								<i class="fas fa-search fa-fw"></i>
							</a>
							<!-- Dropdown - Messages -->
							<div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown">
								<form class="form-inline mr-auto w-100 navbar-search">
									<div class="input-group">
										<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
										<div class="input-group-append">
											<button class="btn btn-primary" type="button">
												<i class="fas fa-search fa-sm"></i>
											</button>
										</div>
									</div>
								</form>
							</div>
						</li-->

						<div class="topbar-divider d-none d-sm-block"></div>

						<!-- Nav Item - User Information -->
						<li class="nav-item dropdown no-arrow">
							<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
								<span class="mr-2 d-none d-lg-inline text-gray-600 small">Admin</span>
								<img class="img-profile rounded-circle" src="https://www.freeclipartnow.com/d/9911-6/AndyToolsHammerSpanner.jpg">
							</a>
							<!-- Dropdown - User Information -->
							<div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
								<a class="dropdown-item" href="#">
									<i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
									Profile
								</a>
								<a class="dropdown-item" href="#">
									<i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
									Settings
								</a>
								<a class="dropdown-item" href="#">
									<i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>
									Activity Log
								</a>
								<div class="dropdown-divider"></div>
								<a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
									<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
									Logout
								</a>
							</div>
						</li>

					</ul>

				</nav>
				<!-- End of Topbar -->

				<!-- Begin Page Content -->
				<div class="container-fluid" id="mContainer">

					<!-- Page Heading -->
					<div class="d-sm-flex align-items-center justify-content-between mb-4">
						<h1 class="h3 mb-0 text-gray-800"><i class="fas fa-fw fa-tachometer-alt"></i> Proyect Overview</h1>
						<a target="_blanl" href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm" onclick="location.reload();">
							<i class="fas fa-sync-alt fa-sm text-white-50"></i> 
							Update Stats
						</a>
					</div>

					<!-- Content Row -->
					<div class="row">

						<!-- Total respuestas -->
						<div class="col-xl-3 col-md-6 mb-4">
							<div class="card border-left-primary shadow h-100 py-2">
								<div class="card-body">
									<div class="row no-gutters align-items-center">
										<div class="col mr-2">
											<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total respuestas</div>
											<div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $Total; ?></div>
										</div>
										<div class="col-auto">
											<i class="fas fa-file-signature fa-2x text-gray-300"></i>
										</div>
									</div>
								</div>
							</div>
						</div>

						<!-- Sexo -->
						<div class="col-xl-3 col-md-6 mb-4">
							<div class="card border-left-info shadow h-100 py-2">
								<div class="card-body">
									<div class="row no-gutters align-items-center">
										<div class="col mr-2">
											<div class="text-xs font-weight-bold text-info text-uppercase mb-1">Sexo (Guess)</div>
											<div class="row no-gutters align-items-center">
												<div class="col-auto">
													<div class="mb-0 mr-1 font-weight-bold text-gray-800"><script>document.write((100*sexMA/(sexMA+sexFE)).toFixed(1));</script>%</div>
												</div>
												<div class="col">
													<div class="progress progress-sm mr-1">
														<div id="pbMA" class="progress-bar bg-info" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
													</div>													
												</div>
												<i class="fas fa-male fa-2x mr-2"></i>
												<div class="col-auto">
													<div class="mb-0 mr-1 font-weight-bold text-gray-800"><script>document.write((100*sexFE/(sexMA+sexFE)).toFixed(1));</script>%</div>
												</div>
												<div class="col">
													<div class="progress progress-sm mr-1">
														<div id="pbFE"class="progress-bar bg-info" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
													</div>
												</div>
												<i class="fas fa-female fa-2x mr-1"></i>
												<script>
													document.getElementById("pbMA").style.width = (100*sexMA/(sexMA+sexFE)).toFixed(0)+"%";
													document.getElementById("pbFE").style.width = (100*sexFE/(sexMA+sexFE)).toFixed(0)+"%";
												</script>
												
											</div>
										</div>

									</div>
								</div>
							</div>
						</div>
						
						<!-- Idioma -->
						<div class="col-xl-3 col-md-6 mb-4">
							<div class="card border-left-success shadow h-100 py-2">
								<div class="card-body">
									<div class="row no-gutters align-items-center">
										<div class="col mr-2">
											<div class="text-xs font-weight-bold text-success text-uppercase mb-1">Idioma</div>
											<div class="row no-gutters align-items-center">
												<div class="text-xs" style="width:30px;">Esp.</div>
												<div class="col">
													<div class="ml-1 progress progress-sm mr-1">
														<div id="pbEs" class="progress-bar bg-info" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
													</div>													
												</div>
												<div class="col-auto">													
													<div class="mb-0 mr-1 font-weight-bold text-gray-800"><?php printf("%05.2f", $Espa); ?>%</div>
												</div>												
												<div class="text-xs" style="width:30px;">Maya</div>																								
												<div class="col">
													<div class="ml-1 progress progress-sm mr-1">
														<div id="pbMa"class="progress-bar bg-info" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
													</div>
												</div>
												<div class="col-auto">
													<div class="mb-0 mr-1 font-weight-bold text-gray-800"><?php printf("%05.2f", $Maya); ?>%</div>
												</div>												
												<script>
													document.getElementById("pbEs").style.width = <?php echo "\"".number_format($Espa,0)."%\""; ?>;
													document.getElementById("pbMa").style.width = <?php echo "\"".number_format($Maya,0)."%\""; ?>;
												</script>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>						

						<!-- Última respuesta -->
						<div class="col-xl-3 col-md-6 mb-4">
							<div class="card border-left-warning shadow h-100 py-2">
								<div class="card-body">
									<div class="row no-gutters align-items-center">
										<div class="col mr-2">
											<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Última respuesta</div>
											<div class="mb-0 font-weight-bold text-gray-800"><?php echo $last; ?></div>
											<div class="mb-0 font-weight-bold text-xs text-gray-500"><?php echo $mLast; ?></div>
										</div>
										<div class="col-auto">
											<i class="fas fa-clock fa-2x text-gray-300"></i>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- Content Row -->

					<div class="row">

						<!-- Histograma por día -->
						<div class="col-xl-8 col-lg-7">
							<div class="card shadow mb-4">
								<!-- Card Header - Dropdown -->
								<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
									<h6 class="m-0 font-weight-bold text-primary">Participaciones por Día</h6>
								</div>
								<!-- Card Body -->
								<div class="card-body">
									<div class="chart-area">
										<canvas id="myAreaChart"></canvas>
									</div>
								</div>
							</div>
						</div>

						<!-- por Nivel de Estudios -->
						<div class="col-xl-4 col-lg-5">
							<div class="card shadow mb-4">
								<!-- Card Header - Dropdown -->
								<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
									<h6 class="m-0 font-weight-bold text-primary">Participación por Nivel de Estudios</h6>									
								</div>
								<!-- Card Body -->
								<div class="card-body">
									<div class="chart-area" id="myPieChart">
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- Content Row -->
					<div class="row">

						<!-- Content Column -->
						<div class="col-xl-8 col-lg-7">
							<div class="card shadow mb-4">
								<div class="card-header py-3">
									<h6 class="m-0 font-weight-bold text-primary">Participación por Municipio / Institución</h6>
								</div>
								<div class="card-body">
									<div class="chart-area" id="myPlaceChart">
									</div>
								</div>
							</div>
						</div>


						<!-- Por edad -->
						<div class="col-xl-4 col-lg-5">
							<div class="card shadow mb-4">
								<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
									<h6 class="m-0 font-weight-bold text-primary">Participación por Edad</h6>									
								</div>
								<!-- Card Body -->
								<div class="card-body">
									<div class="chart-area" id="myAgeChart">
									</div>
								</div>
							</div>
						</div>
					</div>

				</div>
				<!-- /.container-fluid -->

			</div>
			<!-- End of Main Content -->
			
			
			
			

			<!-- Footer -->
			<footer class="sticky-footer bg-white">
				<div class="container my-auto">
					<div class="copyright text-center my-auto">
						<span>Copyright &copy; GeoInt - CentroGeo 2019</span>
					</div>
				</div>
			</footer>
			<!-- End of Footer -->

		</div>
		<!-- End of Content Wrapper -->

	</div>
	<!-- End of Page Wrapper -->

	<!-- Scroll to Top Button-->
	<a class="scroll-to-top rounded" href="#page-top">
		<i class="fas fa-angle-up"></i>
	</a>

	<!-- Logout Modal-->
	<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
					<button class="close" type="button" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">×</span>
					</button>
				</div>
				<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
				<div class="modal-footer">
					<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
					<a class="btn btn-primary" href="login.html">Logout</a>
				</div>
			</div>
		</div>
	</div>

	<!-- Bootstrap core JavaScript-->
	<script src="vendor/jquery/jquery.min.js"></script>
	<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

	<!-- Core plugin JavaScript-->
	<script src="vendor/jquery-easing/jquery.easing.min.js"></script>

	<!-- Custom scripts for all pages-->
	<script src="js/sb-admin-2.min.js"></script>

	<!-- Page level plugins -->
	<script src="vendor/chart.js/Chart.min.js"></script>

	<!-- Page level custom scripts -->
	<script src="js/demo/chart-area-demo.js"></script>
	<!--script src="js/demo/chart-pie-demo.js"></script-->
	
	<!-- AMCharts -->
	<script src="https://www.amcharts.com/lib/4/core.js"></script>
	<script src="https://www.amcharts.com/lib/4/charts.js"></script>
	<script src="https://www.amcharts.com/lib/4/themes/dataviz.js"></script>
	<script src="https://www.amcharts.com/lib/4/themes/material.js"></script>
	<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>		
	
<script>

		function CreatCharts(){
			CreateLvlChart();
			CreateAgeChart();
			CreatePlaceChart();
		}
		
			function CreatePlaceChart() {
			
				am4core.useTheme(am4themes_animated);

				data = {
				
				<?php
				
					$sql = 'SELECT * from (SELECT e.NOMBRECT as Escuela, e.CV_CCT as Clave, e.MUNICIPIO as Municipio, COUNT(e.CV_CCT) as Cuenta FROM respuesta, Superior e WHERE respuesta.clave_escuela = e.CV_CCT  GROUP BY e.CV_CCT UNION SELECT e.NOMBRECT, e.CV_CCT, e.MUNICIPIO, COUNT(e.CV_CCT)  AS count FROM respuesta, Media e WHERE respuesta.clave_escuela = e.CV_CCT  GROUP BY e.CV_CCT UNION SELECT e.NOMBRECT, e.CV_CCT, e.C_NOM_MUN, COUNT(e.CV_CCT)  AS count FROM respuesta, Inicial e WHERE respuesta.clave_escuela = e.CV_CCT GROUP BY e.CV_CCT UNION SELECT e.NOMBRECT, e.CV_CCT, e.C_NOM_MUN, COUNT(e.CV_CCT)  AS count FROM respuesta, Preescolar e WHERE respuesta.clave_escuela = e.CV_CCT GROUP BY e.CV_CCT UNION SELECT e.NOMBRECT, e.CV_CCT, e.C_NOM_MUN, COUNT(e.CV_CCT)  AS count FROM respuesta, Primaria e WHERE respuesta.clave_escuela = e.CV_CCT GROUP BY e.CV_CCT UNION SELECT e.NOMBRECT, e.CV_CCT, e.C_NOM_MUN, COUNT(e.CV_CCT)  AS count FROM respuesta, Secundaria e WHERE respuesta.clave_escuela = e.CV_CCT GROUP BY e.CV_CCT) a order by Municipio';
					$result = $conn->query($sql);

					if (!empty($result)) {
						$Counter = 0;
						$lMun = "";
						foreach ($result as $respuesta){
						
							if($lMun != $respuesta["Municipio"]){
								if($lMun != "") echo '},';
								echo '"'.$respuesta["Municipio"].'": { "'.$respuesta["Escuela"].'": '.$respuesta["Cuenta"];
							}else{
								echo ', "'.$respuesta["Escuela"].'": '.$respuesta["Cuenta"];							
							}
							
							$lMun = $respuesta["Municipio"];

						}
						
						echo '}';
					}

				?>
				};


				function processData(data) {

					  var treeData = [];

					  for (var muni in data) {
						var muniData = { name: muni, children: [] };
						var muniTotal = 0;
						for (var school in data[muni]) {
						  muniTotal += data[muni][school];
						}

						for (var school in data[muni]) {
							muniData.children.push({ name: school, count: data[muni][school] });
						}
						treeData.push(muniData);
					  }
					  
					  return treeData;
				}

					// create chart
					var chart = am4core.create("myPlaceChart", am4charts.TreeMap);
					chart.hiddenState.properties.opacity = 0; // this makes initial fade in effect

					// only one level visible initially
					chart.maxLevels = 1;
					// define data fields
					chart.dataFields.value = "count";
					chart.dataFields.name = "name";
					chart.dataFields.children = "children";
					chart.homeText = "Municipio";

					// enable navigation
					chart.navigationBar = new am4charts.NavigationBar();

					// level 0 series template
					var level0SeriesTemplate = chart.seriesTemplates.create("0");
					level0SeriesTemplate.tooltip.dy = - 15;
					level0SeriesTemplate.tooltip.pointerOrientation = "vertical";
					level0SeriesTemplate.tooltip.fontSize = 10;



					// create hover state
					var columnTemplate = level0SeriesTemplate.columns.template;
					var hoverState = columnTemplate.states.create("hover");

					// darken
					hoverState.adapter.add("fill", function (fill, target) {
					  if (fill instanceof am4core.Color) {
						return am4core.color(am4core.colors.brighten(fill.rgb, -0.2));
					  }
					  return fill;
					})


					var bullet0 = level0SeriesTemplate.bullets.push(new am4charts.LabelBullet());
					bullet0.locationX = 0.5;
					bullet0.locationY = 0.5;
					bullet0.label.text = "{name} ({value})";
					bullet0.label.fill = am4core.color("#ffffff");
					bullet0.label.fontSize = 10;
					
					// level1 series template
					var level1SeriesTemplate = chart.seriesTemplates.create("1");
					level1SeriesTemplate.tooltip.dy = - 15;
					level1SeriesTemplate.tooltip.pointerOrientation = "vertical";
					level1SeriesTemplate.tooltip.fontSize = 12;					

					var bullet1 = level1SeriesTemplate.bullets.push(new am4charts.LabelBullet());
					bullet1.locationX = 0.5;
					bullet1.locationY = 0.5;
					bullet1.label.text = "{name} ({value})";
					bullet1.label.fill = am4core.color("#ffffff");
					bullet1.label.fontSize = 10;

					chart.data = processData(data);
					
			}

		
		
			function CreateAgeChart() {
			
				am4core.useTheme(am4themes_material);			
				am4core.useTheme(am4themes_animated);

				var chart = am4core.create("myAgeChart", am4charts.RadarChart);
				chart.hiddenState.properties.opacity = 0; // this makes initial fade in effect

				chart.data = [
				
				<?php
					$start=false;
					for($A=1; $A<=99; $A++){
						if($ageArray[$A+1]) $start=true;
						if($start){
							echo '{"age": "'.$A.'", "value":'.$ageArray[$A].'}';
							if($A<99) echo ',';
							$rest=0;
							for($B=$A; $B<=99; $B++){
							 if($ageArray[$B]>0) $rest++;
							}
							if($rest==0) break;
						}
					}
				?>
				];

				chart.radius = am4core.percent(100);
				chart.innerRadius = am4core.percent(50);
				chart.startAngle = 180;
				chart.endAngle = 360; 	
				
				var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
				valueAxis.renderer.grid.template.strokeOpacity = 0.1;
				valueAxis.renderer.labels.template.disabled = true;
				valueAxis.strictMinMax = true;

				// Create axes
				var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
				categoryAxis.dataFields.category = "age";
				categoryAxis.renderer.grid.template.location = 0;
				categoryAxis.renderer.minGridDistance = 60;
				categoryAxis.tooltip.disabled = true;
				categoryAxis.renderer.minHeight = 110;
				categoryAxis.renderer.grid.template.disabled = true;
				//categoryAxis.renderer.labels.template.disabled = true;
				let labelTemplate = categoryAxis.renderer.labels.template;
				labelTemplate.radius = am4core.percent(-60);
				labelTemplate.location = 0.5;
				labelTemplate.relativeRotation = 90;
				labelTemplate.fontSize = 10;

				var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
				valueAxis.renderer.grid.template.disabled = true;
				valueAxis.renderer.labels.template.disabled = true;
				valueAxis.tooltip.disabled = true;

				// Create series
				var series = chart.series.push(new am4charts.RadarColumnSeries());
				series.sequencedInterpolation = true;
				series.dataFields.valueY = "value";
				series.dataFields.categoryX = "age";
				series.columns.template.strokeWidth = 0;
				series.tooltipText = "{age} años: [bold]{valueY}[/]";;
				series.columns.template.radarColumn.cornerRadius = 10;
				series.columns.template.radarColumn.innerCornerRadius = 0;

				series.tooltip.pointerOrientation = "vertical";

				// on hover, make corner radiuses bigger
				let hoverState = series.columns.template.radarColumn.states.create("hover");
				hoverState.properties.cornerRadius = 0;
				hoverState.properties.fillOpacity = 1;


				series.columns.template.adapter.add("fill", function(fill, target) {
				  return chart.colors.getIndex(target.dataItem.index);
				})

				// Cursor
				chart.cursor = new am4charts.RadarCursor();
				chart.cursor.innerRadius = am4core.percent(50);
				chart.cursor.lineY.disabled = true;
				chart.cursor.behavior = "none";


			}

		

		function CreateLvlChart(){

				am4core.useTheme(am4themes_animated);
				am4core.useTheme(am4themes_dataviz);

				var chart = am4core.create("myPieChart", am4charts.RadarChart);
				chart.hiddenState.properties.opacity = 0; // this makes initial fade in effect

/*
				chart.data = [{
					"name": "Otros",
					"value": <?php echo $Otros; ?>,
					"full": 100
				}, {
					"name": "Superior",
					"value": <?php echo $Superior; ?>,
					"full": 100
				}, {
					"name": "Media",
					"value": <?php echo $Media; ?>,
					"full": 100
				}, {
					"name": "Secundaria",
					"value": <?php echo $Secundaria; ?>,
					"full": 100
				}, {
					"name": "Primaria",
					"value": <?php echo $Primaria; ?>,
					"full": 100
				}, {
					"name": "Preescolar",
					"value": <?php echo $Preescolar; ?>,
					"full": 100
				}, {
					"name": "Inicial",
					"value": <?php echo $Inicial; ?>,
					"full": 100
				}];
*/
			
				chart.data = [{
					"name": "Otros",
					"value": 100,
					"full": 100
				}, {
					"name": "Superior",
					"value": 100,
					"full": 100
				}, {
					"name": "Media",
					"value": 100,
					"full": 100
				}, {
					"name": "Secundaria",
					"value": 100,
					"full": 100
				}, {
					"name": "Primaria",
					"value": 100,
					"full": 100
				}, {
					"name": "Preescolar",
					"value": 100,
					"full": 100
				}, {
					"name": "Inicial",
					"value": 100,
					"full": 100
				}];

				// Make chart not full circle
				chart.startAngle = -90;
				chart.endAngle = 180;
				chart.innerRadius = am4core.percent(20);

				// Set number format
				chart.numberFormatter.numberFormat = "#.#'%'";

				// Create axes
				var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
				categoryAxis.dataFields.category = "name";
				categoryAxis.renderer.grid.template.location = 0;
				categoryAxis.renderer.grid.template.strokeOpacity = 0;
				categoryAxis.renderer.labels.template.horizontalCenter = "right";
				categoryAxis.renderer.labels.template.fontWeight = 500;
				categoryAxis.renderer.labels.template.adapter.add("fill", function(fill, target) {
				  return (target.dataItem.index >= 0) ? chart.colors.getIndex(target.dataItem.index) : fill;
				});
				categoryAxis.renderer.minGridDistance = 10;

				var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());
				valueAxis.renderer.grid.template.strokeOpacity = 0;
				valueAxis.min = 0;
				valueAxis.max = 100;
				valueAxis.strictMinMax = true;

				// Create series
				var series1 = chart.series.push(new am4charts.RadarColumnSeries());
				series1.dataFields.valueX = "full";
				series1.dataFields.categoryY = "name";
				series1.clustered = false;
				series1.columns.template.fill = new am4core.InterfaceColorSet().getFor("alternativeBackground");
				series1.columns.template.fillOpacity = 0.08;
				series1.columns.template.cornerRadiusTopLeft = 20;
				series1.columns.template.strokeWidth = 0;
				series1.columns.template.radarColumn.cornerRadius = 20;
				series1.defaultState.transitionDuration = 250;

				var series2 = chart.series.push(new am4charts.RadarColumnSeries());
				series2.dataFields.valueX = "value";
				series2.dataFields.categoryY = "name";
				series2.clustered = false;
				series2.columns.template.strokeWidth = 0;
				series2.columns.template.tooltipText = "{name}: [bold]{value}[/]";
				series2.columns.template.radarColumn.cornerRadius = 20;
				series2.defaultState.transitionDuration = 500;

				series2.columns.template.adapter.add("fill", function(fill, target) {
				  return chart.colors.getIndex(target.dataItem.index);
				});

				// Add cursor
				chart.cursor = new am4charts.RadarCursor();
				chart.cursor.behavior = "none";
				
				setTimeout(function(){updateChart(chart)}, 600);

		}
		
		
		function updateChart(Chart){
		
					Chart.data[0].value=<?php echo $Otros; ?>;
					Chart.data[1].value=<?php echo $Superior; ?>;
					Chart.data[2].value=<?php echo $Media; ?>;
					Chart.data[3].value=<?php echo $Secundaria; ?>;
					Chart.data[4].value=<?php echo $Primaria; ?>;
					Chart.data[5].value=<?php echo $Preescolar; ?>;
					Chart.data[6].value=<?php echo $Inicial; ?>;
					Chart.invalidateRawData();
		}


</script>	

</body>

</html>
