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

@extends('layouts/layoutMaster')

@section('title', 'Mappa Dispositivi')

@section('vendor-style')
@vite(['resources/assets/vendor/libs/bs-stepper/bs-stepper.scss'])
@endsection

@section('vendor-script')
@vite(['resources/assets/vendor/libs/bs-stepper/bs-stepper.js'])
@endsection

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1">
    <i class="bx bx-devices"></i> Mappa dispositivi
  </h4>
  <p class="text-muted small mb-0">
    @if($attivitaCorrente)
      Attività: <strong>{{ $attivitaCorrente->nome }}</strong> ·
    @endif
    {{ $totaleDispositivi }} dispositivi totali · {{ $totaleAttivi }} attivi
  </p>
</div>
@endsection

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

<style>
  .md-device-col:has(.md-device-card.is-hidden-by-filter) {
    display: none !important;
  }
  .md-device-card {
    transition: box-shadow .15s ease, transform .15s ease;
  }
  .md-device-card:hover {
    box-shadow: 0 8px 20px rgba(67, 89, 113, .1);
    transform: translateY(-2px);
  }
  .md-device-card.is-hidden-by-filter {
    display: none !important;
  }
  .md-device-card__icon {
    width: 3.5rem;
    height: 3.5rem;
    border-radius: .875rem;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    background: rgba(var(--bs-primary-rgb), .12);
    color: var(--bs-primary);
    font-size: 1.75rem;
  }
  .md-device-card__actions .btn {
    flex: 1;
    min-width: 0;
  }
  .md-tab-empty {
    border: 1px dashed rgba(67, 89, 113, .25);
    border-radius: .75rem;
    padding: 2.5rem 1rem;
    text-align: center;
    color: var(--bs-secondary-color);
  }
  .md-view-tabs .nav-link {
    display: inline-flex;
    align-items: center;
    gap: .35rem;
  }
  .md-pane-section.is-hidden-by-filter {
    display: none !important;
  }
</style>

<ul class="nav nav-pills mb-3 md-view-tabs" id="mdViewTabs" role="tablist">
  <li class="nav-item" role="presentation">
    <button
      class="nav-link active"
      id="md-tab-simple"
      data-bs-toggle="pill"
      data-bs-target="#mdPaneSimple"
      type="button"
      role="tab"
      aria-controls="mdPaneSimple"
      aria-selected="true">
      <i class="bx bx-grid-alt"></i> Elenco attività
    </button>
  </li>
  <li class="nav-item" role="presentation">
    <button
      class="nav-link"
      id="md-tab-setup"
      data-bs-toggle="pill"
      data-bs-target="#mdPaneSetup"
      type="button"
      role="tab"
      aria-controls="mdPaneSetup"
      aria-selected="false">
      <i class="bx bx-list-check"></i> Configura stampanti
    </button>
  </li>
  <li class="nav-item" role="presentation">
    <button
      class="nav-link"
      id="md-tab-tree"
      data-bs-toggle="pill"
      data-bs-target="#mdPaneTree"
      type="button"
      role="tab"
      aria-controls="mdPaneTree"
      aria-selected="false">
      <i class="bx bx-git-branch"></i> Diagramma ad albero
    </button>
  </li>
</ul>

<div class="tab-content" id="mdViewTabContent">
  <div
    class="tab-pane fade show active"
    id="mdPaneSimple"
    role="tabpanel"
    aria-labelledby="md-tab-simple"
    tabindex="0">
    @include('mappa_dispositivi.pills.index-simple')
  </div>
  <div
    class="tab-pane fade"
    id="mdPaneSetup"
    role="tabpanel"
    aria-labelledby="md-tab-setup"
    tabindex="0">
    @include('mappa_dispositivi.pills.index-setup-stampanti')
  </div>
  <div
    class="tab-pane fade"
    id="mdPaneTree"
    role="tabpanel"
    aria-labelledby="md-tab-tree"
    tabindex="0">
    @include('mappa_dispositivi.pills.index-tree')
  </div>
</div>
@endsection

@section('page-script')
@vite(['resources/assets/js/mappa-dispositivi-setup-stampanti.js'])
<script type="module">
  (function () {
    const storageKey = 'fest.mappa_dispositivi.active_tab';
    const tabsEl = document.getElementById('mdViewTabs');
    if (!tabsEl) return;

    const savedTarget = sessionStorage.getItem(storageKey);
    if (savedTarget) {
      const trigger = tabsEl.querySelector(`[data-bs-target="${savedTarget}"]`);
      if (trigger && typeof bootstrap !== 'undefined') {
        bootstrap.Tab.getOrCreateInstance(trigger).show();
      }
    }

    tabsEl.addEventListener('shown.bs.tab', (event) => {
      const target = event.target?.dataset?.bsTarget;
      if (target) {
        sessionStorage.setItem(storageKey, target);
      }
      if (target === '#mdPaneTree' && typeof window.mdInitTreeView === 'function') {
        window.mdInitTreeView();
      }
    });
  })();

  (function () {
    const dissociaUrl = @json(route('punto-vendita.dissocia-dispositivo'));
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;

    document.addEventListener('click', async (event) => {
      const btn = event.target.closest('.md-dissocia-pv');
      if (!btn || btn.disabled) return;

      const pvId = btn.dataset.pvId;
      if (!pvId) return;

      if (!confirm('Sei sicuro di voler dissociare il dispositivo?')) return;

      btn.disabled = true;

      try {
        const response = await fetch(dissociaUrl, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': csrfToken,
            'X-Requested-With': 'XMLHttpRequest',
          },
          body: new URLSearchParams({
            punto_vendita_id: pvId,
            _token: csrfToken,
          }),
        });

        const payload = await response.json().catch(() => ({}));

        if (!response.ok || payload.success === false) {
          throw new Error(payload.message || 'Dissociazione non riuscita');
        }

        const card = btn.closest('.md-device-card');
        const badge = card?.querySelector('.md-pv-binding-badge');
        if (badge) {
          badge.className = 'badge bg-label-secondary md-pv-binding-badge';
          badge.textContent = 'Libero';
        }
        btn.remove();

        if (typeof notyf !== 'undefined') {
          notyf.success(payload.message || 'Disassociazione completata');
        }
      } catch (error) {
        btn.disabled = false;
        if (typeof notyf !== 'undefined') {
          notyf.error(error.message || 'Si è verificato un errore');
        } else {
          alert(error.message || 'Si è verificato un errore');
        }
      }
    });
  })();
</script>
@endsection
