@php
use App\Models\Attivita;
use App\Models\Endpoint;
$configData = Helper::appClasses();
$attivita = Attivita::find(session()->get('attivita_attuale'));
$stati = Endpoint::getStati();
$statusMeta = $endpoint->status && isset($stati[$endpoint->status]) ? $stati[$endpoint->status] : null;
$stampanti = $endpoint->stampanti;
$endpointInfo = is_array($endpoint->info) ? $endpoint->info : (json_decode($endpoint->info ?? '{}', true) ?: []);

$maskSecret = function (?string $value): string {
    if ($value === null || $value === '') {
        return '—';
    }
    $len = strlen($value);
    if ($len <= 8) {
        return str_repeat('•', $len);
    }
    return str_repeat('•', max(0, $len - 4)) . substr($value, -4);
};
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Endpoint — ' . ($endpoint->label ?? $endpoint->id))

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-0 mt-4">
    <i class="bx bx-server"></i>
    {{ $endpoint->label ?? 'Endpoint #' . $endpoint->id }}
  </h4>
  <nav aria-label="breadcrumb" class="mt-1" style="font-size: smaller;">
    <ol class="breadcrumb breadcrumb-custom-icon ">
      <li class="breadcrumb-item">
        <a href="{{ route('endpoint.index') }}">Endpoint</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">
        {{ $endpoint->label ?? ('#' . $endpoint->id) }}
      </li>
    </ol>
  </nav>
</div>
@endsection

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

