<?php

// include 'map.php';
include_once 'header.php';

/*********************/
/********** Map ***********/
/*********************/

$sqlhome = "SELECT * FROM users WHERE total_survey_number > 0";

$homelatlonquery = mysqli_query($mysqli,$sqlhome);

$geojson = array( 'type' => 'FeatureCollection', 'features' => array());

while($row = mysqli_fetch_assoc($homelatlonquery)){

  $marker = array(
    'type' => 'Feature',
    'properties' => array(
      'title' => $row['username'],
      'color' => $row['color'],
      'marker-size' => 'small'
    ),
    'geometry' => array(
      'type' => 'Point',
      'coordinates' => array(
        $row['homelon'],
        $row['homelat']
      )
    )
  );
  array_push($geojson['features'], $marker);
}
// echo "<pre>";
// print_r($geojson);
// exit;

/*********************/
/********** Map Over ***********/
/*********************/

/*********************/
/********** STRESS LEVELS BY STATE ***********/
/*********************/
$username = $_SESSION["username"];

$Q = 1;
$arstatessearched = [];
$statesearched = false; 
$arallstatescores = [];

$sqlsurveyState = "SELECT state FROM users WHERE total_survey_number > 0 GROUP BY state";
$Statequery = mysqli_query($mysqli,$sqlsurveyState);
$statesarr  = array();
while($row = mysqli_fetch_assoc($Statequery)){

  $cscfilter  = array('mysqli'=>$mysqli,'state'=>$row['state']);
  $stateavg   = getAvgCountryStateCity($cscfilter);
  if($stateavg['state_avg'] > 0){
    $filter     = array('mysqli'=>$mysqli,'state'=>$row['state']);
    $name       = getCountryStateCity($filter);
    $statesarr[]=[
      'id'    => $row['state'],
      'name'  => $name['state_name'],
      'avg'   => $stateavg['state_avg']
    ];
  }
}
?>
<section>
<div class="container-fluid">
  <div class="row">
        <div class="col-md-3">
            <div class="st-average-box">
                <div class="st-average-title">
                    <h3>AVERAGE STRESS LEVELS BY STATE</h3>
                </div>
                <?php  
                        echo '<div class="st-county" id="style-2"><ul>';
                        if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == true) 
                        {
                          if(!empty($statesarr)){
                            usort($statesarr, function($b, $a) {
                                  return $a['avg'] <=> $b['avg'];
                              });
                            $Q = 1;
                            foreach ($statesarr as $key => $v) {
                              // $avg = (float)number_format((float)$v['avg'], 2 , '.', '');
                                $avg = floatValueScore($v['avg']);
                                echo "<li><a href='javascript:void(0)' onclick = 'return getCity(".$v['id'].")' style='color:black;'> <span class ='st-county-name'>".$Q.". <span>".$v['name']." </span> </span> <span>".$avg."</span>  </a></li>";
                                $Q++;
                              
                            }
                          }                          
                        }
                        else{
                          if(!empty($statesarr)){
                            usort($statesarr, function($b, $a) {
                                  return $a['avg'] <=> $b['avg'];
                              });
                            $Q = 1;
                            foreach ($statesarr as $key => $v) {
                              // $avg = (float)number_format((float)$v['avg'], 2 , '.', '');
                              $avg = floatValueScore($v['avg']);
                            echo '<li><a href="#"> <span >'.$Q.'. <span > '.$v['name'].'</span> </span>     <span>'.$avg.'</span>  </a></li>';
                              $Q++;
                              if( $Q == 6 )break;
                            }
                          } 
                      }
                      echo '</ul></div>';
                if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == false) 
                {
                ?>
                  
                <div class="st-average-footer text-center">
                    <p> LOGIN TO SEE MORE >> </p>
                </div>
              <?php } else{
                ?>
                <div class="st-average-footer text-center">
                    <p> CLICK ON A STATE TO VIEW CITY RANKINGS</p>
                </div>
                <?php
              } ?>
            </div>
        </div>
        <div class="col-md-6">
            <div class="st-map">
                <div id="map"></div>
            </div>
        </div>
        <div class="col-md-3">
            <?php

            if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == true){

              include 'home_graph.php';
            }else{
              include 'home_login.php';
            }
            ?>
        </div>
    </div>
</div>
</section>
<div id="cityResult"></div>
<!-- </section> -->

<?php
include_once 'footer.php';
?>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
<script type="text/javascript">
  
