@php
use Illuminate\Support\Facades\Auth;
$configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Bilancio servizio')

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

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/apex-charts/apexcharts.js'
])
@endsection

@section('pageTitle')
<div class="d-flex flex-wrap justify-content-between align-items-start gap-2">
  <div class="d-flex flex-column">
    <h4 class="mb-1">
      <i class="bx bx-chart"></i> Bilancio servizio
      <span class="text-muted fs-6 fw-normal">· {{ $attivita?->nome ?? 'Attività' }}</span>
    </h4>
    <small class="text-muted">{{ $periodoLabel ?? ('Servizio in corso · ' . now()->format('d/m/Y H:i')) }}</small>
  </div>
</div>
@endsection

@section('content')
<style>
  .servizio-kpi-value {
    font-size: 1.75rem;
    font-weight: 700;
    line-height: 1.2;
  }

  .servizio-kpi-label {
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: var(--bs-secondary-color);
  }

  .servizio-metodo-row:last-child {
    border-bottom: 0 !important;
  }
</style>

@include('_partials.status')

<div class="card mt-1 mb-0 border-start border-3 border-info">
  <div class="card-body py-3 d-flex flex-wrap align-items-center gap-3">
    <div class="avatar avatar-sm">
      <span class="avatar-initial rounded bg-label-info">
        <i class="bx bx-time-five"></i>
      </span>
    </div>
    <div>
      <div class="fw-semibold">Servizio in corso</div>
      <div class="text-muted small">
        @if(!empty($ultimaChiusuraAt))
          Dal <strong>{{ $ultimaChiusuraAt->format('d/m/Y H:i') }}</strong>
          <!-- al <strong>{{ ($periodoEnd ?? now())->format('d/m/Y H:i') }}</strong> -->
          <small class="d-block mt-1">(ultima chiusura registrata)</small>
        @else
          Dal <strong>{{ ($periodoStart ?? now()->startOfDay())->format('d/m/Y H:i') }}</strong>
          <!-- al <strong>{{ ($periodoEnd ?? now())->format('d/m/Y H:i') }}</strong> -->
          <span class="d-block mt-1">Nessuna chiusura precedente: conteggio dall'inizio giornata.</span>
        @endif
      </div>
    </div>
  </div>
</div>

{{-- KPI principali --}}
<div class="row g-3 mt-1">
  <div class="col-md-4">
    <div class="card h-100 border-start border-4 border-primary">
      <div class="card-body">
        <div class="servizio-kpi-label mb-1">Incasso</div>
        <div class="servizio-kpi-value text-primary">
          € {{ number_format((float) ($totaleIncassoOggi ?? 0), 2, ',', '.') }}
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-body">
        <div class="servizio-kpi-label mb-1">Transazioni</div>
        <div class="servizio-kpi-value">
          {{ number_format((int) ($totaleTransazioniOggi ?? 0), 0, ',', '.') }}
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-body">
        <div class="servizio-kpi-label mb-1">Piatti ordinati</div>
        <div class="servizio-kpi-value">
          {{ number_format((int) ($totPiattiOrdinati ?? 0), 0, ',', '.') }}
        </div>
      </div>
    </div>
  </div>
</div>

{{-- Pagamenti per metodo --}}
<div class="card mt-4">
  <div class="card-header">
    <h5 class="mb-0">Pagamenti per metodo</h5>
  </div>
  <div class="card-body p-0">
    @forelse(($paymentSummary ?? collect()) as $row)
      <div class="d-flex justify-content-between align-items-center px-4 py-3 border-bottom servizio-metodo-row">
        <div>
          <div class="fw-semibold">{{ $row['metodo'] }}</div>
          <small class="text-muted">
            {{ number_format((int) $row['count'], 0, ',', '.') }}
            {{ (int) $row['count'] === 1 ? 'transazione' : 'transazioni' }}
          </small>
        </div>
        <div class="fs-5 fw-semibold">
          € {{ number_format((float) $row['totale'], 2, ',', '.') }}
        </div>
      </div>
    @empty
      <div class="p-4 text-muted">Nessun pagamento registrato in questo periodo.</div>
    @endforelse
  </div>
</div>

