<?php
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
?>
@php
$configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Saltacoda')

@section('vendor-style')
@vite([
'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss',
'resources/assets/vendor/libs/flatpickr/flatpickr.scss',
'resources/assets/vendor/libs/@form-validation/form-validation.scss'
])
@endsection

<!-- Vendor Scripts -->
@section('vendor-script')
@vite([
'resources/assets/vendor/libs/moment/moment.js',
'resources/assets/vendor/libs/flatpickr/flatpickr.js',
'resources/assets/vendor/libs/@form-validation/popular.js',
'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
'resources/assets/vendor/libs/@form-validation/auto-focus.js',
'resources/assets/vendor/libs/@form-validation/popular.js',
'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
'resources/assets/vendor/libs/@form-validation/auto-focus.js',
'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js'
])
@endsection

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-0 text-sm-small mt-md-4 mt-lg-4"> 
    <i class="bx bxs-user-badge d-none d-md-inline-flex d-lg-inline-flex"></i> 
    Saltacoda
    <!-- Saltacoda di {{ $attivita->nome }} -->
  </h4>
  <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block d-lg-block">
            <ol class="breadcrumb breadcrumb-custom-icon">

              <li class="breadcrumb-item">
                <a href="{{ route('dispositivo.index') }}">Dispositivi</a>
                <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
              </li>

              <li class="breadcrumb-item active text-primary">
                <a href="{{ route('saltacoda.index') }}">Saltacoda</a>
                <!-- <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i> -->
              </li>

            </ol>
          </nav>
</div>
@endsection

@section('content')
<style>
  div.upload button:first-child{
    display: none !important;
  }

.bx-chef-hat{
  --svg: url("data:image/svg+xml,%3csvg width='24' height='24' fill='currentColor' viewBox='0 0 24 24' transform='' xmlns='http://www.w3.org/2000/svg'%3e%3c!--Boxicons v3.0.8 https://boxicons.com %7c License https://docs.boxicons.com/free--%3e%3cpath d='M17.13 5.54C16.33 3.42 14.32 2 12 2S7.67 3.42 6.87 5.54A5.506 5.506 0 0 0 2 11c0 2.07 1.18 3.95 3 4.88V18c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-2.12c1.82-.93 3-2.81 3-4.88 0-2.82-2.13-5.15-4.87-5.46m.53 8.75c-.4.14-.67.52-.67.94v1.78H7v-1.78c0-.42-.27-.8-.67-.94-1.4-.5-2.33-1.82-2.33-3.28 0-1.93 1.57-3.5 3.42-3.5.04 0 .14.01.18.02.49 0 .9-.31 1-.78.36-1.61 1.76-2.73 3.41-2.73s3.05 1.12 3.41 2.73c.1.47.51.81 1 .78.06 0 .12 0 .09-.01 1.93 0 3.5 1.57 3.5 3.5 0 1.47-.94 2.79-2.33 3.28ZM5 20h14v2H5z'%3e%3c/path%3e%3c/svg%3e");
}

div.dt-action-buttons .dt-buttons .btn:first-child {
  border-radius: 0.25rem 0 0 0.25rem !important;
 }
div.dt-action-buttons .dt-buttons .btn:last-child {
  border-radius: 0 0.25rem 0.25rem 0 !important;
 }
</style>

@include('_partials.status')


