<!-- <script defer src="http://maps.google.com/maps/api/js?key=AIzaSyAGLvq2vssITcoQofAZ5EH00Pg7a4Hzzx8&v=weekly&libraries=marker" type="text/javascript"></script> -->


<?php include "Views/templates/header.php"; ?>

</div>



<!-- /.row -->
<section class="content">

  <div class="container-fluid">
    <div class="card">
      <div class="card-body">
        <div class="row">
          <div class="col-md-12">
            <div id="map" style="min-width: 500px; height: 400px;"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-body">
        <div class="row">
          <div class="col-md-2">
            <label for="">Desde</label>
            <input class="form-control" id="fecha_desde" type="date" name="fecha_desde">
          </div>
          <div class="col-md-2">
            <label for="">Hasta</label>
            <input class="form-control" id="fecha_hasta" type="date" name="fecha_hasta">
          </div>
          <div class="col-md-2">
            <div class="form-group">
              <label for="my-input" style="color: white;">.</label><br>
              <button class="btn btn-outline-primary btn-block" type="button" name="historial_ventas" id="botonmapa" onclick="cargarActividad()">Consultar</button>
            </div>
          </div>
          <div class="col-md-2">
            <div class="form-group">
              <label for="my-input" style="color: white;">.</label><br>
              <button class="btn btn-outline-success btn-block" type="button" id="botonDetalles" onclick="ocultarMostrar()">Ver / Ocultar Detalle</button>
            </div>
          </div>


        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-body">
          <div class="row" id='content_actividad'></div>
      </div>
    </div>
    <!-- /.row -->
  </div><!-- /.container-fluid -->

</section>

<!-- MODAL MAP -->

<div id="modal_map" class="modal faade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
        <div class="modal-content" >
            <div class="modal-header bg-primary">
                <h5 class="modal-title text-white" id="title">Ubicación</h5>
                <button class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

                <div class="modal-body" style='height:75vh;overflow-y:auto;'>
                    <div id="googleMap" style="width:100%;height:80%;"></div>

                    <p class="mt-3">
                        <strong>Datos Cliente:</strong> <span id="coordenadas_cliente"></span><br>
                        <strong>Visita Entrada:</strong> <span id="coordenadas_ultima_visita_entrada"></span><br>
                        <strong>Visita Salida:</strong> <span id="coordenadas_ultima_visita_salida"></span><br>
                        <strong>Observaciones:</strong> <span id="observaciones_visita"></span>
                    </p>
                </div>

                <div class="modal-footer justify-content-between">
                    <div class="text-left"></div>
                    <div class="text-right">
                        <button class="btn btn-outline-danger" type="button" data-dismiss="modal">Cancelar</button>
                    </div>
                </div>

        </div>

    </div>

</div>


<script type="text/javascript">

  let vendedores = {
    <?php
    $locations=[];
    foreach ($data['vendedores'] as $key=>$value) {

      /*if($value['coord_ultimavisita']!=null){
        $coords=explode('|',$value['coord_ultimavisita']);
        //array_push($locations, ["<h4>{$value['nombre']}</h4><strong>Lat</strong>: {$coords[2]}<br/><strong>Lng</strong>: {$coords[1]}", (float)$coords[1], (float)$coords[2], (float)$coords[0]]);
        $locations[$value['id']]='tester';
      }*/

      if($value['coord_ultimavisita']!=null){
        $coords=explode('|',$value['coord_ultimavisita']);
        $locations[$value['id']]=["<h4>{$value['nombre']}</h4><strong>Lat</strong>: {$coords[2]}<br/><strong>Lng</strong>: {$coords[1]}", (float)$coords[1], (float)$coords[2], (float)$coords[0]];
      }      

      echo "'{$value['codven']}': {
        'id': '{$value['id']}',
        'tipo': '{$value['tipo']}',
        'codven': '{$value['codven']}',
        'nombre': '{$value['nombre']}',
        'coord_ultimavisita': '{$value['coord_ultimavisita']}'
      },";
    }

    ?>
  };

