@extends('layouts/layoutMaster')

@section('title', 'Report')

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

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

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1"><i class="bx bx-file"></i> Report</h4>
  <small class="text-muted">Panoramica operativa e vendite</small>
</div>
@endsection

@section('content')
@php
  $kpi = $kpi ?? [
    'ordini' => 0,
    'incasso' => 0,
    'ticket_medio' => 0,
    'coperti' => 0,
  ];
  $heatmapDayLabels = $heatmapDayLabels ?? ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'];
@endphp

@include('_partials.status')

<div class="row g-4 mb-4">
  <div class="col-12">
    <div class="card">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-4">
            <label for="range-report" class="form-label mb-1">Periodo</label>
            <input id="range-report" type="text" class="form-control" placeholder="Seleziona range date">
          </div>
          <div class="col-md-3">
            <label for="filtro-cucina" class="form-label mb-1">Cucina</label>
            <select id="filtro-cucina" class="form-select">
              <option value="all">Tutte</option>
              @foreach(($cucine ?? collect()) as $cucina)
                <option value="{{ $cucina->id }}" @selected((int)($selectedCucinaId ?? 0) === (int)$cucina->id)>
                  {{ $cucina->nome }}
                </option>
              @endforeach
            </select>
          </div>
          <div class="col-md-3">
            <label for="filtro-pagamento" class="form-label mb-1">Pagamento</label>
            <select id="filtro-pagamento" class="form-select">
              <option value="all" @selected(($selectedPagamento ?? 'all') === 'all')>Tutti</option>
              <option value="contanti" @selected(($selectedPagamento ?? 'all') === 'contanti')>Contanti</option>
              <option value="pos" @selected(($selectedPagamento ?? 'all') === 'pos')>POS</option>
              <option value="paypal" @selected(($selectedPagamento ?? 'all') === 'paypal')>PayPal</option>
            </select>
          </div>
          <div class="col-md-2 d-flex gap-2">
            <button type="button" id="btn-apply-range" class="btn btn-primary w-100">Applica</button>
            <button type="button" id="btn-reset-range" class="btn btn-outline-secondary w-100">Reset</button>
          </div>
        </div>

        <hr class="my-4">

        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
          <div class="d-flex flex-wrap gap-2">
          <button
            type="button"
            class="btn btn-primary report-switch-btn"
            data-report-target="report-sintesi-panel">
            Sintesi
          </button>
          <button
            type="button"
            class="btn btn-outline-primary report-switch-btn"
            data-report-target="report-movimenti-panel">
            <i class="bx bx-transfer-alt me-1"></i> Report Movimenti
          </button>
          <button
            type="button"
            class="btn btn-outline-primary report-switch-btn"
            data-report-target="report-incassi-panel">
            Report Incassi
          </button>
          <button type="button" class="btn btn-outline-primary">Report Ordini</button>
          <button
            type="button"
            class="btn btn-outline-primary report-switch-btn"
            data-report-target="report-cucine-panel">
            Report Cucine
          </button>
          </div>

          <a id="btn-download-report-pdf" href="#" class="btn btn-label-primary disabled" aria-disabled="true">
            <i class="bx bx-download me-1"></i> Download Report PDF
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="report-sintesi-panel" class="report-panel">
  <div class="row g-4 mb-4">
    <div class="col-sm-6 col-xl-3">
      <div class="card h-100">
        <div class="card-body">
          <span class="fw-medium text-muted">Ordini</span>
          <h3 class="mb-1 mt-2">{{ number_format($kpi['ordini'], 0, ',', '.') }}</h3>
          <small class="text-success"><i class="bx bx-up-arrow-alt"></i> +12,4% vs periodo precedente</small>
        </div>
      </div>
    </div>
    <div class="col-sm-6 col-xl-3">
      <div class="card h-100">
        <div class="card-body">
          <span class="fw-medium text-muted">Incasso Totale</span>
          <h3 class="mb-1 mt-2">EUR {{ number_format($kpi['incasso'], 2, ',', '.') }}</h3>
          <small class="text-success"><i class="bx bx-up-arrow-alt"></i> +8,1% vs periodo precedente</small>
        </div>
      </div>
    </div>
    <div class="col-sm-6 col-xl-3">
      <div class="card h-100">
        <div class="card-body">
          <span class="fw-medium text-muted">Ticket Medio</span>
          <h3 class="mb-1 mt-2">EUR {{ number_format($kpi['ticket_medio'], 2, ',', '.') }}</h3>
          <small class="text-danger"><i class="bx bx-down-arrow-alt"></i> -2,3% vs periodo precedente</small>
        </div>
      </div>
    </div>
    <div class="col-sm-6 col-xl-3">
      <div class="card h-100">
        <div class="card-body">
          <span class="fw-medium text-muted">Coperti</span>
          <h3 class="mb-1 mt-2">{{ number_format($kpi['coperti'], 0, ',', '.') }}</h3>
          <small class="text-success"><i class="bx bx-up-arrow-alt"></i> +5,8% vs periodo precedente</small>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-4">
    <div class="col-xl-8">
      <div class="card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
          <div>
            <h5 class="card-title mb-0">Andamento Incasso Giornaliero</h5>
            <small class="text-muted">Ultimi 7 giorni</small>
          </div>
        </div>
        <div class="card-body">
          <div id="report-incasso-chart" style="min-height: 320px;"></div>
        </div>
      </div>
    </div>

    <div class="col-xl-4">
      <div class="card h-100">
        <div class="card-header d-flex align-items-center justify-content-between">
          <h5 class="card-title mb-0">Ripartizione Pagamenti</h5>
          <span class="badge bg-label-primary">Periodo attivo</span>
        </div>
        <div class="card-body pt-4">
          <ul class="p-0 m-0">
            @forelse(($paymentBreakdownRows ?? collect()) as $index => $row)
              <li class="d-flex align-items-center {{ $loop->last ? '' : 'mb-4' }}">
                <div class="avatar flex-shrink-0 me-3">
                  <span class="avatar-initial rounded {{ $index % 3 === 0 ? 'bg-label-success' : ($index % 3 === 1 ? 'bg-label-primary' : 'bg-label-info') }}">
                    <i class="bx {{ $index % 3 === 0 ? 'bx-wallet' : ($index % 3 === 1 ? 'bx-credit-card-front' : 'bx-globe') }}"></i>
                  </span>
                </div>
                <div class="d-flex w-100 flex-wrap align-items-center justify-content-between gap-2">
                  <div class="me-2">
                    <small class="d-block">{{ $row['metodo'] }}</small>
                    <h6 class="fw-normal mb-0">{{ number_format($row['count'], 0, ',', '.') }} transazioni</h6>
                  </div>
                  <div class="user-progress d-flex align-items-center gap-2">
                    <h6 class="fw-normal mb-0">EUR {{ number_format((float) $row['importo'], 2, ',', '.') }}</h6>
                    <span class="text-muted">{{ number_format((float) $row['percent'], 1, ',', '.') }}%</span>
                  </div>
                </div>
              </li>
            @empty
              <li class="text-muted small">Nessun pagamento nel periodo selezionato.</li>
            @endforelse
          </ul>
        </div>
      </div>
    </div>

    <div class="col-lg-6 col-xl-4">
      <div class="card h-100">
        <div class="card-header d-flex align-items-start justify-content-between">
          <div>
            <h5 class="card-title m-0 me-2 mb-2">Heatmap Ordini</h5>
            <span class="badge bg-label-success me-1">+18,2%</span> <span>rispetto al periodo precedente</span>
          </div>
          <div class="btn-group">
            <button type="button" class="btn btn-sm btn-label-primary">Ultimi 7 giorni</button>
            <button type="button" class="btn btn-sm btn-label-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
              <span class="visually-hidden">Toggle Dropdown</span>
            </button>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="javascript:void(0);">Ultimi 7 giorni</a></li>
              <li><a class="dropdown-item" href="javascript:void(0);">Ultimi 14 giorni</a></li>
              <li><a class="dropdown-item" href="javascript:void(0);">Ultimo mese</a></li>
            </ul>
          </div>
        </div>
        <div class="card-body pb-0">
          <div id="report-heatmap-chart"></div>
        </div>
      </div>
    </div>

    <div class="col-lg-6 col-xl-8">
      <div class="card">
        <div class="card-header">
          <h5 class="card-title mb-0">Top Piatti</h5>
        </div>
        <div class="card-body">
          <div id="report-piatti-chart" style="min-height: 320px;"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-4 mt-1">
  <div class="col-12">
    <div id="report-movimenti-panel" class="report-panel d-none">
      @include('report._partials.movimenti', [
        'attivitaNome' => $attivitaNome ?? 'Attivita',
        'periodoLabel' => $periodoLabel ?? 'Periodo non specificato',
        'movimenti' => $movimenti ?? [],
        'totEntrate' => $totEntrate ?? 0,
        'totUscite' => $totUscite ?? 0,
        'saldo' => $saldo ?? 0,
      ])
    </div>

    <div id="report-incassi-panel" class="report-panel d-none">
      @include('report._partials.incassi', [
        'attivitaNome' => $attivitaNome ?? 'Attivita',
        'periodoLabel' => $periodoLabel ?? 'Periodo non specificato',
        'movimenti' => $movimenti ?? [],
        'totEntrate' => $totEntrate ?? 0,
        'totUscite' => $totUscite ?? 0,
        'saldo' => $saldo ?? 0,
      ])
    </div>

    <div id="report-cucine-panel" class="report-panel d-none">
      @include('report._partials.cucine', [
        'attivitaNome' => $attivitaNome ?? 'Attivita',
        'periodoLabel' => $periodoLabel ?? 'Periodo non specificato',
        'cucine' => $cucine ?? collect(),
        'cucineReportRows' => $cucineReportRows ?? [],
      ])
    </div>
  </div>
