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

@extends('layouts/blankLayout')

@section('title', 'Cassa')

@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',
'resources/assets/vendor/scss/pages/front-page-payment.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('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");
}

html:has(.cassa-front-page),
html:has(.cassa-front-page) body {
  height: 100%;
  overflow: hidden;
}

.cassa-front-page{
  height: 100dvh;
  max-height: 100dvh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-width: none;
  padding: 0.5rem 0.75rem 0.35rem;
  box-sizing: border-box;
}
.cassa-front-page > .row.cassa-main-row{
  flex: 1 1 0;
}
.cassa-title{
  flex-shrink: 0;
  margin-bottom: 0.35rem;
}
.cassa-front-page > .alert{
  flex-shrink: 0;
  margin-bottom: 0.35rem;
}
.cassa-main-row{
  flex: 1 1 auto;
  min-height: 0;
  height: auto;
  display: flex;
  flex-wrap: wrap;
  align-content: stretch;
  align-items: stretch;
  --bs-gutter-y: 0.5rem;
  --bs-gutter-x: 0.75rem;
  margin-top: 0 !important;
  overflow: hidden;
}
.cassa-main-row > [class*='col-']{
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 100%;
  min-height: 0;
  overflow: hidden;
}
.cassa-cart-card{
  height: 100%;
  min-height: 0;
  max-height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.cassa-cart-header{
  flex-shrink: 0;
}
.cassa-cart-riepilogo{
  flex-shrink: 0;
  min-height: 0;
}
.cassa-cart-card .carrello-container:not(.cassa-cart-scroll){
  flex-shrink: 0;
}
.cassa-cart-card .carrello-container .mb-6{
  margin-bottom: 0 !important;
}
.cassa-cart-card .card-widget-separator .card-body{
  padding: 0.55rem 0.75rem;
}
.cassa-cart-card .card-widget-separator .pb-4{
  padding-bottom: 0.25rem !important;
}
.cassa-cart-scroll{
  flex: 1 1 auto;
  min-height: 6rem;
  overflow-y: auto !important;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
  padding-right: 0.15rem;
  scrollbar-width: thin;
}
.cassa-cart-scroll .dataTables_wrapper{
  width: 100%;
}
.cassa-cart-scroll table.dataTable{
  margin-bottom: 0;
}
.cassa-cart-scroll .dataTables_filter{
  margin-bottom: 0.35rem;
}
.cassa-cart-scroll .dataTables_info{
  padding-top: 0.35rem;
}
/* Riga carrello — bozza v1: stepper | contenuto | prezzo */
.carrello-item {
  padding: 0.75rem 0.25rem;
  touch-action: manipulation;
}
.carrello-item-nome {
  font-size: 1rem;
  line-height: 1.3;
}
.carrello-item-prezzo {
  font-size: 1.05rem;
  color: var(--bs-primary);
}
.carrello-item-nota-text {
  font-size: 0.85rem;
  color: var(--bs-secondary-color);
  text-decoration: none;
}
.carrello-item-nota-text--present {
  color: var(--bs-warning-text-emphasis, var(--bs-warning));
  background: rgba(var(--bs-warning-rgb), 0.1);
  border-left: 3px solid var(--bs-warning);
  border-radius: 0 0.25rem 0.25rem 0;
  padding: 0.25rem 0.4rem 0.25rem 0.5rem !important;
  margin-left: 0;
}
.carrello-item-nota-text:hover,
.carrello-item-nota-text:focus-visible {
  color: var(--bs-warning);
  /* text-decoration: underline; */
}
.carrello-item-nota-text--present:hover,
.carrello-item-nota-text--present:focus-visible {
  background: rgba(var(--bs-warning-rgb), 0.16);
}

/*Varianti piatto*/
.carrello-item-variante-text {
  font-size: 0.85rem;
  color: var(--bs-success-text-emphasis, var(--bs-success));
  text-decoration: none;
}
.carrello-item-variante-text--present {
  color: var(--bs-success-text-emphasis, var(--bs-success));
  background: rgba(var(--bs-success-rgb), 0.1);
  border-left: 3px solid var(--bs-success);
  border-radius: 0 0.25rem 0.25rem 0;
  padding: 0.25rem 0.4rem 0.25rem 0.5rem !important;
  margin-left: 0;
}
.carrello-item-variante-text:hover,
.carrello-item-variante-text:focus-visible {
  color: var(--bs-success);
  /* text-decoration: underline; */
}
.carrello-item-variante-text--present:hover,
.carrello-item-variante-text--present:focus-visible {
  background: rgba(var(--bs-success-rgb), 0.16);
}

.carrello-item-stepper-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 40px;
  min-width: 36px;
  min-height: 40px;
  padding: 0;
  font-size: 1.2rem;
  line-height: 1;
}
.carrello-item-stepper-qty {
  min-width: 2.5rem;
  height: 40px;
  font-size: 1.2rem;
  font-weight: 800;
  font-variant-numeric: tabular-nums;
  color: var(--bs-primary);
}
.carrello-item-action-btn {
  font-size: 0.8rem;
}
.carrello-item-actions:empty {
  display: none !important;
}
.carrello-item-delete {
  min-width: 44px;
  min-height: 44px;
  font-size: 1.15rem;
  line-height: 1;
  text-decoration: none;
  gap: 0.1rem;
}
.carrello-item-delete-label {
  font-size: 0.65rem;
  font-weight: 600;
  line-height: 1;
  text-transform: uppercase;
  letter-spacing: 0.02em;
}
.carrello-item-delete:hover,
.carrello-item-delete:focus-visible {
  opacity: 0.85;
  text-decoration: none;
}
.carrello-item-allergeni-hint {
  line-height: 1;
  text-decoration: none;
}
.carrello-item-stepper-btn:active,
.carrello-item-delete:active,
.carrello-item-action-btn:active,
.carrello-item-nota-text:active,
.carrello-item-variante-text:active {
  transform: scale(0.97);
}
.cassa-cart-scroll table.dataTable tbody td {
  padding-top: 0;
  padding-bottom: 0;
  vertical-align: top;
}
.cassa-footer{
  flex-shrink: 0;
  margin-top: 0.25rem !important;
  padding-top: 0.15rem;
  line-height: 1.2;
}
@media (max-width: 1199.98px){
  .cassa-main-row{
    flex-direction: column;
  }
  .cassa-main-row > [class*='col-']{
    flex: 1 1 0;
    min-height: 0;
    max-height: none;
  }
}
/* Base: icona + testo in fila */
.btn-expand-hover {
  display: inline-flex;
  align-items: center;
  gap: 0;
  overflow: hidden;
  white-space: nowrap;
  transition: padding 0.2s ease;
}

