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

@extends('layouts/layoutMaster')

@section('title', 'Punti di vendita')

@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-1 text-sm-small mt-md-4 mt-lg-4"> 
    <i class="bx bx-store d-none d-md-inline-flex d-lg-inline-flex"></i> 
    {{ $puntoVendita->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('punto-vendita.index') }}">Punti di vendita</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('punto-vendita.edit', ['punto_vendita_id' => $puntoVendita->id]) }}">{{ $puntoVendita->nome }}</a>
</div>
@endsection

@section('content')

@php
  $tipiPuntoVendita = \App\Models\Dispositivo::getTipoPuntiVendita();
  $endpointList = \App\Models\Endpoint::query()->orderBy('label')->get();
  $cucineAssociateIds = $puntoVendita->hasCucine->pluck('id')->all();
  $cucine = $puntoVendita->hasCucine;
  $tipi = \App\Models\Dispositivo::getTipoDispositivo();
  $tipoMeta = $tipi->get($puntoVendita->tipo);
  $stampante = $puntoVendita->url_stampante ? $puntoVendita->stampante_dispositivo() : null;
  if ($stampante) {
    $stampante->loadMissing('endpoint');
  }
  $puoDissociareDispositivo = Auth::user()->hasRole('superadmin')
    || Auth::user()->hasRole('amministratore')
    || Auth::user()->hasRole('administrator');

  $campiOrdineCatalogo = [
    'cliente' => ['label' => 'Cliente', 'icon' => 'bx-user', 'type' => 'text', 'mostra' => true, 'required' => true, 'stampa' => true, 'placeholder' => 'Cliente'],
    'tavolo' => ['label' => 'Tavolo', 'icon' => 'bx-chair', 'type' => 'text', 'mostra' => true, 'required' => true, 'stampa' => true, 'placeholder' => 'Tavolo'],
    'coperti' => ['label' => 'N. coperti', 'icon' => 'bx-group', 'type' => 'number', 'mostra' => false, 'required' => false, 'stampa' => false, 'placeholder' => 'Coperti'],
    'telefono' => ['label' => 'Telefono', 'icon' => 'bx-phone', 'type' => 'tel', 'mostra' => false, 'required' => false, 'stampa' => false, 'placeholder' => 'Telefono'],
  ];
  $campiOrdineSalvati = $puntoVendita->info['campi_ordine'] ?? [];
  $campiOrdine = [];
  foreach ($campiOrdineCatalogo as $chiave => $defaults) {
    $campiOrdine[$chiave] = array_merge($defaults, $campiOrdineSalvati[$chiave] ?? []);
    $campiOrdine[$chiave]['custom'] = false;
  }
  foreach ($campiOrdineSalvati as $chiave => $campo) {
    if (! array_key_exists($chiave, $campiOrdineCatalogo)) {
      $campiOrdine[$chiave] = array_merge([
        'label' => $campo['label'] ?? ucfirst(str_replace('_', ' ', $chiave)),
        'icon' => 'bx-edit',
        'type' => $campo['type'] ?? 'text',
        'mostra' => false,
        'required' => false,
        'stampa' => false,
        'placeholder' => $campo['placeholder'] ?? ($campo['label'] ?? $chiave),
        'custom' => true,
      ], $campo);
      $campiOrdine[$chiave]['custom'] = true;
    }
  }
@endphp