function getMapData( country='', state = '', city = '',arrgeojson = '') {

    if( country != ''){
      var name = country;
      var datazoom = 2;
    }

    if(state != '' && city == ''){
      var name = state+' '+country;
      var datazoom = 6;
    }

    if(country != '' && state != '' && city != ''){
      var name = city+' '+state+ ' '+country;
      var datazoom = 9;
    }

    var settings = {
        "async": false,
        "crossDomain": true,
        "url": "https://us1.locationiq.com/v1/search.php?key=pk.a3a9d5650529b95fdc1eda8e4625b40e&q="+name+"&format=json",
        "method": "GET"
      }
      var address;
      $.ajax(settings).done(function (response) {
        address = response[0]['display_name'];
      });
      

  mapboxgl.accessToken = 'pk.eyJ1Ijoiam9lMjEyMiIsImEiOiJja2liMjF3bHYwNHQ1MzBxeHN2ZDU2OXplIn0.7j_3UwBXCtE3NpGAKqLqWQ';

  var mapboxClient = mapboxSdk({ accessToken: mapboxgl.accessToken });
    mapboxClient.geocoding.forwardGeocode({
      query: address,
      autocomplete: false,
      limit: 1
    })
    .send()
    .then(function (response) {
      if (
      response &&
      response.body &&
      response.body.features &&
      response.body.features.length
      ) {

        var feature = response.body.features[0];
        if(arrgeojson == ''){
          var geoJson = <?php echo json_encode($geojson,JSON_NUMERIC_CHECK); ?>;
        }else{
          
          var geoJson = arrgeojson;
        }
        var map = new mapboxgl.Map({
        container: 'map',
        //style: 'mapbox://styles/fariskassim/cjmszx78b266o2rlar02ytynj',
        style: 'mapbox://styles/mapbox/dark-v10',
        center: feature.center,
        zoom: datazoom,
        attributionControl: false
      });


      map.on('load', function () {
        map.addSource('mainpoints', {
          'type': 'geojson',
          'data': geoJson

        });

        map.addLayer({
          'id': 'park-volcanoes',
          'type': 'circle',
          'source': 'mainpoints',
          'paint': {
            'circle-radius': ['interpolate',
            ['linear'],
            ['zoom'],
            1, 2,
            5, 3,
            10, 8
            ],
            'circle-color': {      type: 'identity',
            property: 'color'},
          },
          'filter': ['==', '$type', 'Point']
        });
      });
        // var map = new mapboxgl.Map({
        //   container: 'map',
        //   style: 'mapbox://styles/mapbox/streets-v11',
        //   center: feature.center,
        //   zoom: 10
        // });
        //new mapboxgl.Marker().setLngLat(feature.center).addTo(map);
      }
    });
}

  function getCity(id) {
    $.ajax({
        url:"ajaxQry.php",    //the page containing php script
        type: "post",    //request type,
        dataType : 'html',
        data: {action: "get_city_data", id: id},
        success:function(result){
          var result = jQuery.parseJSON(result);
          $('#cityResult').html(result.html);
          let city = '';
          getMapData(result.country, result.state, city ,result.geojson);
          $('html, body').animate({
              scrollTop: $("#cityResult").offset().top
          }, 1000);
        }
    });
  }
  $(document).ready(function() {
    getMapData('United States',state = '', city = '',arrgeojson = '')
    $(document).on('keyup','#searchcity',function() {
      var name      = this.value;
   
      var state  = $('#srcstatename').val();
   
        $.ajax({
          url:"ajaxQry.php",    //the page containing php script
          type: "post",    //request type,
          dataType : 'html',
          data: {action: "search_city", name: name, state:state},
          success:function(result){

            $('ul#src-tbl-city').html(jQuery.parseJSON(result));
            // let state = '';
            // getMapData(state, city ,result.geojson);
          }
        });
     
    });
    $(document).on('click', '#srccity', function() {
      var city = $(this).attr('searchcity');
      var state = $(this).attr('searchstate'); 
      $.ajax({
            url:"ajaxQry.php",    //the page containing php script
            type: "post",    //request type,
            dataType : 'html',
            data: {action: "click_city_servay", name: city,state:state},
            success:function(result){

              // $('ul#src-tbl-city').html(jQuery.parseJSON(result));
              // let state = '';
              var result = jQuery.parseJSON(result);
              getMapData(result.country, result.state, result.city ,result.geojson);
            }
          });
    });
  });
 

</script>