/* Testo nascosto di default (tutte le dimensioni) */
.btn-expand-hover .btn-expand-label {
  display: inline-block;
  max-width: 0;
  opacity: 0;
  overflow: hidden;
  transition: max-width 0.25s ease, opacity 0.2s ease, margin-left 0.25s ease;
  margin-left: 0;
}

/* Hover/focus: espande e mostra il testo */
.btn-expand-hover:hover .btn-expand-label,
.btn-expand-hover:focus-visible .btn-expand-label {
  max-width: 6rem;
  opacity: 1;
  margin-left: 0.35rem;
}
</style>

<div class="container-fluid cassa-front-page px-2 px-md-3 px-xl-3">
  <div class="d-flex flex-column cassa-title">

  <div class="row">

    
    <div class="col-8">
      <h4 class="mb-1">
        <i class="bx bx-store"></i>
        <span class="text-muted">{{ \App\Models\Attivita::find(session()->get('attivita_attuale'))->nome ?? 'Attività ND' }} - </span>
        <span class="text-primary">
          {{ $punto_vendita->nome ?? 'Punto di vendita ND' }}
        </span>
        <span class="text-muted fs-6 fw-normal">[Cassa]</span>
      </h4>
    </div>    
    
    <div class="col-4 d-flex align-items-center justify-content-end">
      <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary d-flex align-items-center" type="button" id="transactionID" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <i class="bx bx-menu fs-5"></i>
        </button>
        <div class="dropdown-menu dropdown-menu-end" aria-labelledby="transactionID">
          @if(Auth::guard('operatore')->check())
            <a class="dropdown-item" href="{{ route('operatore.dashDispositivi') }}">
              <i class="bx bx-category me-2"></i>Dashboard
            </a>
          @elseif(Auth::guard('web')->check())
            <a class="dropdown-item" href="{{ route('dashboard') }}">
              <i class="bx bx-category me-2"></i>Dashboard
            </a>
          @endif
          @if(Auth::guard('web')->check())
            <a class="dropdown-item" href="{{ route('profile.show') }}">
              <i class="bx bx-user-circle me-2"></i>{{ Auth::user()->fullName() }}
            </a>
          @endif
          @if($punto_vendita->binding_token)
            <span class="dropdown-item-text text-success">
              <i class="bx bx-link me-2"></i>Linker attivo
            </span>
          @endif
          <a class="dropdown-item" href="{{ route('punto-vendita.show', ['punto_vendita_id' => $punto_vendita->id , 'vista' => 'catalogo']) }}">
            <i class="bx bx-list-ul me-2"></i>Vista catalogo
          </a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="javascript:void(0);" onclick="showInfoPuntoVendita()">
            <i class="bx bx-info-circle me-2"></i>Informazioni punto vendita
          </a>
          <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="dissociaDispositivo()">
            <i class="bx bx-unlink me-2"></i>Dissocia dispositivo
          </a>
        </div>
      </div>

      <a href="{{ route('punto-vendita.show', ['punto_vendita_id' => $punto_vendita->id , 'vista' => 'catalogo']) }}" class=" d-none ms-2 px-3 py-1 alert text-bg-primary"> <!-- btn btn-primary -->
        <i class="bx bx-list-ul mx-1"></i>
        vista catalogo
      </a>
      <!-- <span class="badge badge-info">{{ $punto_vendita->binding_token }}</span> -->
    </div>
    
  </div>