<div class="nav-align-top">
  <ul class="nav nav-tabs nav-fill" role="tablist">
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link active" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-riepilogo" aria-controls="pv-tab-riepilogo" aria-selected="true">
        <i class="bx bx-list-ul me-1"></i>Riepilogo
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-generali" aria-controls="pv-tab-generali" aria-selected="false">
        <i class="bx bx-cog me-1"></i>Generali
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-dati-ordine" aria-controls="pv-tab-dati-ordine" aria-selected="false">
        <i class="bx bx-notepad me-1"></i>Dati ordine
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-cucine" aria-controls="pv-tab-cucine" aria-selected="false">
        <i class="bx bx-restaurant me-1"></i>Cucine
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-stampante" aria-controls="pv-tab-stampante" aria-selected="false">
        <i class="bx bx-printer me-1"></i>Stampante
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#pv-tab-licenze" aria-controls="pv-tab-licenze" aria-selected="false">
        <i class="bx bx-certification me-1"></i>Licenze
      </button>
    </li>
  </ul>

  <div class="tab-content">
    <div class="tab-pane fade show active" id="pv-tab-riepilogo" role="tabpanel">
      <div class="row g-4 mt-1">
        {{-- Sidebar profilo --}}
        <div class="col-12 col-lg-4 col-xl-3">
          <div class="card h-100">
            <div class="card-body text-center pt-4 pb-3">
              <div class="avatar avatar-xl mx-auto mb-3">
                <span class="avatar-initial rounded-circle bg-label-primary">
                  <i class="{{ $tipoMeta['icon'] ?? 'bx bx-store' }} bx-lg"></i>
                </span>
              </div>
              <h5 class="mb-1">{{ $puntoVendita->nome ?? '—' }}</h5>
              <p class="text-muted small mb-2">ID #{{ $puntoVendita->id }}</p>

              @if($tipoMeta)
                <span class="badge bg-label-info mb-3">
                  {{ $tipoMeta['label'] }}
                </span>
              @endif

              <ul class="list-unstyled text-start small mb-0">
                <li class="d-flex justify-content-between py-2 border-bottom">
                  <span class="text-muted">Stato</span>
                  @if($puntoVendita->is_attivo)
                    <span class="badge bg-label-success">Attivo</span>
                  @else
                    <span class="badge bg-label-danger">Non attivo</span>
                  @endif
                </li>
                <li class="d-flex justify-content-between py-2 border-bottom">
                  <span class="text-muted">Abbinamento</span>
                  @if($puntoVendita->binding_token)
                    <span class="badge bg-label-success">Abbinato</span>
                  @else
                    <span class="badge bg-label-danger">Libero</span>
                  @endif
                </li>
                <li class="d-flex justify-content-between py-2 border-bottom">
                  <span class="text-muted">Stampante</span>
                  @if($stampante)
                    <span class="badge bg-label-info text-truncate ms-2" style="max-width: 9rem;" title="{{ $stampante->nome }}">{{ $stampante->nome }}</span>
                  @else
                    <span class="badge bg-label-secondary">Assente</span>
                  @endif
                </li>
                <li class="d-flex justify-content-between py-2">
                  <span class="text-muted">Cucine</span>
                  <span class="badge bg-label-primary">{{ $cucine->count() }}</span>
                </li>
              </ul>
            </div>
            <div class="card-body border-top pt-3 d-grid gap-2">
              @can('view-punto_vendita')
              <a href="{{ route('punto-vendita.show', ['punto_vendita_id' => $puntoVendita->id]) }}" class="btn btn-primary btn-sm">
                <i class="bx bx-log-in me-1"></i> Entra nel punto vendita
              </a>
              @endcan
              <a href="{{ route('punto-vendita.index') }}" class="btn btn-label-secondary btn-sm">
                <i class="bx bx-arrow-back me-1"></i> Torna all'elenco
              </a>
            </div>
          </div>
        </div>

        {{-- Contenuto principale --}}
        <div class="col-12 col-lg-8 col-xl-9">
          <div class="d-flex flex-wrap gap-2 mb-1">
            <button type="button" class="btn btn-sm btn-outline-primary" data-pv-go-tab="#pv-tab-generali">
              <i class="bx bx-cog me-1"></i> Modifica generali
            </button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-pv-go-tab="#pv-tab-dati-ordine">
              <i class="bx bx-notepad me-1"></i> Dati ordine
            </button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-pv-go-tab="#pv-tab-cucine">
              <i class="bx bx-restaurant me-1"></i> Gestisci cucine
            </button>
            <button type="button" class="btn btn-sm btn-outline-primary" data-pv-go-tab="#pv-tab-stampante">
              <i class="bx bx-printer me-1"></i> Configura stampante
            </button>
          </div>

          <div class="row g-4">
            {{-- Informazioni generali --}}
            <div class="col-12">
              <div class="card">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="bx bx-info-circle text-primary me-1"></i>
                    Informazioni generali
                  </h5>
                </div>
                <div class="card-body">
                  <div class="row g-4">
                    <div class="col-md-6">
                      <dl class="row mb-0">
                        <dt class="col-sm-5 text-muted">Nome</dt>
                        <dd class="col-sm-7 fw-medium">{{ $puntoVendita->nome ?? '—' }}</dd>
                        <dt class="col-sm-5 text-muted">Tipo</dt>
                        <dd class="col-sm-7">{{ $tipoMeta['label'] ?? $puntoVendita->tipo ?? '—' }}</dd>
                        <dt class="col-sm-5 text-muted">Ubicazione</dt>
                        <dd class="col-sm-7">{{ $puntoVendita->ubicazione ?: '—' }}</dd>
                        <dt class="col-sm-5 text-muted">Attività</dt>
                        <dd class="col-sm-7">{{ $puntoVendita->attivita?->nome ?? '—' }}</dd>
                      </dl>
                    </div>
                    <div class="col-md-6">
                      <dl class="row mb-0">
                        <dt class="col-sm-5 text-muted">Licenza</dt>
                        <dd class="col-sm-7">{{ $puntoVendita->licenza ?: '—' }}</dd>
                        <dt class="col-sm-5 text-muted">PIN sblocco</dt>
                        <dd class="col-sm-7">
                          @if($puntoVendita->pin_sblocco)
                            <code>••••</code>
                            <span class="text-muted small">(configurato)</span>
                          @else
                            —
                          @endif
                        </dd>
                        <dt class="col-sm-5 text-muted">Creato il</dt>
                        <dd class="col-sm-7">{{ $puntoVendita->created_at?->format('d/m/Y H:i') ?? '—' }}</dd>
                        <dt class="col-sm-5 text-muted">Aggiornato il</dt>
                        <dd class="col-sm-7">{{ $puntoVendita->updated_at?->format('d/m/Y H:i') ?? '—' }}</dd>
                      </dl>
                    </div>
                  </div>
                  @if($puntoVendita->note)
                    <div class="mt-3 pt-3 border-top">
                      <p class="text-muted small mb-1">Note</p>
                      <p class="mb-0">{{ $puntoVendita->note }}</p>
                    </div>
                  @endif
                </div>
              </div>
            </div>

            {{-- Abbinamento, stampante, orari --}}
            <div class="col-md-4">
              <div class="card h-100">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="bx bx-link text-primary me-1"></i>
                    Abbinamento
                  </h5>
                </div>
                <div class="card-body d-flex flex-column">
                  @if($puntoVendita->binding_token)
                    <p class="mb-2">
                      <span class="badge bg-label-success">Dispositivo collegato</span>
                    </p>
                    <p class="text-muted small mb-3">Un terminale è associato a questo punto vendita tramite binding token.</p>
                    @if($puoDissociareDispositivo)
                      <button type="button" class="btn btn-sm btn-outline-danger mt-auto align-self-start" id="btnDissociaDispositivo">
                        <i class="bx bx-unlink me-1"></i> Dissocia
                      </button>
                    @endif
                  @else
                    <p class="mb-2">
                      <span class="badge bg-label-secondary">Nessun dispositivo</span>
                    </p>
                    <p class="text-muted small mb-0">Il punto vendita non risulta abbinato a un dispositivo fisico.</p>
                  @endif
                </div>
              </div>
            </div>

            <div class="col-md-4">
              <div class="card h-100">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="bx bx-printer text-info me-1"></i>
                    Stampante
                  </h5>
                </div>
                <div class="card-body">
                  @if($stampante)
                    <p class="mb-1 fw-medium">{{ $stampante->nome }}</p>
                    @if($stampante->endpoint)
                      <p class="mb-0 text-muted small">
                        <i class="bx bx-chip me-1"></i>
                        {{ $stampante->endpoint->label ?? 'Endpoint #' . $stampante->endpoint_id }}
                      </p>
                    @endif
                    @if($stampante->ubicazione)
                      <p class="mb-0 text-muted small mt-1">
                        <i class="bx bx-map-pin me-1"></i>{{ $stampante->ubicazione }}
                      </p>
                    @endif
                  @else
                    <p class="text-muted small mb-2">Nessuna stampante configurata per gli scontrini.</p>
                    <button type="button" class="btn btn-sm btn-label-info" data-pv-go-tab="#pv-tab-stampante">
                      Configura ora
                    </button>
                  @endif
                </div>
              </div>
            </div>

            <div class="col-md-4">
              <div class="card h-100">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="bx bx-time-five text-warning me-1"></i>
                    Orari turno
                  </h5>
                </div>
                <div class="card-body">
                  <dl class="row mb-0 small">
                    <dt class="col-5 text-muted">Apertura</dt>
                    <dd class="col-7 mb-2">{{ $puntoVendita->data_apertura_dispositivo?->format('d/m/Y H:i') ?? '—' }}</dd>
                    <dt class="col-5 text-muted">Chiusura</dt>
                    <dd class="col-7 mb-0">{{ $puntoVendita->data_chiusura_dispositivo?->format('d/m/Y H:i') ?? '—' }}</dd>
                  </dl>
                </div>
              </div>
            </div>

            {{-- Cucine --}}
            <div class="col-12">
              <div class="card">
                <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
                  <h5 class="card-title mb-0">
                    <i class="bx bx-restaurant text-primary me-1"></i>
                    Cucine associate
                  </h5>
                  <div class="d-flex align-items-center gap-2">
                    <span class="badge bg-label-primary">{{ $cucine->count() }}</span>
                    <button type="button" class="btn btn-sm btn-label-primary" data-pv-go-tab="#pv-tab-cucine">
                      Modifica
                    </button>
                  </div>
                </div>
                <div class="card-body">
                  @if($cucine->isNotEmpty())
                    <div class="d-flex flex-wrap gap-2">
                      @foreach($cucine as $cucina)
                        <span class="badge bg-label-primary fs-6 fw-normal px-3 py-2">
                          <i class="bx bx-restaurant me-1"></i>{{ $cucina->nome ?? '—' }}
                        </span>
                      @endforeach
                    </div>
                  @else
                    <p class="text-muted small mb-2">Nessuna cucina associata.</p>
                    <button type="button" class="btn btn-sm btn-label-primary" data-pv-go-tab="#pv-tab-cucine">
                      <i class="bx bx-plus me-1"></i> Associa cucine
                    </button>
                  @endif
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="tab-pane fade" id="pv-tab-generali" role="tabpanel">
      <form id="puntoVenditaEditForm" class="mt-1">
        @csrf
        <input type="hidden" name="punto_vendita_id" value="{{ $puntoVendita->id }}">
        <div class="row g-3">
          <div class="col-md-6">
            <label for="pv_nome" class="form-label">Nome</label>
            <input type="text" class="form-control" id="pv_nome" name="nome" data-pv-save value="{{ $puntoVendita->nome }}">
          </div>
          <div class="col-md-6">
            <label for="pv_tipo" class="form-label">Tipo</label>
            <select class="form-select" id="pv_tipo" name="tipo" data-pv-save>
              @foreach($tipiPuntoVendita as $label => $value)
                <option value="{{ $value }}" {{ $puntoVendita->tipo === $value ? 'selected' : '' }}>
                  {{ $label }}
                </option>
              @endforeach
            </select>
          </div>

          <div class="col-md-6">
            <label for="pv_pin_sblocco" class="form-label">PIN sblocco</label>
            <input type="text" class="form-control" id="pv_pin_sblocco" name="pin_sblocco" data-pv-save value="{{ $puntoVendita->pin_sblocco }}">
          </div>
          <div class="col-md-6">
            <label for="pv_ubicazione" class="form-label">Ubicazione</label>
            <input type="text" class="form-control" id="pv_ubicazione" name="ubicazione" data-pv-save value="{{ $puntoVendita->ubicazione }}">
          </div>

          <div class="col-md-6">
            <label for="pv_data_apertura" class="form-label">Data apertura dispositivo</label>
            <input type="datetime-local" class="form-control" id="pv_data_apertura" name="data_apertura_dispositivo" data-pv-save value="{{ $puntoVendita->data_apertura_dispositivo ? $puntoVendita->data_apertura_dispositivo->format('Y-m-d\TH:i') : '' }}">
          </div>
          <div class="col-md-6">
            <label for="pv_data_chiusura" class="form-label">Data chiusura dispositivo</label>
            <input type="datetime-local" class="form-control" id="pv_data_chiusura" name="data_chiusura_dispositivo" data-pv-save value="{{ $puntoVendita->data_chiusura_dispositivo ? $puntoVendita->data_chiusura_dispositivo->format('Y-m-d\TH:i') : '' }}">
          </div>

          <div class="col-md-6 d-flex align-items-end">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="pv_is_attivo" name="is_attivo" data-pv-save value="1" {{ $puntoVendita->is_attivo ? 'checked' : '' }}>
              <label class="form-check-label" for="pv_is_attivo">Dispositivo attivo</label>
            </div>
          </div>

          <div class="col-12">
            <label for="pv_note" class="form-label">Note</label>
            <textarea class="form-control" id="pv_note" name="note" data-pv-save rows="3">{{ $puntoVendita->note }}</textarea>
          </div>
        </div>
      </form>
    </div>

    <div class="tab-pane fade" id="pv-tab-dati-ordine" role="tabpanel">
      <div class="mt-1">
        <div class="alert alert-secondary d-flex align-items-start gap-2 mb-4" role="alert">
          <i class="bx bx-info-circle fs-5 mt-1"></i>
          <div>
            <strong>Campi mostrati in cassa</strong>
            <p class="mb-0 small">Configura i campi predefiniti o aggiungine di personalizzati. Per i campi nuovi inserisci solo etichetta e tipo: la chiave tecnica viene generata automaticamente e identifica il valore in <code>Ordine-&gt;info</code>.</p>
          </div>
        </div>

        <form id="puntoVenditaEditCampiOrdineForm">
          <div class="card mb-4 border-primary border-opacity-25">
            <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
              <h6 class="card-title mb-0"><i class="bx bx-plus-circle me-1"></i> Aggiungi campo personalizzato</h6>
            </div>
            <div class="card-body">
              <div class="row g-3 align-items-end">
                <div class="col-md-4">
                  <label for="pv_nuovo_campo_label" class="form-label">Etichetta</label>
                  <input type="text" class="form-control form-control-sm" id="pv_nuovo_campo_label" placeholder="es. Referente evento" autocomplete="off">
                  <div class="form-text">Mostrata all'operatore in cassa</div>
                </div>
                <div class="col-md-3">
                  <label for="pv_nuovo_campo_type" class="form-label">Tipo</label>
                  <select class="form-select form-select-sm" id="pv_nuovo_campo_type">
                    <option value="text">Testo</option>
                    <option value="tel">Telefono</option>
                    <option value="email">Email</option>
                    <option value="number">Numero</option>
                    <option value="checkbox">Checkbox</option>
                  </select>
                  <div class="form-text">Tipo di input mostrato all'operatore</div>
                </div>
                <div class="col-md-3">
                  <label class="form-label">Chiave generata</label>
                  <div class="form-control form-control-sm bg-light text-muted" id="pv_nuovo_campo_chiave_preview" aria-live="polite">—</div>
                  <div class="form-text">Calcolata dall'etichetta</div>
                </div>
                <div class="col-md-2">
                  <button type="button" class="btn btn-sm btn-primary w-100" id="pvAggiungiCampoOrdine">
                    <i class="bx bx-plus me-1"></i> Aggiungi
                  </button>
                  <div class="form-text">poi salva la configurazione</div>
                </div>
              </div>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th scope="col">Campo</th>
                  <th scope="col">Didascalia</th>
                  <th scope="col" class="text-center" style="width: 8rem;">Mostra</th>
                  <th scope="col" class="text-center" style="width: 8rem;">Obbligatorio</th>
                  <th scope="col" class="text-center" style="width: 8rem;">Stampa</th>
                  <th scope="col" class="text-center" style="width: 5rem;"></th>
                </tr>
              </thead>
              <tbody id="pvCampiOrdineBody">
                @foreach($campiOrdine as $chiave => $campo)
                  <tr
                    data-pv-campo-ordine="{{ $chiave }}"
                    data-pv-campo-type="{{ $campo['type'] ?? 'text' }}"
                    data-pv-campo-label="{{ $campo['label'] ?? $chiave }}"
                    data-pv-campo-custom="{{ !empty($campo['custom']) ? '1' : '0' }}"
                  >
                    <td>
                      <div class="d-flex align-items-center gap-2">
                        <span class="avatar avatar-sm">
                          <span class="avatar-initial rounded bg-label-primary">
                            <i class="bx {{ $campo['icon'] ?? 'bx-edit' }}"></i>
                          </span>
                        </span>
                        <div>
                          <span class="fw-medium">{{ $campo['label'] ?? $chiave }}</span>
                          <div class="text-muted small">
                            Chiave: <code>{{ $chiave }}</code>
                            @if(!empty($campo['custom']))
                              <span class="badge bg-label-warning ms-1">Personalizzato</span>
                            @endif
                          </div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <input type="text" class="form-control form-control-sm" id="pv_campo_{{ $chiave }}_placeholder" data-pv-campo-placeholder value="{{ $campo['placeholder'] ?? ($campo['label'] ?? $chiave) }}" placeholder="{{ $campo['placeholder'] ?? ($campo['label'] ?? $chiave) }}">
                    </td>
                    <td class="text-center">
                      <div class="form-check form-switch d-inline-block mb-0">
                        <input class="form-check-input" type="checkbox" id="pv_campo_{{ $chiave }}_mostra" data-pv-campo-mostra {{ !empty($campo['mostra']) ? 'checked' : '' }}>
                      </div>
                    </td>
                    <td class="text-center">
                      <div class="form-check form-switch d-inline-block mb-0">
                        <input class="form-check-input" type="checkbox" id="pv_campo_{{ $chiave }}_required" data-pv-campo-required {{ !empty($campo['required']) ? 'checked' : '' }}>
                      </div>
                    </td>
                    <td class="text-center">
                      <div class="form-check form-switch d-inline-block mb-0">
                        <input class="form-check-input" type="checkbox" id="pv_campo_{{ $chiave }}_stampa" data-pv-campo-stampa {{ !empty($campo['stampa']) ? 'checked' : '' }}>
                      </div>
                    </td>
                    <td class="text-center">
                      @if(!empty($campo['custom']))
                        <button type="button" class="btn btn-sm btn-icon btn-label-danger" data-pv-campo-rimuovi title="Rimuovi campo">
                          <i class="bx bx-trash"></i>
                        </button>
                      @endif
                    </td>
                  </tr>
                @endforeach
              </tbody>
            </table>
          </div>

          <div class="row g-4 mt-2">
            <div class="col-lg-6">
              <div class="card h-100">
                <div class="card-header">
                  <h6 class="card-title mb-0">
                    <i class="bx bx-show me-1"></i> Anteprima cassa
                  </h6>
                </div>
                <div class="card-body">
                  <div id="pvCampiOrdineAnteprima" class="row g-3">
                    @foreach($campiOrdine as $chiave => $campo)
                      <div class="col-md-6 pv-campo-anteprima" data-pv-anteprima="{{ $chiave }}" data-pv-anteprima-type="{{ $campo['type'] ?? 'text' }}" style="{{ !empty($campo['mostra']) ? '' : 'display:none;' }}">
                        @if(($campo['type'] ?? 'text') === 'checkbox')
                          <div class="form-check form-switch mt-1">
                            <input class="form-check-input" type="checkbox" id="pv_anteprima_{{ $chiave }}" disabled>
                            <label class="form-check-label small text-primary" for="pv_anteprima_{{ $chiave }}" data-pv-anteprima-label="{{ $chiave }}">{{ $campo['label'] ?? $chiave }}</label>
                          </div>
                        @else
                          <label class="form-label small text-primary mb-1" data-pv-anteprima-label="{{ $chiave }}">{{ ($campo['label'] ?? $chiave) }}</label>
                          <input type="{{ $campo['type'] ?? 'text' }}" class="form-control form-control-sm border-primary border-top-0 border-start-0 border-end-0 rounded-0 bg-transparent" disabled placeholder="{{ $campo['placeholder'] ?? $chiave }}">
                        @endif
                      </div>
                    @endforeach
                    <div class="col-md-6" data-pv-anteprima-totale>
                      <label class="form-label small text-primary mb-1">Totale</label>
                      <div class="fw-bold text-primary border-bottom border-primary pb-1">€ 0,00</div>
                    </div>
                  </div>
                  <p class="text-muted small mb-0 mt-3">Il totale resta sempre visibile in cassa.</p>
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="card h-100 border-primary border-opacity-25">
                <div class="card-body d-flex flex-column">
                  <h6 class="mb-2">Suggerimento</h6>
                  <p class="text-muted small mb-3">I campi predefiniti restano sempre disponibili. I campi personalizzati si aggiungono con la chiave che verrà usata in <code>Ordine-&gt;info</code>.</p>
                  <ul class="small text-muted mb-4 ps-3">
                    <li><strong>Mostra</strong> — compare nel riepilogo ordine in cassa</li>
                    <li><strong>Obbligatorio</strong> — richiesto prima del pagamento</li>
                    <li><strong>Stampa</strong> — compare sullo scontrino</li>
                    <li><strong>Didascalia</strong> — placeholder mostrato all'operatore</li>
                  </ul>
                  <button type="button" class="btn btn-primary mt-auto align-self-start" id="saveCampiOrdine">
                    <i class="bx bx-save me-1"></i> Salva configurazione
                  </button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>

    <div class="tab-pane fade" id="pv-tab-cucine" role="tabpanel">
      <form id="puntoVenditaEditCucineForm" class="mt-1" action="{{ route('punto-vendita.associa-cucina') }}" method="POST">
        @csrf
        <input type="hidden" name="punto_vendita_id" value="{{ $puntoVendita->id }}">
        <div class="row g-3">
          <div class="col-12">
            <i class="form-text text-muted mb-4">Seleziona quali cucine possono essere vendute da questo punto vendita</i>
            <div class="row mt-4">
              <div class="col-12">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" id="selectAllCucine" name="selectAllCucine" value="1">
                  <label class="form-check-label" for="selectAllCucine">Seleziona tutto</label>
                </div>
              </div>
              @foreach($puntoVendita->attivita->cucine as $cucina)
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" id="pv_cucina_id_{{ $cucina->id }}" name="cucina_id[]" value="{{ $cucina->id }}" {{ in_array($cucina->id, $cucineAssociateIds) ? 'checked' : '' }}>
                  <label class="form-check-label" for="pv_cucina_id_{{ $cucina->id }}">{{ $cucina->nome }}</label>
                </div>
              @endforeach
            </div>
          </div>
          <div class="col-12 text-center">
            <button type="button" class="btn btn-primary" id="saveCucine">Salva</button>
          </div>
        </div>
      </form>
    </div>

    <div class="tab-pane fade" id="pv-tab-stampante" role="tabpanel">
      <div class="row g-3 mt-1">
        <div class="col-md-6">
          <label for="pv_url_stampante" class="form-label">URL/ID stampante</label>
          <select class="form-select" id="pv_url_stampante" name="url_stampante" data-pv-save>
            <option value="">Seleziona stampante</option>
            @foreach($puntoVendita->attivita->stampanti as $stampante)
              <option value="{{ $stampante->id }}" {{ (int)$puntoVendita->url_stampante === (int)$stampante->id ? 'selected' : '' }}>
                {{ $stampante->nome }}
              </option>
            @endforeach
          </select>
        </div>
        <div class="col-md-6">
          <label for="pv_endpoint_id" class="form-label">Endpoint</label>
          <select class="form-select" id="pv_endpoint_id" name="endpoint_id" data-pv-save>
            <option value="">Seleziona endpoint</option>
            @foreach($endpointList as $endpoint)
              <option value="{{ $endpoint->id }}" {{ (int)$puntoVendita->endpoint_id === (int)$endpoint->id ? 'selected' : '' }}>
                {{ $endpoint->label ?? ('Endpoint #' . $endpoint->id) }}
              </option>
            @endforeach
          </select>
        </div>
      </div>
    </div>

    <div class="tab-pane fade" id="pv-tab-licenze" role="tabpanel">
      <div class="row g-3 mt-1">
        <div class="col-md-6">
          <label for="pv_licenza" class="form-label">Licenza</label>
          <input type="text" class="form-control" id="pv_licenza" name="licenza" data-pv-save value="{{ $puntoVendita->licenza }}">
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

