<!doctype html>
<html lang="es">

<head>
  <meta charset="utf-8">
  <title>Nuevo formulario</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  @vite(['resources/css/app.css', 'resources/js/app.js', 'resources/css/animated-bg.css'])
</head>



{{-- resources/views/formularios/create.blade.php --}}
<x-layout>
  <x-slot:title>Auditoría — Crear acta</x-slot:title>



  <!-- Fondo animado (aislado) -->
  <ul class="circles-form" aria-hidden="true">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>

  <div class="form-content-layer">

    <h1 style="font-size:20px; font-weight:700; margin:0 0 16px;">Aplicativo Auditoria Capita > Home > Formulario </h1>

   

    {{-- ===== Cabecera: info básica proveniente de la base ===== --}}
    @if ($seleccion)
      <div class="mb-6 p-4 rounded-lg border bg-white">
        <h2 class="font-semibold mb-2 text-black">Sede seleccionada</h2>
        <dl class="grid md:grid-cols-2 gap-2 text-sm">
          <div>
            <dt class="font-bold text-blue-900">Departamento:</dt>
            <dd class="font-medium text-black">{{ $seleccion['departamento'] }}
            </dd>
          </div>
          <div>
            <dt class="font-bold text-blue-900">Prestador:</dt>
            <dd class="font-medium text-black">{{ $seleccion['prestador'] }}</dd>
          </div>
          <div>
            <dt class="font-bold text-blue-900">Sede:</dt>
            <dd class="font-medium text-black">{{ $seleccion['municipio'] }}</dd>
          </div>
          <div>
            <dt class="font-bold text-blue-900">NIT:</dt>
            <dd class="font-medium text-black">{{ $seleccion['nit'] }}</dd>
          </div>
          
          <div>
            <dt class="font-bold text-blue-900">Tipo de red:</dt>
            <dd class="font-medium text-black">{{ $seleccion['tipo_red'] ?? '' }}</dd>
          </div>
          <div>
            <dt class="font-bold text-blue-900">Fecha del informe:</dt>
            <dd class="font-medium text-black">
              <input id="fecha_informe_ui" type="date" class="border rounded px-2 py-1"
                     min="{{ now()->toDateString() }}" value="{{ now()->toDateString() }}">
            </dd>
          </div>

        </dl>
        
      </div>
    @endif

    {{-- ===== Formulario con Stepper (solo envía al final) ===== --}}
    <section class="rounded-lg border p-4 bg-white white:bg-zinc-900">
      
      <form method="POST"
      action="{{ route('formularios.store') }}"
      enctype="multipart/form-data"
      x-data="formStepper(5, ['Datos básicos','Disposiciones','Ejecución','Indicadores','Resumen'])"
      x-ref="form"
      x-init="(() => { try { const s = @js(session('stay_on_step')); if (s) { step = Number(s); requestAnimationFrame(() => $root.scrollIntoView({behavior:'smooth', block:'start'})); } } catch(e){} })()"
      @submit.prevent="onSubmit">
  @csrf
        <input type="hidden" name="fecha_informe" id="fecha_informe_hidden" value="{{ now()->toDateString() }}">



        @csrf

        {{-- Indicador de pasos (no clickeable para evitar saltarse validaciones) --}}
        <nav aria-label="Progreso del formulario" class="mb-2">
          <ol class="flex items-center">
            <template x-for="(label, idx) in labels" :key="idx">
              <li class="flex items-center flex-1">
                <div class="relative z-10 flex items-center justify-center w-8 h-8 rounded-full text-xs font-semibold"
                  :class="(idx + 1) <= step ? 'bg-blue-400 text-white' : 'bg-gray-200 dark:bg-blue-900 text-white-600'">
                  <span x-text="idx + 1"></span>
                </div>
                <span class="ml-2 mr-4 text-sm text-black" x-text="label"></span>
                <template x-if="idx < labels.length - 1">
                  <div class="w-8 h-[2px] bg-gray-300 dark:bg-zinc-700 mx-1"></div>
                </template>
              </li>
            </template>
          </ol>
        </nav>

        <div class="flex items-center justify-between pt-4 border-t" x-show="step < total">
          <button type="button" class="px-4 py-2 rounded-lg border text-sm" :disabled="step === 1" @click="prev()">
            Anterior
          </button>

          <div class="space-x-2">
            <button type="button" x-show="step < total" class="px-4 py-2 rounded-lg bg-blue-600 text-white text-sm"
              @click="next()">
              Siguiente
            </button>
          </div>
        </div>

        <div class="pt-4"></div>

        {{-- ===== Paso 1: tu sección original como partial ===== --}}
        @php $b = $prefill ?? []; @endphp
        @include('formularios.sections._datos_basicos')

        {{-- ===== Pasos 2-4 (se agregarán luego) ===== --}}
        @include('formularios.sections._disposiciones')
        @include('formularios.sections._ejecucion')
        @include('formularios.sections._indicadores')
        @include('formularios.sections._resumen')

        {{-- Controles de navegación (sin guardado intermedio) --}}
        <div class="flex items-center justify-between pt-4 border-t" x-show="step < total">
          <button type="button" class="px-4 py-2 rounded-lg border text-sm" :disabled="step === 1" @click="prev()">
            Anterior
          </button>

          <div class="space-x-2">
            <button type="button" x-show="step < total" class="px-4 py-2 rounded-lg bg-blue-600 text-white text-sm"
              @click="next()">
              Siguiente
            </button>
          </div>
        </div>

      </form>
      <script>
        
        (function syncFechaInforme(){
          const ui = document.getElementById('fecha_informe_ui');
          const hid = document.getElementById('fecha_informe_hidden');
          if (!ui || !hid) return;
          const sync = () => { hid.value = ui.value || '{{ now()->toDateString() }}'; };
          ui.addEventListener('change', sync);
          ui.addEventListener('input', sync);
          sync();
        })();
        window.descargarReporte = function () {
          const form = document.getElementById('form-auditoria');
          if (!form) {
            console.error('No se encontró el formulario con id="form-auditoria"');
            return;
          }

          // Guarda attrs originales
          const orig = {
            action: form.action,
            target: form.target,
            method: form.method,
            enctype: form.enctype
          };

          // Bandera opcional para el controller (si quieres diferenciar)
          const preview = document.createElement('input');
          preview.type = 'hidden';
          preview.name = '_preview';
          preview.value = '1';
          form.appendChild(preview);

          // Redirige a la ruta del PDF
          form.action = "{{ route('formularios.pdf') }}";
          form.target = "_blank";          // abre en nueva pestaña
          form.method = "POST";            // necesario para CSRF de Laravel
          // mantenemos enctype tal cual (multipart si tu form lo usa)

          // Enviar (sin validación nativa)
          const prevNoVal = form.noValidate;
          form.noValidate = true;
          form.submit();
          form.noValidate = prevNoVal;

          // Restaurar estado original
          form.action = orig.action;
          form.target = orig.target;
          form.method = orig.method;
          form.enctype = orig.enctype;
          preview.remove();
        };
      </script>
    </section>
  </div>


   @if (session('ok'))
      @php $u = session('updated_info'); @endphp
      <div x-data="{ open: true }" x-show="open" x-cloak class="fixed inset-0 z-50">
        <div class="absolute inset-0 bg-black/50" @click="open=false"></div>
        <div class="absolute inset-0 flex items-center justify-center p-4">
          <div class="w-full max-w-lg bg-white rounded-lg shadow-xl border text-black">
            <div class="px-5 py-4 border-b flex items-center gap-2">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5 text-green-600">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.172 7.707 8.879a1 1 0 10-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
              </svg>
              <div class="font-semibold text-green-800">Actualizado con éxito</div>
            </div>
            <div class="px-5 py-4 text-sm">
              <div class="font-semibold mb-1">{{ session('ok') }}</div>
              @if ($u)
                <div class="space-y-1">
                  <div><span class="font-medium">Prestador:</span> {{ $u['prestador'] ?? '' }}</div>
                  <div><span class="font-medium">Sede:</span> {{ $u['sede'] ?? '' }} <span class="text-gray-500">({{ $u['departamento'] ?? '' }})</span></div>
                  <div class="text-gray-600"><span class="font-medium">Periodo:</span> {{ $u['periodo'] ?? '' }} — <span class="font-medium">Año:</span> {{ $u['anio'] ?? '' }}</div>
                </div>
              @endif
              @if (session('saved_html_url'))
                <div class="mt-3">
                  <a href="{{ session('saved_html_url') }}" target="_blank" class="text-indigo-600 hover:underline">Ver HTML guardado</a>
                </div>
              @endif
            </div>
            <div class="px-5 py-3 border-t flex justify-end gap-2">
              <button type="button" class="px-4 py-2 rounded border" @click="open=false">Cancelar</button>
              <button type="button" class="px-4 py-2 rounded bg-indigo-600 text-white" @click="open=false">Aceptar</button>
            </div>
          </div>
        </div>
      </div>
    @endif