</div>

  @include('_partials.status', ['success' => session('success'), 'error' => session('error')])

  <div class="row g-2 justify-content-center mt-0 cassa-main-row flex-grow-1 min-h-0">
    <div class="col-12 col-xl-8 d-flex flex-column min-h-0">
      @include('punto_vendita.cassa._partials.menu_cucine', ['cucine' => $cucine, 'punto_vendita' => $punto_vendita])
    </div>


    <div class="col-12 col-xl-4 d-flex flex-column min-h-0 flex-grow-1">
      <div class="card border shadow-sm w-100 h-100 min-h-0 cassa-cart-card">
        <div class=" text-center p-2 cassa-cart-header d-flex align-items-center justify-content-between alert alert-primary m-1" style="height:8%;">
          
        <div class="d-flex align-items-center justify-content-center gap-2"><i class="bx bx-cart fs-4 text-muted"></i><span class="text-primary fs-large fw-bold">#{{ $ordine->id }}</span></div>

        <div class=""> <!-- col-sm-3 col-md-3 col-lg-3 -->
              
                  <h4 class="mb-0 text-primary fw-bold" id="totale_carrello">
                    @if($ordine->totale > 0)
                     € {{ number_format($ordine->totale, 2, ',', '.') }}
                    @else
                    € {{ number_format($ordine->righe_ordine->sum('prezzo'), 2, ',', ',') }}
                    @endif

                  </h4>
                  <!-- <small class="mb-0 text-primary">Totale</small> -->
              
            </div>
          <!-- <h6 class="mt-2 mb-0">Carrello ()</h6> -->
          <!-- <div class="dropdown">
            <button class="btn text-muted p-0" type="button" id="transactionID" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              <i class="bx bx-dots-vertical-rounded bx-lg text-primary fs-4"></i>
            </button>
            <div class="dropdown-menu dropdown-menu-end" aria-labelledby="transactionID">
              <a class="dropdown-item" href="javascript:void(0);" onclick="showInfoPuntoVendita()">Informazioni punto vendita</a>
              <a class="dropdown-item" href="javascript:void(0);" onclick="stampaRiepilogo()">Stampa riepilogo</a>
              <a class="dropdown-item" href="javascript:void(0);" onclick="dissociaDispositivo()">Dissocia dispositivo</a>
              <a class="dropdown-item" href="javascript:void(0);" onclick="chiudiPuntoVendita(alert('Chiudi {{ $punto_vendita->tipo}}'))">Chiudi {{ $punto_vendita->tipo}}</a>
            </div>
          </div> -->
        </div>
        <div class="carrello-container card-body p-0 text-start cassa-cart-riepilogo">
          @include('punto_vendita.cassa._partials.carrello.riepilogo')
        </div>
        <div class="card-body pt-0 pb-2 text-start cassa-cart-scroll">
          {{ $dataTable_rigaordine->table(['class' => 'table-borderless table']) }}
          <!-- @foreach($ordine->righe_ordine as $riga_ordine)
            @include('punto_vendita.cassa._partials.carrello.righe_ordine' , ['riga_ordine' => $riga_ordine])
          @endforeach -->
        </div>
      </div>
    </div>
  </div>

  <div class="footer text-center cassa-footer">
    <span class="text-muted fs-6 fw-normal">
      Stampa su:
      {{ $punto_vendita->stampante_dispositivo()->nome?? 'ND' }}
      di ({{ $punto_vendita->stampante_dispositivo()->endpoint->label ?? 'ND' }})
    </span>
  </div>
