<?php $__env->startSection('content'); ?>
<div class='container-fluid main-sec bg-white'>
      <div class='row d-flex'>
      <div class="col-md-6 p-0 py-4">
        <div class="business-form-col">
          <h2 class="mt-3" style='font-weight:bold;'>Draw a circle - Create a circle on a google map using a point and a radius
            </h2>  
          <p style='font-size:14px;' class='pb-3'>Search your business on google map and fill the form below.</p>
          <form method='post' action='<?php echo e(route("business-update")); ?>'>
            
           <?php echo csrf_field(); ?>
        
           <input name='client_id' id='client_id' value="<?php echo e(Auth::User()->id); ?>" hidden>
          <div class='row'>
            <div class='col-md-8'>
            <label for='radius' style='font-weight:bold;'>Address</label>
            <?php $__currentLoopData = $radiusaddress; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ra): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input id="search" class="form-control" type="text" name='radius_address' value='<?php echo e($ra); ?>' placeholder="Add Your Business Address"/> 
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>   
            </div>
        <div class='col-md-4'>
            <div class="form-group">
                <label for='radius' style='font-weight:bold;'>Radius</label>
                <?php $__currentLoopData = $radius; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $rad): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <input type="text" class="form-control" id="radius" name='radius' value='<?php echo e($rad); ?>' placeholder="Enter Radius in miles">
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>
        <div class='form-group'>
          
             <input type="text" class="form-control" value='<?php echo e($radius_image); ?>' id="radiusimage" name='radius_image' hidden>
           
             <button type='button' class='btn btn-warning my-3 w-100 primary-btn' onclick="drawCircle()">Draw A Circle</button>
            </div>
        </div>
      <div>
          <?php $__currentLoopData = $name; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bname): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='bname' value="<?php echo e($bname); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $email; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bemail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='bemail' value="<?php echo e($bemail); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $phone; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bphone): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='bphone' value="<?php echo e($bphone); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $address; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $baddress): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='baddress' value="<?php echo e($baddress); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $description; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bdescription): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='description' value="<?php echo e($bdescription); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $website_url; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $website): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='website_url' value="<?php echo e($website); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $timezone; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $time): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='timezone' value="<?php echo e($time); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          <?php $__currentLoopData = $category; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input class='form-control' name='category' value="<?php echo e($cat); ?>" hidden>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      </div>
          
      <div class='self-fields'>
          <p>Are you processing the order yourself or one of our rep on the phone?</p>
          <?php $__currentLoopData = $closerid; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $closer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <input type="radio" id="self" name="closure_id" value="8888" <?php echo e($closer == "8888" ? 'checked' : 'unchecked'); ?> onclick="toggleInputField(false)">
          <label for="self">Self</label><br>
          <input type="radio" id="closure" name="closure_id" value="<?php echo e($closer); ?>" <?php echo e($closer != "8888" ? 'checked' : 'unchecked'); ?> onclick="toggleInputField(true)">
          <label for="closure">Employee</label><br>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      <div class='form-group my-3'>
          <input class='form-control' id='closure_id' style='display:none;' name='emp_closure_id' placeholder='Enter Representative Employee ID' re>
      </div>
          <div class='alert alert-danger alert-dismissible fade show closer-alert' style='display:none;' role='alert'>
                        Employee Not Found
                        </div>
          <div class='alert alert-success alert-dismissible fade show closer-alert-success' style='display:none;' role='alert'>
          <span id='ename'></span> Employee Found
                </div>
                
          <button id='select-package-btn' type='submit' class='btn btn-success w-100 primary-btn'>Select Package</button>
            </form>
        </div>

          </div> 
          </div>
      <div class="col-md-6 p-0 map-col">
         <div id="map"></div>
      </div> 
      
    </div>
</div>


