@php
use App\Models\Attivita;
use App\Models\Dispositivo;

$configData = Helper::appClasses();
$attivita = Attivita::find(session()->get('attivita_attuale'));
$tipi = Dispositivo::getTipoDispositivo();
$tipoMeta = $tipi->get($puntoVendita->tipo);
$stampante = $puntoVendita->url_stampante ? $puntoVendita->stampante_dispositivo() : null;
if ($stampante) {
    $stampante->loadMissing('endpoint');
}
$cucine = $puntoVendita->hasCucine;
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Punto vendita — ' . ($puntoVendita->nome ?? $puntoVendita->id))

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-0"> <!-- mt-4 -->
    <i class="bx bx-store"></i>
    {{ $puntoVendita->nome ?? 'Punto vendita #' . $puntoVendita->id }}
  </h4>
  <nav aria-label="breadcrumb" class="mt-1" style="font-size: smaller;">
    <ol class="breadcrumb breadcrumb-custom-icon m-0">
      <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>
      @if($attivita)
      <li class="breadcrumb-item text-muted">
        {{ $attivita->nome }}
        <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
      </li>
      @endif
      <li class="breadcrumb-item active text-primary">
        {{ $puntoVendita->nome ?? ('#' . $puntoVendita->id) }}
      </li>
    </ol>
  </nav>
</div>
@endsection

@section('content')
@include('_partials.status')