@if(isset($saltacoda))
<div class="row justify-content-center">
  <div class="col-xxl mb-4 mt-2">
    <div class="card">
      <div class="card-body">
    <form action="{{ route('saltacoda.store', ['attivita' => $attivita->id]) }}" method="POST" class="row g-3">
      @csrf

      <input type="hidden" name="attivita_id" value="{{ $attivita->id }}">

      <div class="col-md-6">
        <label for="is_attivo" class="form-label">Saltacoda attivo</label>
        <select name="is_attivo" id="is_attivo" class="form-select">
          <option value="1" {{ old('is_attivo', $saltacoda->is_attivo ?? 1) == 1 ? 'selected' : '' }}>Abilitato</option>
          <option value="0" {{ old('is_attivo', $saltacoda->is_attivo ?? 0) == 0 ? 'selected' : '' }}>Disabilitato</option>
        </select>
      </div>

      <div class="col-md-6">
        <label for="max_ordini" class="form-label">Numero massimo di ordini in coda</label>
        <input type="number" name="max_ordini" id="max_ordini" class="form-control" min="0" value="{{ old('max_ordini', $saltacoda->max_ordini ?? 0) }}">
      </div>

      <div class="col-12">
        <div class="accordion" id="saltacodaInfoAccordion">
          <div class="accordion-item">
            <h2 class="accordion-header" id="headingSaltacodaInfo">
              <button
                class="accordion-button collapsed"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseSaltacodaInfo"
                aria-expanded="false"
                aria-controls="collapseSaltacodaInfo"
              >
                Info aggiuntive (campi personalizzati)
              </button>
            </h2>
            <div
              id="collapseSaltacodaInfo"
              class="accordion-collapse collapse"
              aria-labelledby="headingSaltacodaInfo"
              data-bs-parent="#saltacodaInfoAccordion"
            >
              <div class="accordion-body pt-2">
                <p class="text-muted small mb-3">
                  Inserisci solo l'etichetta del campo. La chiave tecnica viene calcolata automaticamente.
                </p>
                <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle mb-0" id="user-friendly-info-table">
            <thead class="table-light">
              <tr>
                <th style="width: 36%;">Etichetta (visibile al cliente)</th>
                <th style="width: 24%;">Chiave auto-generata</th>
                <th style="width: 18%;">Tipo campo</th>
                <th style="width: 12%;" class="text-center">Obbligatorio</th>
                <th style="width: 10%;" class="text-center">Azioni</th>
              </tr>
            </thead>
            <tbody id="user-friendly-info-fields">
              <!-- Righe generate via JS -->
            </tbody>
          </table>
        </div>
                <input type="hidden" name="info" id="info" value="{{ old('info', $saltacoda->info ?? '') }}">
                <button type="button" class="btn btn-outline-secondary btn-sm mt-2" id="add-info-row">+ Aggiungi campo</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <script>
        document.addEventListener('DOMContentLoaded', function () {
          let info = {};
          @if(old('info', $saltacoda->info ?? false))
            try {
              info = JSON.parse(@json(old('info', $saltacoda->info ?? '')));
            } catch (e) { info = {}; }
          @endif
          const container = document.getElementById('user-friendly-info-fields');
          const infoInput = document.getElementById('info');
          const addBtn = document.getElementById('add-info-row');

          function slugifyKey(label) {
            let key = (label || '')
              .normalize('NFD')
              .replace(/[\u0300-\u036f]/g, '')
              .toLowerCase()
              .replace(/\s+/g, '_')
              .replace(/[^a-z0-9_]/g, '')
              .replace(/_+/g, '_')
              .replace(/^_+|_+$/g, '');

            if (!key) {
              key = 'campo';
            }

            if (/^\d/.test(key)) {
              key = `campo_${key}`;
            }

            return key;
          }

          function getUniqueKey(baseKey, usedKeys) {
            if (!usedKeys.has(baseKey)) {
              usedKeys.add(baseKey);
              return baseKey;
            }

            let suffix = 2;
            let candidate = `${baseKey}_${suffix}`;
            while (usedKeys.has(candidate)) {
              suffix += 1;
              candidate = `${baseKey}_${suffix}`;
            }
            usedKeys.add(candidate);
            return candidate;
          }

          function syncJson() {
            const newInfo = {};
            const usedKeys = new Set();
            const rows = container.querySelectorAll('tr[data-row-id]');
            const allowedTypes = ['text', 'boolean', 'time'];

            rows.forEach((rowEl) => {
              const labelInputEl = rowEl.querySelector('input[data-label-idx]');
              const keyPreviewEl = rowEl.querySelector('[data-key-preview]');
              const typeSelectEl = rowEl.querySelector('select[data-type-idx]');
              const requiredInputEl = rowEl.querySelector('input[data-required-idx]');
              const label = (labelInputEl.value || '').trim();

              if (!label) {
                keyPreviewEl.textContent = '-';
                return;
              }

              const baseKey = slugifyKey(label);
              const finalKey = getUniqueKey(baseKey, usedKeys);
              const type = allowedTypes.includes(typeSelectEl.value) ? typeSelectEl.value : 'text';
              const required = !!requiredInputEl.checked;
              keyPreviewEl.textContent = finalKey;
              newInfo[finalKey] = {
                label,
                type,
                required
              };
            });

            info = newInfo;
            infoInput.value = Object.keys(info).length > 0 ? JSON.stringify(info) : '';
          }

          function addRow(labelValue, typeValue, requiredValue) {
            const idx = Date.now() + Math.random();
            const row = document.createElement('tr');
            row.setAttribute('data-row-id', idx);
            row.innerHTML = `
              <td>
                <input type="text" class="form-control form-control-sm" placeholder="Es. Nome, Tavolo, Telefono..." data-label-idx="${idx}">
              </td>
              <td>
                <code class="text-primary" data-key-preview>-</code>
              </td>
              <td>
                <select class="form-select form-select-sm" data-type-idx="${idx}">
                  <option value="text">Testo</option>
                  <option value="boolean">Si / No</option>
                  <option value="number">Numero</option>
                  <option value="time">Orario</option>
                </select>
              </td>
              <td class="text-center">
                <input type="checkbox" class="form-check-input mt-0" data-required-idx="${idx}" title="Campo obbligatorio">
              </td>
              <td class="text-center">
                <button type="button" class="btn btn-link text-danger btn-sm p-0" data-remove-idx="${idx}" title="Rimuovi"><i class="bx bx-x"></i></button>
              </td>
            `;
            const labelInput = row.querySelector('input[data-label-idx]');
            labelInput.value = labelValue || '';
            const typeSelect = row.querySelector('select[data-type-idx]');
            typeSelect.value = ['text', 'boolean', 'time'].includes(typeValue) ? typeValue : 'text';
            const requiredInput = row.querySelector('input[data-required-idx]');
            requiredInput.checked = !!requiredValue;
            container.appendChild(row);
          }

          function renderFields() {
            container.innerHTML = '';
            const fields = Object.entries(info).map(([k, v]) => {
              if (typeof v === 'string') {
                return {
                  label: v.trim() !== '' ? v : k,
                  type: 'text',
                  required: false
                };
              }

              if (v && typeof v === 'object') {
                return {
                  label: typeof v.label === 'string' && v.label.trim() !== '' ? v.label : k,
                  type: ['text', 'boolean', 'time'].includes(v.type) ? v.type : 'text',
                  required: !!v.required
                };
              }

              return {
                label: k,
                type: 'text',
                required: false
              };
            });

            if (fields.length === 0) {
              addRow('', 'text', false);
            } else {
              fields.forEach((field) => addRow(field.label, field.type, field.required));
            }

            syncJson();
          }

          addBtn.onclick = function () {
            addRow('', 'text', false);
            syncJson();
          };

          container.addEventListener('input', function (event) {
            if (
              event.target.matches('input[data-label-idx]') ||
              event.target.matches('select[data-type-idx]') ||
              event.target.matches('input[data-required-idx]')
            ) {
              syncJson();
            }
          });

          container.addEventListener('click', function (event) {
            const removeBtn = event.target.closest('button[data-remove-idx]');
            if (!removeBtn) {
              return;
            }
            removeBtn.closest('tr').remove();
            if (container.querySelectorAll('tr[data-row-id]').length === 0) {
              addRow('', 'text', false);
            }
            syncJson();
          });

          renderFields();
        });
      </script>

      <div class="col-12">
        <label class="form-label">Istruzioni per il cliente</label>
        @php
          $note = [];
          $noteRaw = json_decode($saltacoda->note ?? '[]', true);
          if (is_array($noteRaw)) {
            foreach ($noteRaw as $key => $item) {
              if (! is_array($item)) {
                continue;
              }
              if (is_array($item['testo'] ?? null)) {
                foreach ($item['testo'] as $legacyLabel => $legacyValue) {
                  $note[] = [
                    'label' => (string) $legacyLabel,
                    'value' => is_scalar($legacyValue) ? (string) $legacyValue : '',
                  ];
                }
                continue;
              }
              if (is_array($item['value'] ?? null)) {
                foreach ($item['value'] as $legacyLabel => $legacyValue) {
                  $note[] = [
                    'label' => (string) $legacyLabel,
                    'value' => is_scalar($legacyValue) ? (string) $legacyValue : '',
                  ];
                }
                continue;
              }
              $label = trim((string) ($item['label'] ?? ''));
              $value = $item['value'] ?? $item['testo'] ?? '';
              $value = is_scalar($value) ? trim((string) $value) : '';
              if ($label === '' && is_string($key) && ! is_numeric($key)) {
                $label = $key;
              }
              if ($label !== '' || $value !== '') {
                $note[] = ['label' => $label, 'value' => $value];
              }
            }
          }
        @endphp

        @forelse($note as $key => $item)
          <div class="row mb-3">
            <div class="col-12">
              <input type="hidden" name="note[{{ $key }}][label]" value="{{ $item['label'] }}">
              <label for="note-value-{{ $key }}" class="form-label">{{ $item['label'] }}</label>
              <textarea
                rows="2"
                name="note[{{ $key }}][value]"
                id="note-value-{{ $key }}"
                class="form-control"
              >{{ $item['value'] }}</textarea>
            </div>
          </div>
        @empty
          <p class="text-muted small mb-0">Nessuna istruzione configurata.</p>
        @endforelse

      </div>

      <div class="col-12">
        <button type="submit" class="btn btn-primary">Salva impostazioni</button>
      </div>
    </form>
    </div>
    </div>
  </div>
</div>
@else
<div class="row justify-content-center">
  <div class="col-xxl mb-4 mt-2">
    <div class="card">
      <div class="card-body">
        <h4 class="mb-1">Saltacoda disabilitato</h4>
        <p class="mb-0">La saltacoda è disabilitato per questa attività.</p>
        <a href="{{ route('saltacoda.attiva', ['attivita_id' => $attivita->id]) }}" class="btn btn-primary">Abilita Saltacoda</a>
      </div>
    </div>
  </div>
@endif

@endsection

@section('page-script')

@endsection