<script>

    $(document).ready(function() {
      $(window).keydown(function(event){
        if(event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });
    });

</script>

<script>
   function toggleInputField(show) {
            var inputField = document.getElementById("closure_id");
            if (show) {
                inputField.style.display = "block";
                // inputField.setAttribute("name", "closure_id");
                $('#select-package-btn').hide();
            } else {
                inputField.style.display = "none";
                inputField.removeAttribute('name');
                $('#select-package-btn').show();
                 $('.closer-alert-success').hide();
                  $('.closer-alert').hide();
            }
        }
</script>

<script type="text/javascript">
    $('#closure_id').on('keyup',function(){
    //   if( this.value.length < 4 ) return;
      $('#select-package-btn').hide();
    $value=$(this).val();
    $.ajax({
    type : 'get',
    url : '<?php echo e(URL::to('check-closer')); ?>',
    data:{'search':$value},
    success:function(response){
      if(response == 'closer not found')
      {
         $('.closer-alert-success').hide();
        $('.closer-alert').show();
        $('#select-package-btn').hide();
      }else{
        // var resp = JSON.stringify(data);
        $("#closure").attr('value',response.closerid);
        $('#ename').text(response.name);
        $('.closer-alert').hide();
        $('.closer-alert-success').show();
        $('#select-package-btn').show();
      }
      
    }
    });
    });

    $('#radius').on('keyup',function(){
      if( this.value < 10 || this.value > 100 ){
        $('#staticBackdrop').modal('show');
      document.getElementById("map-error-text").innerHTML = "please insert radius in between 10 to 100";
        // alert('please insert radius in between 10 to 100');
        $('#radius').val(null);
      }
    });



</script>

<script>

let map;
 let circle;
 let placesService; // Initialize the PlacesService

function initAutocomplete() {
   map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 37.0902, lng: -95.7129 }, // Centered at the United States
    zoom: 2,
    // mapTypeId: "roadmap",
  });
   
  const input = document.getElementById("search");
  const searchBox = new google.maps.places.SearchBox(input);
  placesService = new google.maps.places.PlacesService(map);

  map.controls[google.maps.ControlPosition.TOP_LEFT].push();
 
  map.addListener("bounds_changed", () => {
    searchBox.setBounds(map.getBounds());
  });

  let markers = [];

  searchBox.addListener("places_changed", () => {
    let places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }

     // Check if the selected place is in the United States or Canada
     const selectedPlace = places[0];
    const countryRestrictions = ["US", "CA"]; // United States and Canada

    if (!selectedPlace || !selectedPlace.address_components) {
      alert("Invalid place or address.");
      return;
    }

    const placeCountry = selectedPlace.address_components.find(
      (component) => component.types.includes("country")
    );
    if (placeCountry && countryRestrictions.includes(placeCountry.short_name)) {
    const selectedPlace = places[0];

    

    // Clear out the old markers.
    markers.forEach((marker) => {
      marker.setMap(null);
    });
    markers = [];

    // For each place, get the icon, name and location.
    const bounds = new google.maps.LatLngBounds();

    places.forEach((place) => {
      if (!place.geometry || !place.geometry.location) {
        console.log("Returned place contains no geometry");
        return;
      }

      const icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25),
      };

      const marker = new google.maps.Marker({
    map,
    title: place.name,
    position: place.geometry.location,
  });

  // Add a click event listener to the marker
  marker.addListener('click', () => {
    // Fetch place details to get website and other details
    const placeDetails = new google.maps.places.PlacesService(map);
    placeDetails.getDetails({ placeId: place.place_id }, (placeDetail, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        // Here you can access placeDetail to get details like name, website, opening hours, etc.
        // Update the HTML or display in an InfoWindow as needed
        const infoWindowContent = `
          <strong>${placeDetail.name}</strong>
          <p>${placeDetail.website || 'Not available'}</p>
          <p> ${placeDetail.formatted_address || 'Not available'}</p>
          <p> ${placeDetail.formatted_phone_number || 'Not available'}</p>
        `;
         $('#name').val(placeDetail.name);
          $('#website').val(placeDetail.website);
          $('#address').val(placeDetail.formatted_address);
          $('#phone').val(placeDetail.formatted_phone_number);
        
        const infoWindow = new google.maps.InfoWindow({
          content: infoWindowContent,
        });

        infoWindow.open(map, marker);
        setTimeout(() => {
            infoWindow.close();
        }, 3000);
      } else {
        console.log("Error fetching place details:", status);
      }
    });
  });

  markers.push(marker);


      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }


    });

     // Fetch place details to get website
    const placeDetails = new google.maps.places.PlacesService(map);
    placeDetails.getDetails({ placeId: selectedPlace.place_id }, (place, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        if (place.name) {
          $('#name').val(place.name);
          $('#website').val(place.website);
          $('#address').val(place.formatted_address);
          $('#phone').val(place.formatted_phone_number);
        } else {
          console.log("Website not available for this place.");
        }
      } else {
        console.log("Error fetching place details:", status);
      }
    });


    map.fitBounds(bounds);

  } else {
      document.getElementById('search').value = "";
      alert("Please select a place in the United States or Canada.");
    }
  });
}

