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

@extends('layouts/layoutMaster')

@section('title', 'Punto Operatore')

@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"> 
    <i class="bx bx-user"></i> Punti Operatore</h4>
</div>
@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");
} */
</style>

@include('_partials.status')

<div class="row justify-content-center">
  <div class="col-12 mb-4 mt-2">
    <div class="card">
      <div class="card-body">
        <h5 class="card-title">Informazioni punto operatore</h5>
        <div class="row">
          <div class="col-md-4 mb-2">
            <p class="mb-0"><strong>Nome:</strong> {{ $dispositivo->nome }}</p>
          </div>
          <div class="col-md-4 mb-2">
            <p class="mb-0"><strong>Tipo:</strong> {{ $dispositivo->tipo }}</p>
          </div>
          <div class="col-md-4 mb-2">
            <p class="mb-0"><strong>ID dispositivo:</strong> {{ $dispositivo->id }}</p>
          </div>
          <div class="col-md-4 mb-2">
            <p class="mb-0"><strong>Cucina:</strong> {{ $dispositivo->cucina?->nome ?? 'Non assegnata' }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row mb-3">
  <div class="col-md-4 col-lg-3">
    <label for="filtro-range-temporale" class="form-label mb-1">Finestra temporale</label>
    <select id="filtro-range-temporale" class="form-select form-select-sm">
      <option value="1h" selected>Ultima ora</option>
      <option value="3h">Ultime 3 ore</option>
      <option value="today">Oggi</option>
    </select>
  </div>
</div>

<div class="row">
  <div class="col-lg-6 mb-4">
    <div class="card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
          <i class="bx bx-bell me-1 text-primary"></i>
          Piatti da chiamare
        </h5>
        <span class="badge bg-label-primary" id="badge-da-chiamare">0</span>
      </div>
      <div class="card-body">
        <p class="text-muted mb-3">
          Seleziona una riga ordine pronta e premi "Chiama".
        </p>
        <div id="lista-da-chiamare" class="d-grid gap-2 overflow-y-auto"></div>
      </div>
    </div>
  </div>

  <div class="col-lg-6 mb-4">
    <div class="card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
          <i class="bx bx-check-circle me-1 text-success"></i>
          Piatti chiamati
        </h5>
        <span class="badge bg-label-success" id="badge-chiamati">0</span>
      </div>
      <div class="card-body">
        <p class="text-muted mb-3">
          Quando il cliente ritira, premi "Ritirato".
        </p>
        <div id="lista-chiamati" class="d-grid gap-2 overflow-y-auto"></div>
      </div>
    </div>
  </div>
</div>

@endsection

@section('page-script')


<script>
  const dispositivoId = @json($dispositivo->id);
  const attivitaId = @json(session('attivita_attuale'));
  const csrfToken = @json(csrf_token());
  const haCucinaAssegnata = @json((bool) $dispositivo->cucina_id);
  let filtroRange = localStorage.getItem('punto_operatore_range_temporale') || '1h';

  let righeDaChiamare = [];
  let righeChiamate = [];

  function renderRighe() {
    renderListaDaChiamare();
    renderListaChiamate();
  }

  function renderListaDaChiamare() {
    const container = $('#lista-da-chiamare');
    $('#badge-da-chiamare').text(righeDaChiamare.length);
    container.empty();

    if (!haCucinaAssegnata) {
      container.append('<div class="alert alert-warning mb-0">Assegna una cucina al punto operatore per visualizzare le righe ordine.</div>');
      return;
    }

    if (righeDaChiamare.length === 0) {
      container.append('<div class="alert alert-secondary mb-0">Nessuna riga ordine da chiamare.</div>');
      return;
    }

    righeDaChiamare.forEach((riga) => {
      container.append(`
        <div class="border rounded p-3">
          <div class="row align-items-center gx-2">
            <!-- Colonna 1: ID ordine -->
            <div class="col-auto fw-semibold text-nowrap" style="min-width: 90px;">
             <span class="text-muted text-small d-none">Ordine</span> <span class="text-secondary fs-4">#${riga.ordine_id}</span>
            </div>
            <!-- Colonna 2: Quantità x Piatto (colonna più larga) -->
            <div class="col flex-grow-1">
              <span class="fs-large text-primary">${riga.quantita} x ${riga.piatto}</span>
              <div>
                <small class="text-muted">Riga #${riga.id} - stato: ${riga.stato}</small>
              </div>
            </div>
            <!-- Colonna 3: Bottone Chiama -->
            <div class="col-auto">
              <button type="button" class="btn btn-sm btn-primary" onclick="chiamaRiga(${riga.id})">
                Chiama
              </button>
            </div>
          </div>
        </div>
   
      `);
    });
  }

  function renderListaChiamate() {
    const container = $('#lista-chiamati');
    $('#badge-chiamati').text(righeChiamate.length);
    container.empty();

    if (!haCucinaAssegnata) {
      container.append('<div class="alert alert-warning mb-0">Assegna una cucina al punto operatore per visualizzare le righe ordine.</div>');
      return;
    }

    if (righeChiamate.length === 0) {
      container.append('<div class="alert alert-secondary mb-0">Nessuna riga ordine chiamata.</div>');
      return;
    }

    righeChiamate.forEach((riga) => {
      container.append(`
        <div class="border rounded p-3">
          <div class="row align-items-center gx-2">
            <!-- Colonna 1: ID ordine -->
            <div class="col-auto fw-semibold text-nowrap" style="min-width: 90px;">
              <span class="text-muted text-small d-none">Ordine</span> <span class="text-secondary fs-4">#${riga.ordine_id}</span>
            </div>
            <!-- Colonna 2: Quantità x Piatto (colonna più larga) -->
            <div class="col flex-grow-1">
              <span class="fs-large text-primary">${riga.quantita} x ${riga.piatto}</span>
              <div>
                <small class="text-muted">Riga #${riga.id} - stato: ${riga.stato}</small>
              </div>
            </div>
            <!-- Colonna 3: Bottone Ritirato -->
            <div class="col-auto">
              <button type="button" class="btn btn-sm btn-success" onclick="ritiraRiga(${riga.id})">
                Ritirato
              </button>
            </div>
          </div>
        </div>
   
      `);
    });
  }

  function chiamaRiga(rigaOrdineId) {
    $.ajax({
      type: 'POST',
      url: "{{ route('riga-ordine.chiamata') }}",
      dataType: 'json',
      data: {
        riga_ordine_id: rigaOrdineId,
        dispositivo_id: dispositivoId,
        attivita_id: attivitaId,
        _token: csrfToken,
      },
      success: function() {
        loadRighe();
      },
      error: function(xhr) {
        alert(xhr?.responseJSON?.message || 'Errore durante la chiamata della riga ordine.');
      },
    });
  }

  function ritiraRiga(rigaOrdineId) {
    $.ajax({
      type: 'POST',
      url: "{{ route('riga-ordine.ritiro') }}",
      dataType: 'json',
      data: {
        riga_ordine_id: rigaOrdineId,
        dispositivo_id: dispositivoId,
        attivita_id: attivitaId,
        _token: csrfToken,
      },
      success: function() {
        loadRighe();
      },
      error: function(xhr) {
        alert(xhr?.responseJSON?.message || 'Errore durante il ritiro della riga ordine.');
      },
    });
  }

  function loadRigheDaChiamare() {
    return $.ajax({
      type: 'GET',
      url: "{{ route('riga-ordine.lista-da-chiamare') }}",
      dataType: 'json',
      data: {
        dispositivo_id: dispositivoId,
        attivita_id: attivitaId,
        range: filtroRange,
      },
      success: function(response) {
        righeDaChiamare = response?.data || [];
      },
      error: function() {
        righeDaChiamare = [];
      },
    });
  }

  function loadRigheChiamate() {
    return $.ajax({
      type: 'GET',
      url: "{{ route('riga-ordine.lista-chiamate') }}",
      dataType: 'json',
      data: {
        dispositivo_id: dispositivoId,
        attivita_id: attivitaId,
        range: filtroRange,
      },
      success: function(response) {
        righeChiamate = response?.data || [];
      },
      error: function() {
        righeChiamate = [];
      },
    });
  }

  function loadRighe() {
    $.when(loadRigheDaChiamare(), loadRigheChiamate()).always(function() {
      renderRighe();
    });
  }

  function initFiltroRange() {
    const $select = $('#filtro-range-temporale');
    if ($select.find(`option[value="${filtroRange}"]`).length === 0) {
      filtroRange = '1h';
    }
    $select.val(filtroRange);
    $select.on('change', function() {
      filtroRange = $(this).val() || '1h';
      localStorage.setItem('punto_operatore_range_temporale', filtroRange);
      loadRighe();
    });
  }

document.addEventListener('DOMContentLoaded', function() {
    initFiltroRange();
    renderRighe();
    if (haCucinaAssegnata) {
      loadRighe();
      setInterval(loadRighe, 5000);
    }
  });

</script>
@endsection