</div>
@endsection

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', function () {
    var rangeInput = document.getElementById('range-report');
    var cucinaInput = document.getElementById('filtro-cucina');
    var pagamentoInput = document.getElementById('filtro-pagamento');
    var applyRangeButton = document.getElementById('btn-apply-range');
    var resetRangeButton = document.getElementById('btn-reset-range');
    var downloadPdfButton = document.getElementById('btn-download-report-pdf');
    var reportSwitchButtons = Array.from(document.querySelectorAll('.report-switch-btn'));
    var reportPanels = Array.from(document.querySelectorAll('.report-panel'));
    var exportRoute = @json(route('report.export-pdf'));
    var reportTypeByPanel = {
      'report-movimenti-panel': 'movimenti',
      'report-incassi-panel': 'incassi',
      'report-cucine-panel': 'cucine'
    };

    function setActiveReport(targetId) {
      reportPanels.forEach(function (panel) {
        panel.classList.toggle('d-none', panel.id !== targetId);
      });

      reportSwitchButtons.forEach(function (button) {
        var isActive = button.getAttribute('data-report-target') === targetId;
        button.classList.toggle('btn-primary', isActive);
        button.classList.toggle('btn-outline-primary', !isActive);
      });

      if (downloadPdfButton) {
        var selectedType = reportTypeByPanel[targetId] || null;
        if (!selectedType) {
          downloadPdfButton.classList.add('disabled');
          downloadPdfButton.setAttribute('aria-disabled', 'true');
          downloadPdfButton.setAttribute('href', '#');
          return;
        }

        var currentUrl = new URL(window.location.href);
        var params = new URLSearchParams(currentUrl.search);
        params.set('type', selectedType);
        downloadPdfButton.classList.remove('disabled');
        downloadPdfButton.setAttribute('aria-disabled', 'false');
        downloadPdfButton.setAttribute('href', exportRoute + '?' + params.toString());
      }
    }

    reportSwitchButtons.forEach(function (button) {
      button.addEventListener('click', function () {
        var targetId = button.getAttribute('data-report-target');
        if (!targetId) return;
        setActiveReport(targetId);
      });
    });

    setActiveReport('report-sintesi-panel');

    if (typeof flatpickr !== 'undefined') {
      flatpickr(rangeInput, {
        mode: 'range',
        dateFormat: 'Y-m-d',
        defaultDate: [@json($rangeDateFrom ?? now()->startOfMonth()->format('Y-m-d')), @json($rangeDateTo ?? now()->format('Y-m-d'))]
      });
    }

    if (applyRangeButton && rangeInput) {
      applyRangeButton.addEventListener('click', function () {
        var rangeValue = (rangeInput.value || '').trim();
        var url = new URL(window.location.href);
        if (rangeValue.length > 0) {
          url.searchParams.set('range', rangeValue);
        } else {
          url.searchParams.delete('range');
        }
        if (cucinaInput && cucinaInput.value && cucinaInput.value !== 'all') {
          url.searchParams.set('cucina_id', cucinaInput.value);
        } else {
          url.searchParams.delete('cucina_id');
        }
        if (pagamentoInput && pagamentoInput.value && pagamentoInput.value !== 'all') {
          url.searchParams.set('pagamento', pagamentoInput.value);
        } else {
          url.searchParams.delete('pagamento');
        }
        window.location.href = url.toString();
      });
    }

    if (resetRangeButton) {
      resetRangeButton.addEventListener('click', function () {
        var url = new URL(window.location.href);
        url.searchParams.delete('range');
        url.searchParams.delete('cucina_id');
        url.searchParams.delete('pagamento');
        window.location.href = url.toString();
      });
    }

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

    var revenueCategories = @json($incassoChartLabels ?? []);
    var revenueSeries = @json($incassoChartSeries ?? []);
    var heatmapSeries = @json($heatmapSeries ?? []);
    var heatmapDayLabels = @json($heatmapDayLabels);
    var topPiattiLabels = @json($topPiattiLabels ?? []);
    var topPiattiSeries = @json($topPiattiSeries ?? []);

    var revenueConfig = {
      chart: {
        type: 'area',
        height: 320,
        toolbar: { show: false }
      },
      series: [
        { name: 'Incasso', data: revenueSeries }
      ],
      xaxis: {
        categories: revenueCategories
      },
      stroke: { curve: 'smooth', width: 3 },
      dataLabels: { enabled: false },
      colors: ['#696cff'],
      fill: {
        type: 'gradient',
        gradient: {
          shadeIntensity: 1,
          opacityFrom: 0.35,
          opacityTo: 0.08
        }
      },
      yaxis: {
        labels: {
          formatter: function (value) {
            return 'EUR ' + Number(value).toLocaleString('it-IT');
          }
        }
      },
      tooltip: {
        y: {
          formatter: function (value) {
            return 'EUR ' + Number(value).toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
          }
        }
      }
    };
    new ApexCharts(document.querySelector('#report-incasso-chart'), revenueConfig).render();

    var heatmapConfig = {
      chart: {
        height: 330,
        type: 'heatmap',
        toolbar: { show: false }
      },
      series: heatmapSeries,
      xaxis: {
        categories: heatmapDayLabels
      },
      yaxis: {
        reversed: true
      },
      dataLabels: {
        enabled: false
      },
      colors: ['#696cff'],
      plotOptions: {
        heatmap: {
          shadeIntensity: 0.6,
          radius: 4,
          colorScale: {
            ranges: [
              { from: 0, to: 5, color: '#e7e7ff', name: 'Basso' },
              { from: 6, to: 10, color: '#b6b8ff', name: 'Medio' },
              { from: 11, to: 15, color: '#8c8fff', name: 'Alto' },
              { from: 16, to: 25, color: '#696cff', name: 'Picco' }
            ]
          }
        }
      }
    };
    new ApexCharts(document.querySelector('#report-heatmap-chart'), heatmapConfig).render();

    var topDishesConfig = {
      chart: {
        type: 'bar',
        height: 320,
        toolbar: { show: false }
      },
      series: [
        { name: 'Porzioni', data: topPiattiSeries }
      ],
      xaxis: {
        categories: topPiattiLabels
      },
      plotOptions: {
        bar: {
          horizontal: true,
          borderRadius: 6
        }
      },
      colors: ['#ff9f43'],
      dataLabels: { enabled: false }
    };
    new ApexCharts(document.querySelector('#report-piatti-chart'), topDishesConfig).render();
  });
</script>
@endsection