<div class="row g-4">
  {{-- Sidebar riepilogo --}}
  <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">
            <i class="bx bx-chip bx-lg"></i>
          </span>
        </div>
        <h5 class="mb-1">{{ $endpoint->label ?? '—' }}</h5>
        <p class="text-muted small mb-3">ID #{{ $endpoint->id }}</p>

        @if($statusMeta)
          <span class="badge {{ $statusMeta['class'] }} mb-3">
            <i class="{{ $statusMeta['icon'] }}"></i>
            {{ $statusMeta['label'] }}
          </span>
        @else
          <span class="badge bg-label-secondary mb-3">Stato sconosciuto</span>
        @endif

        @if($endpoint->ubicazione)
          <p class="mb-0 text-muted small">
            <i class="bx bx-map-pin me-1"></i>{{ $endpoint->ubicazione }}
          </p>
        @endif
      </div>
      <div class="card-body border-top pt-3">
        <ul class="list-unstyled mb-0">
          <li class="d-flex align-items-center mb-3">
            <div class="avatar avatar-sm me-2">
              <span class="avatar-initial rounded bg-label-info"><i class="bx bx-printer"></i></span>
            </div>
            <div>
              <small class="text-muted d-block">Stampanti</small>
              <span class="fw-medium">{{ $stampanti->count() }}</span>
            </div>
          </li>
          <li class="d-flex align-items-center mb-3">
            <div class="avatar avatar-sm me-2">
              <span class="avatar-initial rounded bg-label-warning"><i class="bx bx-pulse"></i></span>
            </div>
            <div>
              <small class="text-muted d-block">Ultimo heartbeat</small>
              <span class="fw-medium small">
                @if($endpoint->last_heartbeat)
                  {{ $endpoint->last_heartbeat->format('d/m/Y H:i') }}
                @else
                  —
                @endif
              </span>
            </div>
          </li>
          <li class="d-flex align-items-center">
            <div class="avatar avatar-sm me-2">
              <span class="avatar-initial rounded bg-label-success"><i class="bx bx-time-five"></i></span>
            </div>
            <div>
              <small class="text-muted d-block">Ultima attività</small>
              <span class="fw-medium small">
                @if($endpoint->last_activity)
                  {{ $endpoint->last_activity->format('d/m/Y H:i') }}
                @else
                  —
                @endif
              </span>
            </div>
          </li>
        </ul>
      </div>
      <div class="card-body border-top pt-3 d-grid gap-2">
        <a href="{{ route('endpoint.index') }}" class="btn btn-label-secondary">
          <i class="bx bx-arrow-back me-1"></i> Torna all'elenco
        </a>
      </div>
    </div>
  </div>

  {{-- Dettagli --}}
  <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 d-flex align-items-center justify-content-between flex-wrap gap-2">
            <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">Etichetta</dt>
                  <dd class="col-sm-7 fw-medium">{{ $endpoint->label ?? '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Descrizione</dt>
                  <dd class="col-sm-7">{{ $endpoint->descrizione ?: '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Ubicazione</dt>
                  <dd class="col-sm-7">{{ $endpoint->ubicazione ?: '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Tipo</dt>
                  <dd class="col-sm-7">{{ $endpoint->type ?: '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Versione</dt>
                  <dd class="col-sm-7">
                    @if($endpoint->version)
                      <span class="badge bg-label-secondary">{{ $endpoint->version }}</span>
                    @else
                      —
                    @endif
                  </dd>
                </dl>
              </div>
              <div class="col-md-6">
                <dl class="row mb-0">
                  <dt class="col-sm-5 text-muted">Attività</dt>
                  <dd class="col-sm-7">{{ $endpoint->attivita?->nome ?? '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Utente</dt>
                  <dd class="col-sm-7">{{ $endpoint->user?->name ?? ($endpoint->user_id ? '#' . $endpoint->user_id : '—') }}</dd>

                  <dt class="col-sm-5 text-muted">Licenza</dt>
                  <dd class="col-sm-7">{{ $endpoint->licenza_id ? '#' . $endpoint->licenza_id : '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Registrato il</dt>
                  <dd class="col-sm-7">{{ $endpoint->created_at?->format('d/m/Y H:i') ?? '—' }}</dd>

                  <dt class="col-sm-5 text-muted">Aggiornato il</dt>
                  <dd class="col-sm-7">{{ $endpoint->updated_at?->format('d/m/Y H:i') ?? '—' }}</dd>
                </dl>
              </div>
            </div>
          </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-link text-info me-1"></i>
              Connessione
            </h5>
          </div>
          <div class="card-body">
            <dl class="row mb-0">
              <dt class="col-12 text-muted small mb-1">URL endpoint</dt>
              <dd class="col-12 mb-3">
                @if($endpoint->url)
                  <code class="d-block text-break user-select-all">{{ $endpoint->url }}</code>
                @else
                  <span class="text-muted">—</span>
                @endif
              </dd>

              <dt class="col-sm-5 text-muted">Heartbeat</dt>
              <dd class="col-sm-7">
                @if($endpoint->last_heartbeat)
                  {{ $endpoint->last_heartbeat->format('d/m/Y H:i') }}
                  <small class="text-muted d-block">{{ $endpoint->last_heartbeat->diffForHumans() }}</small>
                @else
                  <span class="text-muted">Mai ricevuto</span>
                @endif
              </dd>

              <dt class="col-sm-5 text-muted">Ultima attività</dt>
              <dd class="col-sm-7">
                @if($endpoint->last_activity)
                  {{ $endpoint->last_activity->format('d/m/Y H:i') }}
                  <small class="text-muted d-block">{{ $endpoint->last_activity->diffForHumans() }}</small>
                @else
                  <span class="text-muted">—</span>
                @endif
              </dd>
            </dl>
          </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-key text-warning me-1"></i>
              Credenziali
            </h5>
          </div>
          <div class="card-body">
            <label class="form-label small text-muted mb-2">Product key</label>
            @if($endpoint->product_key)
              @include('endpoint.nuovo_product_key', ['success' => true, 'endpoint' => $endpoint])
            @else
              <p class="text-muted small mb-3">Nessuna product key assegnata.</p>
            @endif

            <dl class="row mb-0 mt-3">
              <dt class="col-sm-4 text-muted small">Token</dt>
              <dd class="col-sm-8"><code class="small">{{ $maskSecret($endpoint->token) }}</code></dd>

              <dt class="col-sm-4 text-muted small">Secret</dt>
              <dd class="col-sm-8"><code class="small">{{ $maskSecret($endpoint->secret) }}</code></dd>
            </dl>
            <p class="text-muted small mb-0 mt-2">
              <i class="bx bx-info-circle"></i> Token e secret sono mascherati per sicurezza.
            </p>
          </div>
        </div>
      </div>

      <div class="col-12">
        <div class="card">
          <div class="card-header d-flex align-items-center justify-content-between">
            <h5 class="card-title mb-0">
              <i class="bx bx-printer text-primary me-1"></i>
              Stampanti collegate
            </h5>
            <span class="badge bg-label-primary">{{ $stampanti->count() }}</span>
          </div>
          <div class="card-body p-5">
            @if($stampanti->isNotEmpty())
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                  <thead class="">
                    <tr>
                      <th>ID</th>
                      <th>Nome</th>
                      <th>Tipo</th>
                    </tr>
                  </thead>
                  <tbody>
                    @foreach($stampanti as $dispositivo)
                      <tr>
                        <td class="text-muted">#{{ $dispositivo->id }}</td>
                        <td class="fw-medium">{{ $dispositivo->nome ?? '—' }}</td>
                        <td><span class="badge bg-label-secondary">{{ $dispositivo->tipo ?? '—' }}</span></td>
                      </tr>
                    @endforeach
                  </tbody>
                </table>
              </div>
            @else
              <div class="text-center text-muted py-5">
                <i class="bx bx-printer bx-lg d-block mb-2 opacity-50"></i>
                Nessuna stampante registrata su questo endpoint.
              </div>
            @endif
          </div>
        </div>
      </div>

      @if(!empty($endpointInfo))
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="bx bx-data text-secondary me-1"></i>
              Info aggiuntive (JSON)
            </h5>
          </div>
          <div class="card-body">
            <pre class="bg-lighter rounded p-3 mb-0 small text-break"><code>{{ json_encode($endpointInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</code></pre>
          </div>
        </div>
      </div>
      @endif
    </div>
  </div>
</div>
@endsection

@section('page-script')
@include('endpoint._partials.copy-product-key-script')
@endsection