</script>

<?php include "Views/templates/footer.php"; ?>



<script>

  var locations = <?=json_encode($locations)?>;


  var i,infowindow, map, markerViewBorder,pinGlyph;    
  var marker=[];
  var pin=[];
  var pinButton=[];

  function changePin(index) {

        for (i = 0; i < pin.length; i++) {
            pinButton=document.getElementById('btn-active-pin'+i);

            if (i === index) {
              if (pinButton.classList.contains('btn-warning')) {
                  pin[index].background= "#f60";
                  pinButton.classList.add('btn-outline-dark');
                  pinButton.classList.remove('btn-warning');
                  marker[index].zIndex=100;
              } else {
                  pin[index].background= "#28a745";
                  pinButton.classList.remove('btn-outline-dark');
                  pinButton.classList.add('btn-warning'); 
                  marker[index].zIndex=1000;
              }
            } else {
                if(pinButton)
                {
                  pin[i].background= "#f60";
                  pinButton.classList.add('btn-outline-dark');
                  pinButton.classList.remove('btn-warning');
                  marker[i].zIndex=100;
                }
            }
        }

        /*for (i = 0; i < pin.length; i++) {

          pinButton[i]=document.getElementById('btn-active-pin'+i);

          if (i === index) {
            
            if (pinButton[index].classList.contains('btn-warning')) {
                pin[index].background= "#f60";
                pinButton[index].classList.add('btn-outline-dark');
                pinButton[index].classList.remove('btn-warning');
                marker[index].zIndex=100;
            } else {
                pin[index].background= "#28a745";
                pinButton[index].classList.remove('btn-outline-dark');
                pinButton[index].classList.add('btn-warning'); 
                marker[index].zIndex=1000;
            }

          } else {
              if(pinButton[i])
              {
                pin[i].background= "#f60";
                pinButton[i].classList.add('btn-outline-dark');
                pinButton[i].classList.remove('btn-warning');
                marker[i].zIndex=100;
              }
          }
        }*/
        //console.log(marker[index])


  }

  async function initMap(selected) {

    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary( "marker", );

    infowindow = new google.maps.InfoWindow();

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 7,
      center: new google.maps.LatLng(15.70814815256062, -90.3196639157081),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapId: "4504f8b37365c3d01",
    });

    for (const prop in locations) {

        pin[prop] = new PinElement({
          borderColor: "#fff",
          background: "#f60",
          glyphColor: "#fff",
        });
        marker[prop] = new AdvancedMarkerElement({
          map,
          position: { lat: locations[prop][1], lng: locations[prop][2] },
          content: pin[prop].element,
        });

        google.maps.event.addListener(marker[prop], 'click', (function(marker, prop) {
          return function() {
            infowindow.setContent(locations[prop][0]);
            infowindow.open(map, marker);
          }
        })(marker[prop], prop));        

    }

/*    for (i = 0; i < locations.length; i++) {
      pin[i] = new PinElement({
          borderColor: "#fff",
          background: "#f60",
          glyphColor: "#fff",
      });

      marker[i] = new AdvancedMarkerElement({
        map,
        position: { lat: locations[i][1], lng: locations[i][2] },
        content: pin[i].element,
      });

      google.maps.event.addListener(marker[i], 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker[i], i));
    }*/
  }

  initMap(false);
  //initMap(1);
  /*

  var infowindow = new google.maps.InfoWindow();

  var marker, i,pin;

  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map,
      icon: {
        url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
      }
    });

    pin = new PinElement({
      scale: 1.5,
    });
    // Create a marker and apply the element.
    marker = new AdvancedMarkerElement({
        map,
        position: { lat: 37.419, lng: -122.02 },
        content: pin.element,
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(locations[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }*/

</script>



  <!-- prettier-ignore -->
<?php
/*
  <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyAGLvq2vssITcoQofAZ5EH00Pg7a4Hzzx8", v: "weekly"});</script>
*/
?>