@section('page-script')
<script type="module">
  $(document).ready(function() {
    var pvId = {{ $puntoVendita->id }};
    var pvTimer = {};

    function pvNotyf(type, message) {
      new Notyf({ duration: 2500, position: { x: 'right', y: 'top' } })[type](message);
    }

    function pvValoreCampo($el) {
      if ($el.is(':checkbox')) {
        return $el.is(':checked') ? 1 : 0;
      }
      return $el.val();
    }

    function pvAjaxError(xhr, fallback) {
      var msg = fallback;
      if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
        var key = Object.keys(xhr.responseJSON.errors)[0];
        msg = xhr.responseJSON.errors[key][0];
      } else if (xhr.responseJSON && xhr.responseJSON.message) {
        msg = xhr.responseJSON.message;
      }
      pvNotyf('error', msg);
    }

    function salvaCampo(nome, valore) {
      var data = {
        punto_vendita_id: pvId,
        _token: '{{ csrf_token() }}'
      };
      data[nome] = valore;

      $.ajax({
        url: '{{ route('punto-vendita.update') }}',
        method: 'POST',
        data: data,
        headers: { 'Accept': 'application/json' }
      })
      .done(function(res) {
        if (res.success) {
          pvNotyf('success', res.message || 'Salvato');
        } else {
          pvNotyf('error', res.message || 'Errore nel salvataggio');
        }
      })
      .fail(function(xhr) {
        pvAjaxError(xhr, 'Errore nel salvataggio');
      });
    }

    $(document).on('input.pvAutosave', '[data-pv-save]', function() {
      var $el = $(this);
      if ($el.is('select, :checkbox')) {
        return;
      }
      var name = $el.attr('name');
      if (!name) {
        return;
      }
      clearTimeout(pvTimer[name]);
      pvTimer[name] = setTimeout(function() {
        salvaCampo(name, pvValoreCampo($el));
      }, 500);
    });

    $(document).on('change.pvAutosave', '[data-pv-save]', function() {
      var $el = $(this);
      if (!$el.is('select, :checkbox')) {
        return;
      }
      var name = $el.attr('name');
      if (!name) {
        return;
      }
      salvaCampo(name, pvValoreCampo($el));
    });

    function dissociaDispositivo() {
      $.ajax({
        url: '{{ route('punto-vendita.dissocia-dispositivo', ['punto_vendita_id' => $puntoVendita->id]) }}',
        type: 'POST',
        data: {
          punto_vendita_id: pvId,
          _token: '{{ csrf_token() }}'
        },
        headers: { 'Accept': 'application/json' }
      })
      .done(function(response) {
        pvNotyf('success', response.message || 'Disassociazione completata');
        window.location.reload();
      })
      .fail(function(xhr) {
        pvAjaxError(xhr, 'Si è verificato un errore');
      });
    }

    $(document).on('click.pvDissocia', '#btnDissociaDispositivo', function() {
      if (confirm('Sei sicuro di voler dissociare il dispositivo?')) {
        dissociaDispositivo();
      }
    });

    $(document).on('click.pvGoTab', '#pv-tab-riepilogo [data-pv-go-tab]', function() {
      var target = $(this).data('pv-go-tab');
      if (!target) {
        return;
      }
      var tabEl = document.querySelector('.nav-link[data-bs-target="' + target + '"]');
      if (tabEl && window.bootstrap) {
        bootstrap.Tab.getOrCreateInstance(tabEl).show();
      }
    });

    var pvInfoEsistente = @json($puntoVendita->info ?? []);

    function pvNormalizzaChiaveCampo(valore) {
      var chiave = String(valore || '')
        .trim()
        .toLowerCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/\s+/g, '_')
        .replace(/[^a-z0-9_]/g, '')
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');

      if (chiave && /^[0-9]/.test(chiave)) {
        chiave = 'campo_' + chiave;
      }

      return chiave;
    }

    function pvGeneraChiaveCampoUnica(etichetta) {
      var base = pvNormalizzaChiaveCampo(etichetta);
      if (!base) {
        return '';
      }
      if (!/^[a-z]/.test(base)) {
        base = 'campo_' + base;
      }

      var chiave = base;
      var i = 2;
      while (pvCampoOrdineEsiste(chiave)) {
        chiave = base + '_' + i;
        i += 1;
      }
      return chiave;
    }

    function pvAggiornaAnteprimaChiaveCampo() {
      var etichetta = ($('#pv_nuovo_campo_label').val() || '').trim();
      var $preview = $('#pv_nuovo_campo_chiave_preview');
      if (!etichetta) {
        $preview.text('—').removeClass('text-danger text-success').addClass('text-muted');
        return;
      }
      var chiave = pvGeneraChiaveCampoUnica(etichetta);
      if (!chiave) {
        $preview.text('Etichetta non valida').removeClass('text-muted text-success').addClass('text-danger');
        return;
      }
      $preview.text(chiave).removeClass('text-muted text-danger').addClass('text-success');
    }

    function pvCampoOrdineEsiste(chiave) {
      return $('#pvCampiOrdineBody [data-pv-campo-ordine="' + chiave + '"]').length > 0;
    }

    function pvRaccogliCampiOrdine() {
      var campi = {};
      $('#pvCampiOrdineBody [data-pv-campo-ordine]').each(function() {
        var $row = $(this);
        var chiave = $row.data('pv-campo-ordine');
        campi[chiave] = {
          label: $row.data('pv-campo-label') || chiave,
          placeholder: $('#pv_campo_' + chiave + '_placeholder').val() || chiave,
          mostra: $('#pv_campo_' + chiave + '_mostra').is(':checked'),
          required: $('#pv_campo_' + chiave + '_required').is(':checked'),
          stampa: $('#pv_campo_' + chiave + '_stampa').is(':checked'),
          type: $row.data('pv-campo-type') || 'text',
          icon: String($row.data('pv-campo-custom')) === '1' ? 'bx-edit' : undefined
        };
        if (String($row.data('pv-campo-custom')) === '1') {
          campi[chiave].custom = true;
        }
      });
      return campi;
    }

    function pvAggiornaAnteprimaCampiOrdine() {
      $('#pvCampiOrdineBody [data-pv-campo-ordine]').each(function() {
        var $row = $(this);
        var chiave = $row.data('pv-campo-ordine');
        var mostra = $('#pv_campo_' + chiave + '_mostra').is(':checked');
        var label = $row.data('pv-campo-label') || chiave;
        var placeholder = $('#pv_campo_' + chiave + '_placeholder').val() || label;
        var $anteprima = $('[data-pv-anteprima="' + chiave + '"]');
        if (!$anteprima.length) {
          return;
        }
        $anteprima.toggle(mostra);
        $('[data-pv-anteprima-label="' + chiave + '"]').text(label);
        if ($anteprima.data('pv-anteprima-type') !== 'checkbox') {
          $anteprima.find('input:not([type=checkbox])').attr('placeholder', placeholder);
        }
      });
    }

    function pvAggiungiAnteprimaCampo(chiave, label, type, mostra) {
      if ($('[data-pv-anteprima="' + chiave + '"]').length) {
        return;
      }
      type = type || 'text';
      var $wrap = $('<div>', {
        class: 'col-md-6 pv-campo-anteprima',
        'data-pv-anteprima': chiave,
        'data-pv-anteprima-type': type
      }).toggle(!!mostra);

      if (type === 'checkbox') {
        var inputId = 'pv_anteprima_' + chiave;
        $wrap.append(
          $('<div>', { class: 'form-check form-switch mt-1' }).append(
            $('<input>', {
              class: 'form-check-input',
              type: 'checkbox',
              id: inputId,
              disabled: true
            }),
            $('<label>', {
              class: 'form-check-label small text-primary',
              for: inputId,
              'data-pv-anteprima-label': chiave,
              text: label
            })
          )
        );
      } else {
        $wrap.append(
          $('<label>', {
            class: 'form-label small text-primary mb-1',
            'data-pv-anteprima-label': chiave,
            text: label
          })
        );
        $wrap.append(
          $('<input>', {
            type: type,
            class: 'form-control form-control-sm border-primary border-top-0 border-start-0 border-end-0 rounded-0 bg-transparent',
            disabled: true,
            placeholder: label
          })
        );
      }

      $('#pvCampiOrdineAnteprima [data-pv-anteprima-totale]').before($wrap);
    }

    function pvAggiungiRigaCampoOrdine(chiave, label, type, options) {
      options = options || {};
      var mostra = options.mostra !== undefined ? options.mostra : true;
      var required = !!options.required;
      var stampa = !!options.stampa;
      var custom = options.custom !== false;

      var $row = $('<tr>', {
        'data-pv-campo-ordine': chiave,
        'data-pv-campo-type': type || 'text',
        'data-pv-campo-label': label,
        'data-pv-campo-custom': custom ? '1' : '0'
      });

      $row.append(
        '<td><div class="d-flex align-items-center gap-2">' +
          '<span class="avatar avatar-sm"><span class="avatar-initial rounded bg-label-primary"><i class="bx bx-edit"></i></span></span>' +
          '<div><span class="fw-medium">' + $('<div>').text(label).html() + '</span>' +
          '<div class="text-muted small">Chiave: <code>' + chiave + '</code>' +
          (custom ? ' <span class="badge bg-label-warning ms-1">Personalizzato</span>' : '') +
          '</div></div></div></td>'
      );
      $row.append(
        '<td><input type="text" class="form-control form-control-sm" id="pv_campo_' + chiave + '_placeholder" data-pv-campo-placeholder value="' + $('<div>').text(label).html() + '"></td>'
      );
      $row.append(
        '<td class="text-center"><div class="form-check form-switch d-inline-block mb-0">' +
          '<input class="form-check-input" type="checkbox" id="pv_campo_' + chiave + '_mostra" data-pv-campo-mostra' + (mostra ? ' checked' : '') + '></div></td>'
      );
      $row.append(
        '<td class="text-center"><div class="form-check form-switch d-inline-block mb-0">' +
          '<input class="form-check-input" type="checkbox" id="pv_campo_' + chiave + '_required" data-pv-campo-required' + (required ? ' checked' : '') + '></div></td>'
      );
      $row.append(
        '<td class="text-center"><div class="form-check form-switch d-inline-block mb-0">' +
          '<input class="form-check-input" type="checkbox" id="pv_campo_' + chiave + '_stampa" data-pv-campo-stampa' + (stampa ? ' checked' : '') + '></div></td>'
      );
      $row.append(
        '<td class="text-center">' +
          (custom ? '<button type="button" class="btn btn-sm btn-icon btn-label-danger" data-pv-campo-rimuovi title="Rimuovi campo"><i class="bx bx-trash"></i></button>' : '') +
        '</td>'
      );

      $('#pvCampiOrdineBody').append($row);
      pvAggiungiAnteprimaCampo(chiave, label, type, mostra);
    }

    function pvSalvaCampiOrdineServer() {
      var info = $.extend(true, {}, pvInfoEsistente || {});
      info.campi_ordine = pvRaccogliCampiOrdine();

      $.ajax({
        url: '{{ route('punto-vendita.update') }}',
        method: 'POST',
        data: {
          punto_vendita_id: pvId,
          info: JSON.stringify(info),
          _token: '{{ csrf_token() }}'
        },
        headers: { 'Accept': 'application/json' }
      })
      .done(function(response) {
        if (response.success) {
          pvInfoEsistente = info;
          pvNotyf('success', response.message || 'Configurazione salvata');
        } else {
          pvNotyf('error', response.message || 'Errore nel salvataggio');
        }
      })
      .fail(function(xhr) {
        pvAjaxError(xhr, 'Errore nel salvataggio');
      });
    }

    pvAggiornaAnteprimaCampiOrdine();

    $(document).on('change.pvCampiOrdine', '[data-pv-campo-mostra], [data-pv-campo-required]', function() {
      var $row = $(this).closest('[data-pv-campo-ordine]');
      var chiave = $row.data('pv-campo-ordine');
      if ($(this).is('[data-pv-campo-mostra]') && !$(this).is(':checked')) {
        $('#pv_campo_' + chiave + '_required').prop('checked', false);
      }
      pvAggiornaAnteprimaCampiOrdine();
    });

    $(document).on('input.pvCampiOrdine', '[data-pv-campo-placeholder]', function() {
      pvAggiornaAnteprimaCampiOrdine();
    });

    $(document).on('input.pvNuovoCampoLabel', '#pv_nuovo_campo_label', function() {
      pvAggiornaAnteprimaChiaveCampo();
    });

    pvAggiornaAnteprimaChiaveCampo();

    $(document).on('click.pvAggiungiCampoOrdine', '#pvAggiungiCampoOrdine', function() {
      var label = ($('#pv_nuovo_campo_label').val() || '').trim();
      var type = $('#pv_nuovo_campo_type').val() || 'text';
      var chiave = pvGeneraChiaveCampoUnica(label);

      if (!label) {
        pvNotyf('error', 'Inserisci un\'etichetta');
        return;
      }
      if (!chiave) {
        pvNotyf('error', 'Impossibile generare una chiave valida da questa etichetta');
        return;
      }

      pvAggiungiRigaCampoOrdine(chiave, label, type, { mostra: true, required: false, stampa: false, custom: true });
      pvAggiornaAnteprimaCampiOrdine();

      $('#pv_nuovo_campo_label').val('');
      $('#pv_nuovo_campo_type').val('text');
      pvAggiornaAnteprimaChiaveCampo();
      pvNotyf('success', 'Campo "' + label + '" aggiunto (chiave: ' + chiave + '). Salva la configurazione.');
    });

    $(document).on('click.pvRimuoviCampoOrdine', '[data-pv-campo-rimuovi]', function() {
      var $row = $(this).closest('[data-pv-campo-ordine]');
      var chiave = $row.data('pv-campo-ordine');
      if (!confirm('Rimuovere il campo "' + chiave + '"?')) {
        return;
      }
      $row.remove();
      $('[data-pv-anteprima="' + chiave + '"]').remove();
    });

    $(document).on('click.pvSaveCampiOrdine', '#saveCampiOrdine', function() {
      pvSalvaCampiOrdineServer();
    });

    $(document).on('click.pvSaveCucine', '#saveCucine', function() {
      var $form = $('#puntoVenditaEditCucineForm');
      var cucineIds = [];
      $form.find('input[name="cucina_id[]"]:checked').each(function() {
        cucineIds.push($(this).val());
      });

      $.ajax({
        url: $form.attr('action'),
        method: 'POST',
        data: {
          cucine_ids: cucineIds,
          punto_vendita_id: $form.find('input[name="punto_vendita_id"]').val(),
          _token: $form.find('input[name="_token"]').val()
        },
        headers: { 'Accept': 'application/json' }
      })
      .done(function(response) {
        if (response.success) {
          pvNotyf('success', response.message);
        } else {
          pvNotyf('error', response.message);
        }
      })
      .fail(function(xhr) {
        pvAjaxError(xhr, 'Si è verificato un errore');
      });
    });
  });
</script>
@endsection