   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
 

<!-- Google Maps JavaScript API (Autocomplete & Maps) -->
<script src="https://maps.googleapis.com/maps/api/js?key=<%= GoogleMapsAPIKey%>&libraries=places"></script>
<link rel="stylesheet" href="/css/lib/leaflet.css">
<script src="/js/lib/leaflet.js"></script>


<style>
  #map {
    height: 400px;
    width: 100%;
    margin-top: 20px;
    display: none;
  }

  input,
  select {
    /* width: 100%; */
    padding: 7px 7px !important;
    border: 1px solid #ccc;
    border-radius: 8px;
    font-size: 16px;
  }
</style>
 

  <div class="container pt-20 ">

    <%- include('../../partials/utils/title.ejs', {title: "Edit Redzone"}) %>

    <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
            { label: "View Redzone", href: "/admin/redzones" },
       { label: "Edit Redzone" }
    ];
  %>

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

    <div class="  mt-4">

      <div class="bg-white shadow-md rounded-lg" style="padding: 20px;">
        <form>

          <!-- Area Name -->
          <div class="mb-3">
            <label class="form-label">Area Name</label>
            <input type="text" class="form-control" name="name" value="<%= city.name %>" required placeholder="Enter Area Name">
          </div>

          <!-- Entry Option -->
          <div class="mb-3">
            <label class="form-label">Select Option</label>
            <div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="entryMode" id="manual" value="manual" checked style="margin-top: 2px; margin-right: 5px;">
                <label class="form-check-label" for="manual">Manual Entry</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="entryMode" id="autocomplete" value="autocomplete" style="margin-top: 2px; margin-right: 5px;">
                <label class="form-check-label" for="autocomplete">Autocomplete Location</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="entryMode" id="geofence" value="geofence" <%= city.geofence_json ? 'checked' : '' %> style="margin-top: 2px; margin-right: 5px;">
                <label class="form-check-label" for="geofence">Geofence</label>
              </div>

            </div>
          </div>

          <!-- Autocomplete Address -->
          <div id="autocompleteFields" class="mb-3" style="display: none;">
            <label class="form-label">Enter Address</label>
            <input type="text" id="address" name="address" class="form-control" placeholder="Enter Address">
          </div>

          <!-- Manual Entry -->
          <div id="manualFields">
            <div class="mb-3">
              <label class="form-label">Enter Location Name</label>
              <input type="text" name="location" id="location" value="<%= city.location %>" class="form-control" placeholder="Enter Location Name">
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">Latitude</label>
                <input type="text" name="lat" id="lat" class="form-control" value="<%= city.lat %>" placeholder="Enter Latitude">
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">Longitude</label>
                <input type="text" name="lng" id="lng" class="form-control" value="<%= city.lng %>" placeholder="Enter Longitude">
              </div>
            </div>

            <div class="row">
              <div class="col-md-12 mb-3">
                <label class="form-label">Radius (Km)</label>
                <input type="text"     oninput="this.value = this.value
      .replace(/[^0-9.]/g, '')        // allow numbers + dot
      .replace(/(\..*?)\..*/g, '$1')" 
 name="radius" id="radius" class="form-control" value="<%= city.radius %>" placeholder="Enter Radius">
              </div>

              <div class="col-md-6 mb-3" style="display: none;">
                <label class="form-label">Toll Fee</label>
                <input type="text" oninput="this.value = this.value.replace(/[^0-9]/g, '')" name="toll_fee" id="toll_fee" class="form-control" value="<%= city.toll_fee %>" placeholder="Enter Toll Fee">
              </div>
            </div>
          </div>

          <!-- Geofence Entry -->
          <div id="geofenceFields" class="mb-3" style="display: none;">
            <label class="form-label">Enter Geofence JSON (LatLng Points)</label>
            <textarea name="geofence" id="geofence_json" class="form-control" rows="5" placeholder='{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","coordinates":[[[[58.39,23.60],[58.40,23.60],[58.40,23.61]]]]}]}'><%- city.geofence_json || '' %></textarea>
          </div>

          <!-- View Map Button -->
          <div class="mb-3">
            <button type="button" class="btn btn-primary" onclick="showMap()">View Map</button>
          </div>

          <!-- Map -->
          <div id="map"></div>

          <!-- Status -->
          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="active" class="form-select">
              <option value="1" <%= city.active == 1 ? 'selected' : '' %>>Active</option>
              <option value="0" <%= city.active == 0 ? 'selected' : '' %>>Inactive</option>
            </select>
          </div>


          <!-- Submit -->
          <div class="text-center" style="display: flex; justify-content: end; align-items: center;">
            <button type="button" class="btn btn-success" onclick="submitRedzone()">Update Redzone</button>
          </div>

        </form>
      </div>

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


  <script>
    // Switch Fields Based on Entry Mode
 document.querySelectorAll('input[name="entryMode"]').forEach(radio => {
  radio.addEventListener('change', function() {
    const manualFields = document.getElementById('manualFields');
    const autocompleteFields = document.getElementById('autocompleteFields');
    const geofenceFields = document.getElementById('geofenceFields');
    const location = document.getElementById('location');
    const lat = document.getElementById('lat');
    const lng = document.getElementById('lng');

    if (this.value === 'manual') {
      manualFields.style.display = 'block';
      autocompleteFields.style.display = 'none';
      geofenceFields.style.display = 'none';

      location.readOnly = false;
      lat.readOnly = false;
      lng.readOnly = false;

    } else if (this.value === 'autocomplete') {
      manualFields.style.display = 'block';
      autocompleteFields.style.display = 'block';
      geofenceFields.style.display = 'none';

      location.readOnly = true;
      lat.readOnly = true;
      lng.readOnly = true;

    } else if (this.value === 'geofence') {
      manualFields.style.display = 'none';
      autocompleteFields.style.display = 'none';
      geofenceFields.style.display = 'block';

      location.readOnly = false;
      lat.readOnly = false;
      lng.readOnly = false;
    }
  });
});




    // Google Places Autocomplete
    let autocomplete;

    function initAutocomplete() {
      autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'));
      autocomplete.addListener('place_changed', fillInAddress);
    }

    function fillInAddress() {
      const place = autocomplete.getPlace();
      if (!place.geometry) {
        alert("No location available for input.");
        return;
      }
      document.getElementById('lat').value = place.geometry.location.lat();
      document.getElementById('lng').value = place.geometry.location.lng();
      document.getElementById('location').value = place.name || place.formatted_address || "";
    }

    // Load the autocomplete when page loads

    window.onload = () => {
      // 2. Initialize Google Places Autocomplete
      initAutocomplete();
      const selected = document.querySelector('input[name="entryMode"]:checked').value;
      const manualFields = document.getElementById('manualFields');
      const autocompleteFields = document.getElementById('autocompleteFields');
      const geofenceFields = document.getElementById('geofenceFields');
          const location = document.getElementById('location');
    const lat = document.getElementById('lat');
    const lng = document.getElementById('lng');
      if (selected === 'manual') {
        manualFields.style.display = 'block';
        autocompleteFields.style.display = 'none';
        geofenceFields.style.display = 'none';
            location.readOnly = false;
      lat.readOnly = false;
      lng.readOnly = false;
      } else if (selected === 'autocomplete') {
        manualFields.style.display = 'block';
        autocompleteFields.style.display = 'block';
        geofenceFields.style.display = 'none';
           location.readOnly = true;
      lat.readOnly = true;
      lng.readOnly = true;
      } else if (selected === 'geofence') {
        manualFields.style.display = 'none';
        autocompleteFields.style.display = 'none';
        geofenceFields.style.display = 'block';
            location.readOnly = false;
      lat.readOnly = false;
      lng.readOnly = false;
      }
    };
  </script>
  <script>
    async function submitRedzone() {
      const form = document.querySelector('form');
      const formData = new FormData(form);
      const data = Object.fromEntries(formData.entries());

        // Frontend validation
  if (!data.name || data.name.trim() === '') {
    return Swal.fire('Error', 'Area Name cannot be empty', 'error');
  }

  if (data.entryMode === 'manual') {
    if (!data.location || !data.lat || !data.lng || !data.radius) {
      return Swal.fire('Error', 'Please fill all manual entry fields', 'error');
    }
  }

  if (data.entryMode === 'autocomplete') {
    if (!data.location || !data.lat || !data.lng) {
      return Swal.fire('Error', 'Please select a valid location from autocomplete', 'error');
    }
  }

  if (data.entryMode === 'geofence') {
    if (!data.geofence || data.geofence.trim() === '') {
      return Swal.fire('Error', 'Geofence JSON cannot be empty', 'error');
    }
  }

      // Convert geofence to proper JSON if entryMode is geofence
      if (data.entryMode === 'geofence') {
        try {
          // Parse the JSON string to validate it
          const parsedGeofence = JSON.parse(data.geofence);
          // Keep it as parsed object, don't stringify (backend will handle it)
          data.geofence = parsedGeofence;
        } catch (e) {
          return Swal.fire('Invalid Geofence JSON', 'Please check your geofence input. Error: ' + e.message, 'error');
        }
      }
            document.getElementById("loaderOverlay").style.display = "flex"; // Show loader

      const id = "<%= city.id%>"; // Replace this with your actual redzone ID


      try {
        const response = await fetch(`/admin/update-redzone/${id}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });

        const result = await response.json();

        if (response.ok) {
                      document.getElementById("loaderOverlay").style.display = "none"; // Show loader

          Swal.fire('Success!', result.message || 'Redzone created successfully.', 'success').then(() => {
            window.location.href = '/admin/redzones'; // redirect to listing page
          });
        } else {
          document.getElementById("loaderOverlay").style.display = "none"; // Hide loader
          throw new Error(result.message || 'Something went wrong');
        }

      } catch (err) {
        document.getElementById("loaderOverlay").style.display = "none"; // Hide loader
        Swal.fire('Error!', err.message, 'error');
      }
    }
  </script>
  <script>
    let leafletMap; // make it global

    function showMap() {
      const entryMode = document.querySelector('input[name="entryMode"]:checked').value;
      const mapDiv = document.getElementById('map');
      mapDiv.style.display = 'block';

      // Clear previous content
      mapDiv.innerHTML = '';

      if (entryMode === 'manual' || entryMode === 'autocomplete') {
        const lat = parseFloat(document.getElementById('lat').value);
        const lng = parseFloat(document.getElementById('lng').value);
        const radius = parseFloat(document.getElementById('radius').value) * 1000;

        if (!lat || !lng || !radius) {
Swal.fire({
  icon: 'warning',
  title: 'Invalid Input',
  text: 'Please enter valid Latitude, Longitude, and Radius.',
  confirmButtonColor: '#3085d6',
  confirmButtonText: 'OK'
});
          return;
        }

        const map = new google.maps.Map(mapDiv, {
          center: {
            lat,
            lng
          },
          zoom: 14
        });

        new google.maps.Marker({
          position: {
            lat,
            lng
          },
          map: map
        });
const circle = new google.maps.Circle({
  map: map,
  center: { lat, lng },
  radius: radius,
  fillColor: '#FF6600',
  fillOpacity: 0.3,
  strokeColor: "#FF6600",
  strokeWeight: 2,
});

// ✅ Make sure the circle is fully visible in viewport
const bounds = circle.getBounds();
map.fitBounds(bounds);


      } else if (entryMode === 'geofence') {
        try {
          const raw = document.getElementById('geofence_json').value;
          const geofenceData = JSON.parse(raw);

          // Extract coordinates from GeoJSON
          let coordinates = [];
        if (geofenceData.type === "GeometryCollection") {
          // Handle GeometryCollection with MultiPolygon
          for (const geometry of geofenceData.geometries) {
            if (geometry.type === "MultiPolygon") {
              // MultiPolygon has array of polygons (we'll take first one)
              if (geometry.coordinates && geometry.coordinates[0] && geometry.coordinates[0][0]) {
                coordinates = geometry.coordinates[0][0].map(coord => ({
                  lat: coord[0], // Your format uses [lat, lng] instead of standard GeoJSON [lng, lat]
                  lng: coord[1]
                }));
                break;
              }
            }
          }
        } else if (geofenceData.type === "Polygon") {
          // Handle simple Polygon
          coordinates = geofenceData.coordinates[0].map(coord => ({
            lat: coord[0], // Your format uses [lat, lng]
            lng: coord[1]
          }));
        } else if (Array.isArray(geofenceData)) {
            // Handle direct array format (backward compatibility)
            coordinates = geofenceData;
          }

          if (coordinates.length < 3) {
            alert("Invalid geofence data. Must have at least 3 coordinates. Found: " + coordinates.length);
            console.error("Parsed geofence data:", geofenceData);
            console.error("Extracted coordinates:", coordinates);
            return;
          }

          // Initialize Leaflet Map
          leafletMap = L.map('map').setView([coordinates[0].lat, coordinates[0].lng], 14);

          // Add tile layer
          L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
          }).addTo(leafletMap);

          // Convert coords to Leaflet LatLngs
          const latlngs = coordinates.map(coord => [coord.lat, coord.lng]);

          // Add polygon
          const polygon = L.polygon(latlngs, {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.4
          }).addTo(leafletMap);

          leafletMap.fitBounds(polygon.getBounds());

        } catch (err) {
          console.error("Error parsing geofence:", err);
          alert("Invalid geofence data format. Error: " + err.message);
        }
      }
    }
  </script>

  <%- footer %>