@php
$configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Editar zona')

@section('content')
<div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
  <h4 class="mb-0">Editar zona</h4>
  <a class="btn btn-outline-secondary" href="{{ route('admin.zones.index') }}">Volver</a>
</div>

@if ($errors->any())
  <div class="alert alert-danger">
    <ul class="mb-0">
      @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif

<div class="card">
  <div class="card-body">
    <form method="POST" action="{{ route('admin.zones.update', $zone) }}">
      @csrf
      @method('PUT')
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Nombre</label>
          <input class="form-control" name="name" value="{{ old('name', $zone->name) }}" required />
        </div>
        <div class="col-md-6">
          <label class="form-label">Ciudad</label>
          <input class="form-control" name="city" value="{{ old('city', $zone->city) }}" />
        </div>
        <div class="col-12">
          <label class="form-label">Descripción</label>
          <textarea class="form-control" name="description" rows="3">{{ old('description', $zone->description) }}</textarea>
        </div>
        <div class="col-12">
          <label class="form-label">Dirección / Centro</label>
          <input class="form-control" id="zone-address" name="center_address" value="{{ old('center_address', $zone->center_address) }}"
            placeholder="Escribe una dirección para el centro de la zona" />
          <input type="hidden" id="zone-lat" name="center_lat" value="{{ old('center_lat', $zone->center_lat) }}" />
          <input type="hidden" id="zone-lng" name="center_lng" value="{{ old('center_lng', $zone->center_lng) }}" />
        </div>
        <div class="col-md-4">
          <label class="form-label">Radio (km)</label>
          <input class="form-control" id="zone-radius" name="radius_km" value="{{ old('radius_km', $zone->radius_km ?? 3) }}" />
        </div>
        <div class="col-12">
          <div id="zone-map" style="height: 320px; border-radius: 12px;"></div>
        </div>
        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" @checked(old('is_active', $zone->is_active)) />
            <label class="form-check-label" for="is_active">Activa</label>
          </div>
        </div>
      </div>
      <div class="mt-3">
        <button class="btn btn-primary" type="submit">Guardar cambios</button>
      </div>
    </form>
  </div>
</div>
@endsection

@section('page-script')
  <script>
    window.initZoneMap = function initZoneMap() {
      const addressInput = document.getElementById('zone-address');
      const latInput = document.getElementById('zone-lat');
      const lngInput = document.getElementById('zone-lng');
      const radiusInput = document.getElementById('zone-radius');
      const mapEl = document.getElementById('zone-map');

      if (!addressInput || !mapEl) {
        return;
      }

      const defaultCenter = {
        lat: parseFloat(latInput.value) || 41.2675,
        lng: parseFloat(lngInput.value) || 2.9608
      };

      const map = new google.maps.Map(mapEl, {
        center: defaultCenter,
        zoom: 13,
      });

      const marker = new google.maps.Marker({
        map,
        position: defaultCenter,
        draggable: true,
      });

      const circle = new google.maps.Circle({
        map,
        center: defaultCenter,
        radius: (parseFloat(radiusInput.value) || 3) * 1000,
        fillColor: '#7367f0',
        fillOpacity: 0.12,
        strokeColor: '#7367f0',
        strokeOpacity: 0.6,
        strokeWeight: 2,
      });

      const autocomplete = new google.maps.places.Autocomplete(addressInput, {
        fields: ['formatted_address', 'geometry'],
      });

      autocomplete.addListener('place_changed', () => {
        const place = autocomplete.getPlace();
        if (!place.geometry || !place.geometry.location) {
          return;
        }

        const location = place.geometry.location;
        map.setCenter(location);
        map.setZoom(14);
        marker.setPosition(location);
        circle.setCenter(location);

        latInput.value = location.lat();
        lngInput.value = location.lng();
        addressInput.value = place.formatted_address || addressInput.value;
      });

      marker.addListener('dragend', () => {
        const position = marker.getPosition();
        circle.setCenter(position);
        latInput.value = position.lat();
        lngInput.value = position.lng();
      });

      radiusInput.addEventListener('input', () => {
        const km = parseFloat(radiusInput.value) || 0;
        circle.setRadius(km * 1000);
      });
    };

    (function loadZoneMapsScript() {
      if (window.google && window.google.maps) {
        return;
      }

      const script = document.createElement('script');
      script.src = 'https://maps.googleapis.com/maps/api/js?key={{ config('services.google.maps_key') ?: env('GOOGLE_MAPS_API_KEY') }}&libraries=places&loading=async&callback=initZoneMap';
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);
    })();
  </script>
@endsection