<div class="row g-4">
  <div class="col-12 col-lg-4 col-xl-3">
    <div class="card mb-4">
      <div class="card-body text-center pt-4">
        <div class="avatar avatar-xl mx-auto mb-3">
          <span class="avatar-initial rounded-circle bg-label-primary">
            @if($tipoMeta && !empty($tipoMeta['icon']))
              <i class="bx bx-store bx-lg"></i>
              <!-- <i class="{{ $tipoMeta['icon'] }} bx-lg"></i> -->
            @else
              <i class="bx bx-store bx-lg"></i>
            @endif
          </span>
        </div>
        <h5 class="mb-1">{{ $puntoVendita->nome ?? '—' }}</h5>
        <p class="text-muted small mb-3">ID #{{ $puntoVendita->id }}</p>

        @if($tipoMeta)
          <span class="badge bg-label-info mb-3">
            <i class="{{ $tipoMeta['icon'] ?? 'bx bx-store' }} me-1"></i>
            {{ $tipoMeta['label'] }}
          </span>
        @endif

        @if($puntoVendita->is_attivo)
          <span class="badge bg-label-success mb-2">Attivo</span> <!-- d-block -->
        @else
          <span class="badge bg-label-danger mb-2">Non attivo</span> <!-- d-block -->
        @endif

        @if($puntoVendita->binding_token)
            <span class="badge bg-label-success">Abbinato</span>
            @else
              <span class="badge bg-label-danger">Non abbinato</span>
            @endif

        @if($puntoVendita->ubicazione)
          <p class="mb-0 text-muted small">
            <i class="bx bx-map-pin me-1"></i>{{ $puntoVendita->ubicazione }}
          </p>
        @endif
      </div>
      <div class="card-body border-top pt-3 d-grid gap-2">
        <a href="{{ route('punto-vendita.index') }}" class="btn btn-label-secondary">
          <i class="bx bx-arrow-back me-1"></i> Torna all'elenco
        </a>
        @can('view-punto_vendita')
        <a href="{{ route('punto-vendita.show', ['punto_vendita_id' => $puntoVendita->id]) }}" class="btn btn-primary">
          <i class="bx bx-log-in me-1"></i> Entra nel punto vendita
        </a>
        @endcan
        @can('edit-punto_vendita')
        <button type="button" class="btn btn-outline-primary" onclick="openModalPuntoVendita('{{ $puntoVendita->id }}')">
          <i class="bx bx-edit-alt me-1"></i> Modifica
        </button>
        @endcan
      </div>
    </div>
  </div>

  <div class="col-12 col-lg-8 col-xl-9">
    <div class="row g-4">
      <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>

      <div class="col-md-6">
        <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 collegata
            </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>
                  Endpoint: {{ $stampante->endpoint->label ?? '#' . $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 mb-0">
                <i class="bx bx-info-circle me-1"></i>
                Nessuna stampante associata a questo punto vendita.
              </p>
            @endif
          </div>
        </div>
      </div>

      <div class="col-md-6">
        <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 dispositivo
            </h5>
          </div>
          <div class="card-body">
            <dl class="row mb-0">
              <dt class="col-sm-5 text-muted">Apertura</dt>
              <dd class="col-sm-7">{{ $puntoVendita->data_apertura_dispositivo?->format('d/m/Y H:i') ?? '—' }}</dd>
              <dt class="col-sm-5 text-muted">Chiusura</dt>
              <dd class="col-sm-7">{{ $puntoVendita->data_chiusura_dispositivo?->format('d/m/Y H:i') ?? '—' }}</dd>
            </dl>
          </div>
        </div>
      </div>

      <div class="col-6">
        <div class="card p-4">
          <div class="card-header d-flex align-items-center justify-content-between">
            <h5 class="card-title mb-0">
              <i class="bx bx-restaurant text-primary me-1"></i>
              Cucine associate
            </h5>
            <span class="badge bg-label-primary">{{ $cucine->count() }}</span>
          </div>
          <div class="card-body p-0">
            @if($cucine->isNotEmpty())
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                  <thead class="table-light">
                    <tr>
                      <th>Nome</th>
                      <th class="text-center">Attiva</th>
                    </tr>
                  </thead>
                  <tbody>
                    @foreach($cucine as $cucina)
                      <tr>
                        <td class="fw-medium">{{ $cucina->nome ?? '—' }}</td>
                        <td class="text-center">
                          @if($cucina->is_attiva ?? false)
                            <span class="badge bg-label-success">Sì</span>
                          @else
                            <span class="badge bg-label-secondary">No</span>
                          @endif
                        </td>
                      </tr>
                    @endforeach
                  </tbody>
                </table>
              </div>
            @else
              <div class="text-center text-muted py-5">
                <i class="bx bx-restaurant bx-lg d-block mb-2 opacity-50"></i>
                Nessuna cucina associata. Puoi aggiungerle dalla modifica del punto vendita.
              </div>
            @endif
          </div>

        </div>
    </div>

    <div class="col-6">
      <div class="card p-4">
        <div class="card-header d-flex align-items-center justify-content-between">
          <h5 class="card-title mb-0">
            <i class="bx bx-hash text-primary me-1"></i>
            Stato abbinamento
          </h5>
        </div>
        <div class="card-body p-0">
          <p class="mb-0">
            @if($puntoVendita->binding_token)
            <span class="badge bg-label-success fs-5" mx-5">Abbinato</span>
            <button class="btn btn-danger" onclick="if(confirm('Sei sicuro di voler dissociare il dispositivo?')) dissociaDispositivo()">Dissocia dispositivo</button>
       
            @else
              <span class="badge bg-label-danger">Non abbinato</span>
            @endif
          </p>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalPuntoVendita" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalPuntoVenditaTitle">Modifica punto vendita</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
      </div>
      <div class="modal-body">
        <div id="modalPuntoVenditaBody"></div>
      </div>
    </div>
  </div>
</div>
@endsection

@section('page-script')
<script>
  function openModalPuntoVendita(id) {
    $('#modalPuntoVenditaBody').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>');
    $('#modalPuntoVenditaTitle').text('Modifica punto vendita');
    $('#modalPuntoVendita').modal('show');
    $('#modalPuntoVenditaBody').load("{{ route('punto-vendita.edit') }}?punto_vendita_id=" + id);
  }


  function dissociaDispositivo() {
    $.ajax({
      url: "{{ route('punto-vendita.dissocia-dispositivo', ['punto_vendita_id' => $puntoVendita->id]) }}",
      type: "POST",
      data: {
        punto_vendita_id: "{{ $puntoVendita->id }}",
        _token: "{{ csrf_token() }}",
      },
      success: function(response) {
       new Notyf({
        type: 'success',
        layout: 'topRight',
        text: response.message || 'Disassociazione completata',
        timeout: 3000
      }).success(response.message);
      window.location.reload();
      },
      error: function(xhr, status, error) {
        new Notyf({
          type: 'error',
          layout: 'topRight',
          text: xhr.responseJSON.message || 'Si è verificato un errore',
          timeout: 3000
        }).error(xhr.responseJSON.message);
      }
    });
  }
</script>
@endsection