</div>


<!-- Modal basic -->
<div class="modal fade" id="basicModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel1"></h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  
                </div>
                <div class="modal-footer">

              </div>
              </div>
            </div>
          </div>


@endsection

@section('page-script')


<script>

    
  document.querySelectorAll('.cassa-piatto-card').forEach(function (card) {
    card.addEventListener('click', function () {
      document.dispatchEvent(new CustomEvent('cassa-piatto-tap', {
        bubbles: true,
        detail: {
          piattoId: card.getAttribute('data-piatto-id'),
          nome: card.getAttribute('data-piatto-nome'),
          prezzo: card.getAttribute('data-piatto-prezzo'),
          cucinaId: card.getAttribute('data-cucina-id')
        }
      }));
    });
    card.addEventListener('keydown', function (e) {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        card.click();
      }
    });
  });


  function dissociaDispositivo() {
    $.ajax({
      url: "{{ route('punto-vendita.dissocia-dispositivo', ['punto_vendita_id' => $punto_vendita->id]) }}",
      type: "POST",
      data: {
        punto_vendita_id: "{{ $punto_vendita->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.href = "{{ route('punto-vendita.index') }}";
      },
      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);
      }
    });
  }


  
let nfcAbortController = null;

function stopNfcScan() {
  if (nfcAbortController) {
    try { nfcAbortController.abort(); } catch (e) {}
    nfcAbortController = null;
  }
}

function scanningNfcRequest() {
  const $status = $('#segrestaWalletAlertToScan');
  const $submit = $('button[type="submit"]');
  const $tag = $('#tag_id');

  stopNfcScan();
  $tag.val('');
  $submit.prop('disabled', true);

  if (!('NDEFReader' in window)) {
    $status
      .show()
      .removeClass('alert-warning alert-success')
      .addClass('alert-danger')
      .text('NFC non supportato su questo dispositivo/browser.');
      ///
    $status
      .show()
      .removeClass('alert-warning alert-success')
      .addClass('alert-danger')
      .text('NFC non supportato da questo dispositivo/browser. Inserisci manualmente il codice del braccialetto.');

    // Prompt manuale tramite prompt JS
    const manualTag = prompt('NFC non disponibile. Inserisci manualmente il codice del braccialetto/tag per pagare con Segresta Wallet:');
    if (manualTag && manualTag.trim() !== '') {
      $tag.val(manualTag.trim());

      var chiEResponse = chiE(manualTag);
      $status
        .removeClass('alert-danger alert-warning')
        .addClass('alert-success')
        .text('Codice braccialetto inserito manualmente: ' + manualTag + '. Puoi confermare il pagamento.\n' + chiEResponse);
      $submit.prop('disabled', false);
    } else {
      $status
        .removeClass('alert-success alert-warning')
        .addClass('alert-danger')
        .text('Inserimento del codice del braccialetto annullato o non valido.');
      $submit.prop('disabled', true);
    }
    /////
    return;
  }

  nfcAbortController = new AbortController();
  const reader = new NDEFReader();

  reader.scan({ signal: nfcAbortController.signal })
    .then(() => {
      $status
        .show()
        .removeClass('alert-danger alert-success')
        .addClass('alert-warning')
        .text('Lettore NFC attivo: avvicina il braccialetto.');

      reader.onreading = (event) => {
        const tagId = event.serialNumber || '';

        if (!tagId) {
          $status
            .removeClass('alert-warning alert-success')
            .addClass('alert-danger')
            .text('Tag letto ma seriale non disponibile. Riprova.');
          $submit.prop('disabled', true);
          return;
        }

        $tag.val(tagId);
        $status
          .removeClass('alert-warning alert-danger')
          .addClass('alert-success')
          .text('Braccialetto letto: ' + tagId + '. Puoi confermare il pagamento.');
        $submit.prop('disabled', false);

        // opzionale: una lettura basta
        stopNfcScan();
      };

      reader.onerror = () => {
        $status
          .removeClass('alert-warning alert-success')
          .addClass('alert-danger')
          .text('Errore durante la lettura NFC. Riprova.');
        $submit.prop('disabled', true);
      };
    })
    .catch((err) => {
      if (err?.name === 'AbortError') return;
      $status
        .show()
        .removeClass('alert-warning alert-success')
        .addClass('alert-danger')
        .text('Impossibile avviare NFC: ' + (err?.message || 'errore sconosciuto'));
      $submit.prop('disabled', true);
    });
}
</script>

@include('punto_vendita.cassa._partials.scripts')

@endsection