{{-- Dettagli (secondo piano) --}}
<div class="card mt-4">
  <div class="card-header">
    <button
      class="btn btn-sm btn-label-primary"
      type="button"
      data-bs-toggle="collapse"
      data-bs-target="#servizioDettagli"
      aria-expanded="false"
      aria-controls="servizioDettagli"
    >
      <i class="bx bx-chevron-down me-1"></i> Mostra dettagli (cucine e andamento orario)
    </button>
    @if(Auth::user()->can('create-chiusura-servizio') && \App\Models\ChiusuraServizio::where('attivita_id', $attivita->id)->where('chiusura_at', '>=', now()->subHours(1))->count() == 0)
    <form
      id="form-chiudi-servizio"
      method="POST"
      action="{{ route('chiusura-servizio.chiudi-servizio') }}"
      class="btn btn-sm  d-inline-flex align-items-center"
    >
      @csrf
      <button type="button" class="btn btn-warning" id="btn-chiudi-servizio">
        <i class="bx bx-lock-alt me-1"></i> Chiudi servizio
      </button>
    </form>
  @endcan
  </div>
  <div class="collapse" id="servizioDettagli">
    <div class="card-body border-top">
      <ul class="nav nav-tabs mb-3" role="tablist">
        <li class="nav-item" role="presentation">
          <button class="nav-link active" type="button" data-bs-toggle="tab" data-bs-target="#servizio-tab-cucine" role="tab">
            Cucine e piatti
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" type="button" data-bs-toggle="tab" data-bs-target="#servizio-tab-heatmap" role="tab" id="servizio-tab-heatmap-btn">
            Andamento orario
          </button>
        </li>
      </ul>

      <div class="tab-content">
        <div class="tab-pane fade show active" id="servizio-tab-cucine" role="tabpanel">
          <div class="accordion" id="accordionCucineOggi">
            @forelse(($cucineRows ?? collect()) as $index => $cucina)
              @php
                $itemId = 'cucina-' . $index;
                $headingId = 'heading-' . $itemId;
                $collapseId = 'collapse-' . $itemId;
              @endphp
              <div class="accordion-item">
                <h2 class="accordion-header" id="{{ $headingId }}">
                  <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#{{ $collapseId }}"
                    aria-expanded="false"
                    aria-controls="{{ $collapseId }}"
                  >
                    <div class="w-100 d-flex flex-wrap justify-content-between align-items-center gap-2 pe-2">
                      <span class="fw-semibold">{{ $cucina['nome'] }}</span>
                      <span class="text-muted small">
                        {{ number_format((int) $cucina['tot_quantita'], 0, ',', '.') }} ord.
                        · € {{ number_format((float) $cucina['tot_importo'], 2, ',', '.') }}
                      </span>
                    </div>
                  </button>
                </h2>
                <div id="{{ $collapseId }}" class="accordion-collapse collapse" aria-labelledby="{{ $headingId }}" data-bs-parent="#accordionCucineOggi">
                  <div class="accordion-body p-0">
                    <div class="table-responsive">
                      <table class="table table-sm mb-0">
                        <thead>
                          <tr>
                            <th>Piatto</th>
                            <th class="text-end">Qtà</th>
                            <th class="text-end">Totale</th>
                          </tr>
                        </thead>
                        <tbody>
                          @foreach($cucina['piatti'] as $piatto)
                            <tr>
                              <td>{{ $piatto['nome'] }}</td>
                              <td class="text-end">{{ number_format((int) $piatto['quantita'], 0, ',', '.') }}</td>
                              <td class="text-end">€ {{ number_format((float) $piatto['totale'], 2, ',', '.') }}</td>
                            </tr>
                          @endforeach
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            @empty
              <div class="alert alert-warning mb-0">Nessuna cucina con ordinazioni in questo periodo.</div>
            @endforelse
          </div>
        </div>

        <div class="tab-pane fade" id="servizio-tab-heatmap" role="tabpanel">
          <p class="text-muted small mb-3">Ordinazioni per ora e cucina.</p>
          <div id="heatmap-incassi-oggi" style="min-height: 320px;"></div>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const chiudiBtn = document.getElementById('btn-chiudi-servizio');
    const chiudiForm = document.getElementById('form-chiudi-servizio');

    if (chiudiBtn && chiudiForm) {
      chiudiBtn.addEventListener('click', function () {
        Swal.fire({
          title: 'Chiudere il servizio?',
          html: [
            'Verrà registrata la chiusura del servizio corrente con uno <strong>snapshot</strong> dei totali',
            '(incasso, transazioni, pagamenti per metodo, cucine e piatti).',
            '<br><br>',
            'Il prossimo servizio partirà da questo momento.',
            '<br><br>',
            '<span class="text-muted">Le vendite non vengono bloccate: i nuovi ordini saranno conteggiati nel servizio successivo.</span>'
          ].join(' '),
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Sì, chiudi servizio',
          cancelButtonText: 'Annulla',
          customClass: {
            confirmButton: 'btn btn-warning me-2',
            cancelButton: 'btn btn-label-secondary'
          },
          buttonsStyling: false
        }).then(function (result) {
          if (result.isConfirmed) {
            chiudiForm.submit();
          }
        });
      });
    }

    if (typeof ApexCharts === 'undefined') {
      return;
    }

    const heatmapSeries = @json($heatmapSeries ?? []);
    const hourLabels = @json($heatmapHourLabels ?? []);
    let heatmapChart = null;

    function isDarkTheme() {
      const theme = document.documentElement.getAttribute('data-bs-theme');
      if (theme === 'dark') {
        return true;
      }
      if (theme === 'light') {
        return false;
      }
      return window.matchMedia('(prefers-color-scheme: dark)').matches;
    }

    function getThemeColors() {
      const css = getComputedStyle(document.documentElement);
      return {
        labelColor: (css.getPropertyValue('--bs-secondary-color') || '#6c757d').trim(),
        borderColor: (css.getPropertyValue('--bs-border-color') || '#e9ecef').trim(),
        emptyColor: (css.getPropertyValue('--bs-tertiary-bg') || css.getPropertyValue('--bs-border-color') || '#e9ecef').trim()
      };
    }

    function getHeatmapColorScale(dark, emptyColor) {
      if (dark) {
        return [
          { from: 0, to: 0, color: emptyColor, name: 'Nessuna ordinazione' },
          { from: 1, to: 5, color: '#434968', name: 'Basso' },
          { from: 6, to: 12, color: '#5a5fcf', name: 'Medio' },
          { from: 13, to: 20, color: '#696cff', name: 'Alto' },
          { from: 21, to: 99999, color: '#8592ff', name: 'Picco' }
        ];
      }

      return [
        { from: 0, to: 0, color: emptyColor, name: 'Nessuna ordinazione' },
        { from: 1, to: 5, color: '#dbeafe', name: 'Basso' },
        { from: 6, to: 12, color: '#93c5fd', name: 'Medio' },
        { from: 13, to: 20, color: '#60a5fa', name: 'Alto' },
        { from: 21, to: 99999, color: '#2563eb', name: 'Picco' }
      ];
    }

    function buildHeatmapOptions() {
      const dark = isDarkTheme();
      const colors = getThemeColors();

      return {
        chart: {
          type: 'heatmap',
          height: 320,
          toolbar: { show: false },
          foreColor: colors.labelColor
        },
        theme: {
          mode: dark ? 'dark' : 'light'
        },
        series: heatmapSeries,
        xaxis: {
          categories: hourLabels,
          labels: {
            style: { colors: colors.labelColor, fontSize: '11px' }
          },
          axisBorder: { show: false },
          axisTicks: { show: false }
        },
        yaxis: {
          labels: {
            style: { colors: colors.labelColor, fontSize: '12px' }
          }
        },
        dataLabels: {
          enabled: false
        },
        colors: ['#696cff'],
        plotOptions: {
          heatmap: {
            shadeIntensity: dark ? 0.35 : 0.55,
            radius: 4,
            colorScale: {
              ranges: getHeatmapColorScale(dark, colors.emptyColor)
            }
          }
        },
        legend: {
          position: 'bottom',
          labels: {
            colors: colors.labelColor
          }
        },
        grid: {
          borderColor: colors.borderColor,
          strokeDashArray: 4
        },
        tooltip: {
          theme: dark ? 'dark' : 'light',
          y: {
            formatter: function (val) {
              return Number(val || 0).toLocaleString('it-IT') + ' ordinazioni';
            }
          }
        }
      };
    }

    function destroyHeatmap() {
      if (heatmapChart) {
        heatmapChart.destroy();
        heatmapChart = null;
      }
    }

    function renderHeatmap() {
      const el = document.querySelector('#heatmap-incassi-oggi');
      if (!el) {
        return;
      }

      destroyHeatmap();
      heatmapChart = new ApexCharts(el, buildHeatmapOptions());
      heatmapChart.render();
    }

    function heatmapTabVisible() {
      return !!document.querySelector('#servizio-tab-heatmap.show.active');
    }

    const heatmapTabBtn = document.getElementById('servizio-tab-heatmap-btn');
    if (heatmapTabBtn) {
      heatmapTabBtn.addEventListener('shown.bs.tab', renderHeatmap);
    }

    const dettagli = document.getElementById('servizioDettagli');
    if (dettagli) {
      dettagli.addEventListener('shown.bs.collapse', function () {
        if (heatmapTabVisible()) {
          renderHeatmap();
        }
      });
    }

    const themeObserver = new MutationObserver(function () {
      if (heatmapChart && heatmapTabVisible()) {
        renderHeatmap();
      }
    });
    themeObserver.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['data-bs-theme']
    });
  });
</script>
@endsection