// draw circle code

function drawCircle() {

  var radiuss = document.getElementById('radius').value;
  if(radiuss > 10)
  {
    if (circle) {
    circle.setMap(null);
  }

  const radiusInMiles = parseFloat(document.getElementById("radius").value);
  const center = map.getCenter();
  const radiusInMeters = radiusInMiles * 1609.34; // Convert miles to meters

 

  circle = new google.maps.Circle({
    map: map,
    center: center,
    radius: radiusInMeters,
    draggable: true,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
  });

  map.fitBounds(circle.getBounds());
  const numPoints = 100; // Adjust as needed
  const circlePath = [];

  setTimeout(() => {
    

  for (let i = 0; i < numPoints; i++) {
    const theta = (i / numPoints) * 360;
    const point = google.maps.geometry.spherical.computeOffset(center, radiusInMeters, theta);
    circlePath.push(point);
  }

  

  // Encode the circle path using the geometry library
  const encodedCirclePath = google.maps.geometry.encoding.encodePath(circlePath);

  // Create a URL for the map with the drawn circle
  const mapUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${center.lat()},${center.lng()}&zoom=9.5&size=900x800&maptype=roadmap&markers=color:red%7C${center.lat()},${center.lng()}&path=color:red%7Cfillcolor:red%7Cweight:2%7Cenc:${encodedCirclePath}&key=AIzaSyDtMhPtoqeZSt-5Qyh6E4FcO0Q_jqH2oLw&libraries=geometry&callback=initMap`;

  // Set the map URL in the input field
  document.getElementById("radiusimage").value = mapUrl;
  console.log(mapUrl);
  }, 1000);

  // Add a listener to update the circle's position when dragged
  circle.addListener("dragend", function () {
    map.fitBounds(circle.getBounds());

    // Update the map URL when the circle is dragged
    const updatedCirclePath = google.maps.geometry.encoding.encodePath(circlePath);
    const updatedMapUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${circle.getCenter().lat()},${circle.getCenter().lng()}&zoom=9.5&size=900x800&maptype=roadmap&markers=color:red%7C${circle.getCenter().lat()},${circle.getCenter().lng()}&path=color:red%7Cfillcolor:red%7Cweight:2%7Cenc:${updatedCirclePath}&key=AIzaSyDtMhPtoqeZSt-5Qyh6E4FcO0Q_jqH2oLw&libraries=geometry&callback=initMap`;

    // Set the updated map URL in the input field
    document.getElementById("radiusimage").value = updatedMapUrl;
    console.log(updatedMapUrl);
  });
  }
  else{
    alert('Radius will not be less than 10 miles');
  }
  
}

        
    window.initAutocomplete = initAutocomplete;
    </script>


<?php $__env->stopSection(); ?>


<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/tprproject/get-myaio-app/resources/views/editradius.blade.php ENDPATH**/ ?>