</x-layout>



<script>
  document.addEventListener("DOMContentLoaded", function () {
    var dbg = document.getElementById("analytics-debug");
    if (dbg) { try { dbg.scrollIntoView({ behavior: "smooth", block: "start" }); } catch (e) { dbg.scrollIntoView(); } }

    // Desactiva validación nativa del navegador para el formulario del stepper
    try {
      var form = document.querySelector('form[x-data^="formStepper"]');
      if (form) {
        form.noValidate = true;
        try { form.id = 'form-auditoria'; } catch (e) {}
      }
    } catch (e) {}
  });
</script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const inputVU = document.getElementById('input_valor_per_capita');

    function renderVU() {
      const vu = Number(inputVU?.value || 0);
      const texto = vu.toFixed(2);

      // Pinta la columna “Valor x usuario”
      document.querySelectorAll('.js-valor-usuario').forEach(el => {
        el.textContent = texto;
      });

      // Actualiza hidden(s) si los estás enviando al backend
      document.querySelectorAll('.js-valor-usuario-hidden').forEach(el => {
        el.value = texto;
      });

      // (Opcional) recalcula columnas dependientes: VC = poblacion * vu
      document.querySelectorAll('[data-poblacion]').forEach(row => {
        const pob = Number(row.getAttribute('data-poblacion') || 0);
        const vc = pob * vu;
        const vcEl = row.querySelector('.js-valor-contratado');
        const vcHidden = row.querySelector('.js-valor-contratado-hidden');
        if (vcEl) vcEl.textContent = vc.toFixed(2);
        if (vcHidden) vcHidden.value = vc.toFixed(2);
      });
    }

    if (inputVU) {
      // Pinta al cargar
      renderVU();
      // Y cada vez que el usuario cambie el valor
      inputVU.addEventListener('input', renderVU);
      inputVU.addEventListener('change', renderVU);
    }
  });
</script>

</html>
