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

@extends('layouts/layoutMaster')

@section('title', 'Bilancio')

@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/apex-charts/apex-charts.scss',
'resources/assets/vendor/scss/pages/card-analytics.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/apex-charts/apexcharts.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 text-sm-small mt-md-4 mt-lg-4">
    <i class="bx bx-chart d-none d-md-inline-flex d-lg-inline-flex"></i> Bilancio annuale
  </h4>
  
    <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block d-lg-block">
            <ol class="breadcrumb breadcrumb-custom-icon">
      
              <li class="breadcrumb-item">
                <a href="#">Configurazioni</a>
                <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
              </li>
              <li class="breadcrumb-item active text-primary">
                <a href="{{ route('bilancio.index') }}">Bilancio annuale</a>
              </li>
            </ol>
          </nav>
</div>
@endsection

@section('content')
<style>
  div.upload button:first-child{
    display: none !important;
  }

  .bilancio-float-header {
    max-width: 1100px;
    margin: 0 auto 1rem auto;
    border-radius: 1rem;
  }

  .bilancio-float-header .nav-pills .nav-link {
    border-radius: .7rem;
    padding: .45rem .9rem;
  }
</style>
@php
  $andamentoMensile = collect($andamentoMensile ?? []);
  $costiRows = collect($costiRows ?? []);
  $ricaviRows = collect($ricaviRows ?? []);
  $chartLabels = $andamentoMensile->pluck('mese')->values()->all();
  $chartCostiSeries = $andamentoMensile->map(fn ($r) => round((float) ($r['costi'] ?? 0), 2))->values()->all();
  $chartRicaviSeries = $andamentoMensile->map(fn ($r) => round((float) ($r['ricavi'] ?? 0), 2))->values()->all();
  $chartSaldoSeries = $andamentoMensile->map(fn ($r) => round((float) ($r['saldo'] ?? 0), 2))->values()->all();
  $chartCategorieCostiLabels = $costiRows->pluck('voce')->values()->all();
  $chartCategorieCostiSeries = $costiRows->map(fn ($r) => round((float) ($r['totale'] ?? 0), 2))->values()->all();
  $chartCategorieCostiColors = $costiRows->map(function ($r) {
    $colore = trim((string) ($r['colore'] ?? ''));
    return $colore !== '' ? $colore : '#dc3545';
  })->values()->all();
  $chartCategorieRicaviLabels = $ricaviRows->pluck('voce')->values()->all();
  $chartCategorieRicaviSeries = $ricaviRows->map(fn ($r) => round((float) ($r['totale'] ?? 0), 2))->values()->all();
  $chartCategorieRicaviColors = $ricaviRows->map(function ($r) {
    $colore = trim((string) ($r['colore'] ?? ''));
    return $colore !== '' ? $colore : '#198754';
  })->values()->all();

  $categoriaPerformance = collect($categoriaPerformance ?? [])->take(10)->values();
  $piattiPerformance = collect($piattiPerformance ?? [])->take(10)->values();
  $cucinePerformance = collect($cucinePerformance ?? [])->take(10)->values();
  $pagamentiPerformance = collect($pagamentiPerformance ?? [])->take(10)->values();

  $statCategoriaLabels = $categoriaPerformance->pluck('categoria')->values()->all();
  $statCategoriaSaldo = $categoriaPerformance->map(fn($r) => round((float) ($r['saldo'] ?? 0), 2))->values()->all();

  $statPiattiLabels = $piattiPerformance->pluck('nome')->values()->all();
  $statPiattiTotali = $piattiPerformance->map(fn($r) => round((float) ($r['totale'] ?? 0), 2))->values()->all();

  $statCucineLabels = $cucinePerformance->pluck('nome')->values()->all();
  $statCucineTotali = $cucinePerformance->map(fn($r) => round((float) ($r['totale'] ?? 0), 2))->values()->all();

  $statPagamentiLabels = $pagamentiPerformance->pluck('metodo')->values()->all();
  $statPagamentiTotali = $pagamentiPerformance->map(fn($r) => round((float) ($r['totale'] ?? 0), 2))->values()->all();
  $affluenzaHeatmapSeries = collect($affluenzaHeatmapSeries ?? [])->values()->all();
  $affluenzaGiorniLabels = collect($affluenzaGiorniLabels ?? [])->values()->all();
  $affluenzaGiorniSeries = collect($affluenzaGiorniSeries ?? [])->values()->all();
@endphp

@if(session('status'))
<div class="alert alert-success">
  {{ session('status') }}
</div>
@endif

<div class="card shadow-sm border bilancio-float-header">
  <div class="card-body py-3">
    <div class="d-flex flex-wrap align-items-center justify-content-center gap-3">
      <div class="text-center text-md-start">
        <!-- <span class="text-muted small d-block">Attivita</span> -->
        <strong>{{ $attivita?->nome ?? 'N/D' }}</strong>
      </div>

      <form method="GET" action="{{ route('bilancio.index') }}" class="d-flex align-items-center gap-2">
        <label for="bilancio-anno" class="form-label mb-0 small text-muted">Anno</label>
        <select id="bilancio-anno" name="anno" class="form-select form-select-sm" style="min-width: 110px;">
          @foreach(($anniSelezionabili ?? collect()) as $anno)
            <option value="{{ $anno }}" {{ (int)($selectedYear ?? now()->year) === (int)$anno ? 'selected' : '' }}>
              {{ $anno }}
            </option>
          @endforeach
        </select>
        <button type="submit" class="btn btn-sm btn-primary">Applica</button>
      </form>

      <ul class="nav nav-pills gap-1" role="tablist">
        <li class="nav-item" role="presentation">
          <button type="button" class="nav-link active" role="tab" data-bs-toggle="tab" data-bs-target="#bilancio-tab-sintesi" aria-controls="bilancio-tab-sintesi" aria-selected="true">
            <i class="bx bx-pie-chart-alt me-1"></i>Sintesi
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#bilancio-tab-ricavi" aria-controls="bilancio-tab-ricavi" aria-selected="false">
            <i class="bx bx-trending-up me-1"></i>Ricavi
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#bilancio-tab-costi" aria-controls="bilancio-tab-costi" aria-selected="false">
            <i class="bx bx-trending-down me-1"></i>Costi
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button type="button" class="nav-link" role="tab" data-bs-toggle="tab" data-bs-target="#bilancio-tab-statistiche" aria-controls="bilancio-tab-statistiche" aria-selected="false">
            <i class="bx bx-bar-chart-alt-2 me-1"></i>Statistiche
          </button>
        </li>
      </ul>
    </div>
  </div>
</div>

<div class="tab-content pt-2">
  @include('bilancio._partials.statistiche')
  @include('bilancio._partials.sintesi')
  @include('bilancio._partials.costi')
  @include('bilancio._partials.ricavi')
</div>

@endsection

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', function () {
    var bilancioCharts = [];

    function resizeBilancioCharts() {
      bilancioCharts.forEach(function (chart) {
        if (chart && typeof chart.updateOptions === 'function') {
          chart.updateOptions({}, false, true);
        }
      });
    }

    document.querySelectorAll('[data-bs-toggle="tab"][data-bs-target^="#bilancio-tab-"]').forEach(function (tabBtn) {
      tabBtn.addEventListener('shown.bs.tab', resizeBilancioCharts);
    });

    function renderBilancioCharts(retryCount) {
      if (typeof ApexCharts === 'undefined') {
        if (retryCount > 0) {
          setTimeout(function () {
            renderBilancioCharts(retryCount - 1);
          }, 120);
        }
        return;
      }

      var labels = @json($chartLabels);
      var costiSeries = @json($chartCostiSeries);
      var costiNegativeSeries = costiSeries.map(function (n) { return -1 * Number(n || 0); });
      var ricaviSeries = @json($chartRicaviSeries);
      var saldoSeries = @json($chartSaldoSeries);
      var categorieCostiLabels = @json($chartCategorieCostiLabels);
      var categorieCostiSeries = @json($chartCategorieCostiSeries);
      var categorieCostiColors = @json($chartCategorieCostiColors);
      var categorieRicaviLabels = @json($chartCategorieRicaviLabels);
      var categorieRicaviSeries = @json($chartCategorieRicaviSeries);
      var categorieRicaviColors = @json($chartCategorieRicaviColors);
      var statCategoriaLabels = @json($statCategoriaLabels);
      var statCategoriaSaldo = @json($statCategoriaSaldo);
      var statPiattiLabels = @json($statPiattiLabels);
      var statPiattiTotali = @json($statPiattiTotali);
      var statCucineLabels = @json($statCucineLabels);
      var statCucineTotali = @json($statCucineTotali);
      var statPagamentiLabels = @json($statPagamentiLabels);
      var statPagamentiTotali = @json($statPagamentiTotali);
      var affluenzaHeatmapSeries = @json($affluenzaHeatmapSeries);
      var affluenzaGiorniLabels = @json($affluenzaGiorniLabels);
      var affluenzaGiorniSeries = @json($affluenzaGiorniSeries);
      var css = getComputedStyle(document.documentElement);
      var labelColor = (css.getPropertyValue('--bs-secondary-color') || '#6c757d').trim();
      var borderColor = (css.getPropertyValue('--bs-border-color') || '#e9ecef').trim();
      var cardColor = (css.getPropertyValue('--bs-body-bg') || '#fff').trim();

      function buildParetoData(values) {
        var total = values.reduce(function (sum, n) { return sum + Number(n || 0); }, 0);
        var cumulative = 0;
        return values.map(function (n) {
          cumulative += Number(n || 0);
          if (total <= 0) {
            return 0;
          }
          return Number(((cumulative / total) * 100).toFixed(2));
        });
      }

      function shortLabel(text, max) {
        var s = String(text || '');
        if (s.length <= max) {
          return s;
        }
        return s.slice(0, max - 1) + '…';
      }

      function buildTotalBalanceLineOptions(series, colors, dropShadowColor, withLegend) {
        return {
          series: series,
          chart: {
            height: 245,
            parentHeightOffset: 0,
            parentWidthOffset: 0,
            type: 'line',
            zoom: { enabled: true },
            dropShadow: {
              enabled: true,
              top: 10,
              left: 5,
              blur: 3,
              color: dropShadowColor,
              opacity: 0.15
            },
            toolbar: { show: false }
          },
          dataLabels: { enabled: false },
          stroke: { width: 4, curve: 'smooth' },
          colors: colors,
          markers: {
            size: 6,
            colors: 'transparent',
            strokeColors: 'transparent',
            strokeWidth: 4,
            hover: { size: 9 }
          },
          xaxis: {
            categories: labels,
            axisBorder: { show: false },
            axisTicks: { show: false },
            labels: {
              style: {
                colors: labelColor,
                fontSize: '13px'
              }
            }
          },
          yaxis: {
            labels: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(0);
              },
              style: {
                colors: labelColor,
                fontSize: '13px'
              }
            }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          grid: {
            show: false,
            padding: {
              top: -10,
              left: 0,
              right: 0,
              bottom: 10
            }
          },
          legend: {
            show: !!withLegend,
            position: 'top',
            horizontalAlign: 'left'
          }
        };
      }

      var costiEl = document.querySelector('#bilancio-costi-chart');
      if (costiEl && !costiEl.dataset.chartRendered) {
        var costiChart = new ApexCharts(costiEl, {
          series: [{ name: 'Costi', data: costiSeries }],
          chart: {
            height: 245,
            parentHeightOffset: 0,
            parentWidthOffset: 0,
            type: 'line',
            dropShadow: {
              enabled: true,
              top: 10,
              left: 5,
              blur: 3,
              color: '#ff9f43',
              opacity: 0.15
            },
            toolbar: { show: false }
          },
          dataLabels: { enabled: false },
          stroke: { width: 4, curve: 'smooth' },
          legend: { show: false },
          colors: ['#ff9f43'],
          markers: {
            size: 6,
            colors: 'transparent',
            strokeColors: 'transparent',
            strokeWidth: 4,
            discrete: costiSeries.length ? [{
              fillColor: cardColor,
              seriesIndex: 0,
              dataPointIndex: costiSeries.length - 1,
              strokeColor: '#ff9f43',
              strokeWidth: 8,
              size: 6,
              radius: 8
            }] : [],
            hover: { size: 9 }
          },
          grid: {
            show: false,
            padding: {
              top: -10,
              left: 0,
              right: 0,
              bottom: 10
            }
          },
          xaxis: {
            categories: labels,
            axisBorder: { show: false },
            axisTicks: { show: false },
            labels: {
              show: true,
              style: {
                fontSize: '13px',
                colors: labelColor
              }
            }
          },
          yaxis: {
            labels: {
              show: false
            }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          }
        });
        costiChart.render();
        bilancioCharts.push(costiChart);
        costiEl.dataset.chartRendered = '1';
      }

      var ricaviEl = document.querySelector('#bilancio-ricavi-chart');
      if (ricaviEl && !ricaviEl.dataset.chartRendered) {
        var ricaviChart = new ApexCharts(ricaviEl, {
          series: [{ name: 'Ricavi', data: ricaviSeries }],
          chart: {
            height: 245,
            parentHeightOffset: 0,
            parentWidthOffset: 0,
            type: 'line',
            dropShadow: {
              enabled: true,
              top: 10,
              left: 5,
              blur: 3,
              color: '#ff9f43',
              opacity: 0.15
            },
            toolbar: { show: false }
          },
          dataLabels: { enabled: false },
          stroke: { width: 4, curve: 'smooth' },
          legend: { show: false },
          colors: ['#ff9f43'],
          markers: {
            size: 6,
            colors: 'transparent',
            strokeColors: 'transparent',
            strokeWidth: 4,
            discrete: ricaviSeries.length ? [{
              fillColor: cardColor,
              seriesIndex: 0,
              dataPointIndex: ricaviSeries.length - 1,
              strokeColor: '#ff9f43',
              strokeWidth: 8,
              size: 6,
              radius: 8
            }] : [],
            hover: { size: 9 }
          },
          grid: {
            show: false,
            padding: {
              top: -10,
              left: 0,
              right: 0,
              bottom: 10
            }
          },
          xaxis: {
            categories: labels,
            axisBorder: { show: false },
            axisTicks: { show: false },
            labels: {
              show: true,
              style: {
                fontSize: '13px',
                colors: labelColor
              }
            }
          },
          yaxis: {
            labels: {
              show: false
            }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          }
        });
        ricaviChart.render();
        bilancioCharts.push(ricaviChart);
        ricaviEl.dataset.chartRendered = '1';
      }

      var costiCategorieEl = document.querySelector('#bilancio-costi-categorie-chart');
      if (costiCategorieEl && !costiCategorieEl.dataset.chartRendered) {
        var costiCategorieChart = new ApexCharts(costiCategorieEl, {
          chart: {
            height: 360,
            type: 'bar',
            toolbar: { show: false }
          },
          series: [{ name: 'Costi per categoria', data: categorieCostiSeries }],
          colors: categorieCostiColors.length ? categorieCostiColors : ['#dc3545', '#f39c12', '#e74c3c', '#8e44ad', '#3498db', '#2ecc71'],
          plotOptions: {
            bar: {
              horizontal: true,
              barHeight: '60%',
              distributed: true,
              borderRadiusApplication: 'end',
              borderRadius: 7
            }
          },
          dataLabels: {
            enabled: true,
            style: {
              colors: ['#fff'],
              fontWeight: 400,
              fontSize: '13px'
            },
            formatter: function (val, opts) {
              return (categorieCostiLabels[opts.dataPointIndex] || '').toString();
            },
            offsetX: 0,
            dropShadow: { enabled: false }
          },
          xaxis: {
            categories: categorieCostiSeries.map(function (_, idx) { return String(idx + 1); }),
            labels: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(0);
              },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          yaxis: {
            max: Math.max.apply(null, categorieCostiSeries.concat([0])),
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          legend: { show: false },
          grid: { borderColor: borderColor }
        });
        costiCategorieChart.render();
        bilancioCharts.push(costiCategorieChart);
        costiCategorieEl.dataset.chartRendered = '1';
      }

      var ricaviCategorieEl = document.querySelector('#bilancio-ricavi-categorie-chart');
      if (ricaviCategorieEl && !ricaviCategorieEl.dataset.chartRendered) {
        var ricaviCategorieChart = new ApexCharts(ricaviCategorieEl, {
          chart: {
            height: 360,
            type: 'bar',
            toolbar: { show: false }
          },
          series: [{ name: 'Ricavi per categoria', data: categorieRicaviSeries }],
          colors: categorieRicaviColors.length ? categorieRicaviColors : ['#198754', '#17a2b8', '#20c997', '#6f42c1', '#ffc107', '#fd7e14'],
          plotOptions: {
            bar: {
              horizontal: true,
              barHeight: '60%',
              distributed: true,
              borderRadiusApplication: 'end',
              borderRadius: 7
            }
          },
          dataLabels: {
            enabled: true,
            style: {
              colors: ['#fff'],
              fontWeight: 400,
              fontSize: '13px'
            },
            formatter: function (val, opts) {
              return (categorieRicaviLabels[opts.dataPointIndex] || '').toString();
            },
            offsetX: 0,
            dropShadow: { enabled: false }
          },
          xaxis: {
            categories: categorieRicaviSeries.map(function (_, idx) { return String(idx + 1); }),
            labels: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(0);
              },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          yaxis: {
            max: Math.max.apply(null, categorieRicaviSeries.concat([0])),
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          legend: { show: false },
          grid: { borderColor: borderColor }
        });
        ricaviCategorieChart.render();
        bilancioCharts.push(ricaviCategorieChart);
        ricaviCategorieEl.dataset.chartRendered = '1';
      }

      var costiPercentEl = document.querySelector('#bilancio-costi-percent-chart');
      if (costiPercentEl && !costiPercentEl.dataset.chartRendered && categorieCostiSeries.length) {
        var costiPercentChart = new ApexCharts(costiPercentEl, {
          chart: {
            height: 396,
            type: 'donut',
            parentHeightOffset: 0,
            toolbar: { show: false }
          },
          labels: categorieCostiLabels,
          series: categorieCostiSeries,
          colors: categorieCostiColors.length ? categorieCostiColors : ['#dc3545'],
          stroke: { width: 0 },
          legend: {
            show: true,
            position: 'bottom',
            offsetY: 10,
            markers: { width: 8, height: 8, offsetX: -3 },
            itemMargin: { horizontal: 15, vertical: 5 },
            fontSize: '13px',
            labels: { colors: labelColor, useSeriesColors: false }
          },
          dataLabels: {
            enabled: false,
            formatter: function (val) {
              return parseInt(val, 10) + '%';
            }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          plotOptions: {
            pie: {
              donut: {
                size: '75%',
                labels: {
                  show: true,
                  value: {
                    fontSize: '24px',
                    color: labelColor,
                    fontWeight: 500,
                    offsetY: -20,
                    formatter: function (val) {
                      return parseInt(val, 10) + '%';
                    }
                  },
                  total: {
                    show: true,
                    fontSize: '15px',
                    color: labelColor,
                    label: 'Quota media costi',
                    formatter: function () {
                      var total = categorieCostiSeries.reduce(function (sum, n) { return sum + Number(n || 0); }, 0);
                      var avg = total > 0 ? (100 / categorieCostiSeries.length) : 0;
                      return Number(avg).toFixed(0) + '%';
                    }
                  }
                }
              }
            }
          },
          grid: { padding: { top: 15 } }
        });
        costiPercentChart.render();
        bilancioCharts.push(costiPercentChart);
        costiPercentEl.dataset.chartRendered = '1';
      }

      var ricaviPercentEl = document.querySelector('#bilancio-ricavi-percent-chart');
      if (ricaviPercentEl && !ricaviPercentEl.dataset.chartRendered && categorieRicaviSeries.length) {
        var ricaviPercentChart = new ApexCharts(ricaviPercentEl, {
          chart: {
            height: 396,
            type: 'donut',
            parentHeightOffset: 0,
            toolbar: { show: false }
          },
          labels: categorieRicaviLabels,
          series: categorieRicaviSeries,
          colors: categorieRicaviColors.length ? categorieRicaviColors : ['#198754'],
          stroke: { width: 0 },
          legend: {
            show: true,
            position: 'bottom',
            offsetY: 10,
            markers: { width: 8, height: 8, offsetX: -3 },
            itemMargin: { horizontal: 15, vertical: 5 },
            fontSize: '13px',
            labels: { colors: labelColor, useSeriesColors: false }
          },
          dataLabels: {
            enabled: false,
            formatter: function (val) {
              return parseInt(val, 10) + '%';
            }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          plotOptions: {
            pie: {
              donut: {
                size: '75%',
                labels: {
                  show: true,
                  value: {
                    fontSize: '24px',
                    color: labelColor,
                    fontWeight: 500,
                    offsetY: -20,
                    formatter: function (val) {
                      return parseInt(val, 10) + '%';
                    }
                  },
                  total: {
                    show: true,
                    fontSize: '15px',
                    color: labelColor,
                    label: 'Quota media ricavi',
                    formatter: function () {
                      var total = categorieRicaviSeries.reduce(function (sum, n) { return sum + Number(n || 0); }, 0);
                      var avg = total > 0 ? (100 / categorieRicaviSeries.length) : 0;
                      return Number(avg).toFixed(0) + '%';
                    }
                  }
                }
              }
            }
          },
          grid: { padding: { top: 15 } }
        });
        ricaviPercentChart.render();
        bilancioCharts.push(ricaviPercentChart);
        ricaviPercentEl.dataset.chartRendered = '1';
      }

      var costiParetoEl = document.querySelector('#bilancio-costi-pareto-chart');
      if (costiParetoEl && !costiParetoEl.dataset.chartRendered && categorieCostiSeries.length) {
        var costiParetoLine = buildParetoData(categorieCostiSeries);
        var costiParetoChart = new ApexCharts(costiParetoEl, {
          chart: {
            height: 320,
            type: 'line',
            stacked: false,
            toolbar: { show: false }
          },
          series: [
            { name: 'Costi', type: 'column', data: categorieCostiSeries },
            { name: 'Cumulata %', type: 'line', data: costiParetoLine }
          ],
          colors: ['#dc3545', '#ff9f43'],
          stroke: { width: [0, 3], curve: 'smooth' },
          dataLabels: { enabled: false },
          plotOptions: {
            bar: {
              columnWidth: '46%',
              borderRadius: 6,
              borderRadiusApplication: 'end'
            }
          },
          xaxis: {
            categories: categorieCostiLabels,
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          yaxis: [
            {
              labels: {
                formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
                style: { colors: labelColor, fontSize: '12px' }
              }
            },
            {
              opposite: true,
              max: 100,
              min: 0,
              tickAmount: 5,
              labels: {
                formatter: function (val) { return Number(val || 0).toFixed(0) + '%'; },
                style: { colors: '#ff9f43', fontSize: '12px' }
              }
            }
          ],
          tooltip: {
            shared: true,
            intersect: false,
            y: {
              formatter: function (val, opts) {
                if (opts.seriesIndex === 1) {
                  return Number(val || 0).toFixed(2) + '%';
                }
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          legend: { show: true, position: 'top', horizontalAlign: 'left' },
          grid: { borderColor: borderColor, strokeDashArray: 6 }
        });
        costiParetoChart.render();
        bilancioCharts.push(costiParetoChart);
        costiParetoEl.dataset.chartRendered = '1';
      }

      var ricaviParetoEl = document.querySelector('#bilancio-ricavi-pareto-chart');
      if (ricaviParetoEl && !ricaviParetoEl.dataset.chartRendered && categorieRicaviSeries.length) {
        var ricaviParetoLine = buildParetoData(categorieRicaviSeries);
        var ricaviParetoChart = new ApexCharts(ricaviParetoEl, {
          chart: {
            height: 320,
            type: 'line',
            stacked: false,
            toolbar: { show: false }
          },
          series: [
            { name: 'Ricavi', type: 'column', data: categorieRicaviSeries },
            { name: 'Cumulata %', type: 'line', data: ricaviParetoLine }
          ],
          colors: ['#198754', '#ff9f43'],
          stroke: { width: [0, 3], curve: 'smooth' },
          dataLabels: { enabled: false },
          plotOptions: {
            bar: {
              columnWidth: '46%',
              borderRadius: 6,
              borderRadiusApplication: 'end'
            }
          },
          xaxis: {
            categories: categorieRicaviLabels,
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          yaxis: [
            {
              labels: {
                formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
                style: { colors: labelColor, fontSize: '12px' }
              }
            },
            {
              opposite: true,
              max: 100,
              min: 0,
              tickAmount: 5,
              labels: {
                formatter: function (val) { return Number(val || 0).toFixed(0) + '%'; },
                style: { colors: '#ff9f43', fontSize: '12px' }
              }
            }
          ],
          tooltip: {
            shared: true,
            intersect: false,
            y: {
              formatter: function (val, opts) {
                if (opts.seriesIndex === 1) {
                  return Number(val || 0).toFixed(2) + '%';
                }
                return '€ ' + Number(val || 0).toFixed(2).replace('.', ',');
              }
            }
          },
          legend: { show: true, position: 'top', horizontalAlign: 'left' },
          grid: { borderColor: borderColor, strokeDashArray: 6 }
        });
        ricaviParetoChart.render();
        bilancioCharts.push(ricaviParetoChart);
        ricaviParetoEl.dataset.chartRendered = '1';
      }

      var statPerfEl = document.querySelector('#bilancio-stat-performance-chart');
      if (statPerfEl && !statPerfEl.dataset.chartRendered) {
        var statPerfChart = new ApexCharts(statPerfEl, {
          chart: {
            height: 320,
            type: 'line',
            stacked: false,
            toolbar: { show: false },
            zoom: { enabled: false }
          },
          series: [
            { name: 'Ricavi', type: 'line', data: ricaviSeries },
            { name: 'Costi', type: 'line', data: costiSeries },
            { name: 'Saldo', type: 'line', data: saldoSeries }
          ],
          colors: ['#198754', '#dc3545', '#ff9f43'],
          stroke: { curve: 'smooth', width: [3, 3, 4] },
          markers: { size: 4, hover: { size: 6 } },
          dataLabels: { enabled: false },
          xaxis: {
            categories: labels,
            labels: { style: { colors: labelColor, fontSize: '12px' } },
            axisBorder: { show: false },
            axisTicks: { show: false }
          },
          yaxis: {
            labels: {
              formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          legend: { position: 'top', horizontalAlign: 'left' },
          tooltip: {
            shared: true,
            intersect: false,
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          },
          grid: { borderColor: borderColor, strokeDashArray: 6 }
        });
        statPerfChart.render();
        bilancioCharts.push(statPerfChart);
        statPerfEl.dataset.chartRendered = '1';
      }

      var statRangeEl = document.querySelector('#bilancio-stat-balance-range-chart');
      if (statRangeEl && !statRangeEl.dataset.chartRendered) {
        var statRangeChart = new ApexCharts(statRangeEl, {
          chart: {
            height: 320,
            type: 'bar',
            toolbar: { show: false }
          },
          series: [
            {
              name: 'Saldo',
              data: saldoSeries
            }
          ],
          colors: saldoSeries.map(function (v) { return Number(v || 0) >= 0 ? '#198754' : '#dc3545'; }),
          plotOptions: {
            bar: {
              distributed: true,
              borderRadius: 6,
              columnWidth: '50%'
            }
          },
          dataLabels: { enabled: false },
          xaxis: {
            categories: labels,
            labels: { style: { colors: labelColor, fontSize: '12px' } },
            axisBorder: { show: false },
            axisTicks: { show: false }
          },
          yaxis: {
            labels: {
              formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          tooltip: {
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          },
          grid: { borderColor: borderColor, strokeDashArray: 6 },
          legend: { show: false }
        });
        statRangeChart.render();
        bilancioCharts.push(statRangeChart);
        statRangeEl.dataset.chartRendered = '1';
      }

      var statCategoriaEl = document.querySelector('#bilancio-stat-categoria-chart');
      if (statCategoriaEl && !statCategoriaEl.dataset.chartRendered && statCategoriaSaldo.length) {
        var statCategoriaLabelsShort = statCategoriaLabels.map(function (label) { return shortLabel(label, 22); });
        var statCategoriaChart = new ApexCharts(statCategoriaEl, {
          chart: { height: 360, type: 'bar', toolbar: { show: false } },
          series: [{ name: 'Saldo categoria', data: statCategoriaSaldo }],
          colors: statCategoriaSaldo.map(function (v) { return Number(v || 0) >= 0 ? '#198754' : '#dc3545'; }),
          plotOptions: { bar: { horizontal: true, distributed: true, borderRadius: 6, barHeight: '60%' } },
          dataLabels: { enabled: false },
          xaxis: {
            categories: statCategoriaLabelsShort,
            labels: {
              formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          yaxis: {
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          legend: { show: false },
          grid: { borderColor: borderColor, strokeDashArray: 6 },
          tooltip: {
            x: { formatter: function (_, opts) { return statCategoriaLabels[opts.dataPointIndex] || ''; } },
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          }
        });
        statCategoriaChart.render();
        bilancioCharts.push(statCategoriaChart);
        statCategoriaEl.dataset.chartRendered = '1';
      }

      var statPiattiEl = document.querySelector('#bilancio-stat-piatti-chart');
      if (statPiattiEl && !statPiattiEl.dataset.chartRendered && statPiattiTotali.length) {
        var statPiattiLabelsShort = statPiattiLabels.map(function (label) { return shortLabel(label, 22); });
        var statPiattiChart = new ApexCharts(statPiattiEl, {
          chart: { height: 360, type: 'bar', toolbar: { show: false } },
          series: [{ name: 'Incasso piatto', data: statPiattiTotali }],
          colors: ['#696cff'],
          plotOptions: { bar: { horizontal: true, borderRadius: 6, barHeight: '60%' } },
          dataLabels: { enabled: false },
          xaxis: {
            categories: statPiattiLabelsShort,
            labels: {
              formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          yaxis: {
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          legend: { show: false },
          grid: { borderColor: borderColor, strokeDashArray: 6 },
          tooltip: {
            x: { formatter: function (_, opts) { return statPiattiLabels[opts.dataPointIndex] || ''; } },
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          }
        });
        statPiattiChart.render();
        bilancioCharts.push(statPiattiChart);
        statPiattiEl.dataset.chartRendered = '1';
      }

      var statCucineEl = document.querySelector('#bilancio-stat-cucine-chart');
      if (statCucineEl && !statCucineEl.dataset.chartRendered && statCucineTotali.length) {
        var statCucineLabelsShort = statCucineLabels.map(function (label) { return shortLabel(label, 22); });
        var statCucineChart = new ApexCharts(statCucineEl, {
          chart: { height: 360, type: 'bar', toolbar: { show: false } },
          series: [{ name: 'Incasso cucina', data: statCucineTotali }],
          colors: ['#20c997'],
          plotOptions: { bar: { horizontal: true, borderRadius: 6, barHeight: '60%' } },
          dataLabels: { enabled: false },
          xaxis: {
            categories: statCucineLabelsShort,
            labels: {
              formatter: function (val) { return '€ ' + Number(val || 0).toFixed(0); },
              style: { colors: labelColor, fontSize: '12px' }
            }
          },
          yaxis: {
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          legend: { show: false },
          grid: { borderColor: borderColor, strokeDashArray: 6 },
          tooltip: {
            x: { formatter: function (_, opts) { return statCucineLabels[opts.dataPointIndex] || ''; } },
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          }
        });
        statCucineChart.render();
        bilancioCharts.push(statCucineChart);
        statCucineEl.dataset.chartRendered = '1';
      }

      var statPagamentiEl = document.querySelector('#bilancio-stat-pagamenti-chart');
      if (statPagamentiEl && !statPagamentiEl.dataset.chartRendered && statPagamentiTotali.length) {
        var statPagamentiChart = new ApexCharts(statPagamentiEl, {
          chart: { height: 320, type: 'donut', toolbar: { show: false } },
          series: statPagamentiTotali,
          labels: statPagamentiLabels,
          colors: ['#198754', '#696cff', '#ff9f43', '#20c997', '#e74c3c', '#6c757d'],
          dataLabels: { enabled: false },
          legend: { position: 'bottom', fontSize: '12px' },
          tooltip: {
            y: { formatter: function (val) { return '€ ' + Number(val || 0).toFixed(2).replace('.', ','); } }
          },
          plotOptions: {
            pie: {
              donut: {
                size: '65%',
                labels: {
                  show: true,
                  total: {
                    show: true,
                    label: 'Totale pagamenti',
                    formatter: function () {
                      var total = statPagamentiTotali.reduce(function (sum, n) { return sum + Number(n || 0); }, 0);
                      return '€ ' + total.toFixed(2).replace('.', ',');
                    }
                  }
                }
              }
            }
          }
        });
        statPagamentiChart.render();
        bilancioCharts.push(statPagamentiChart);
        statPagamentiEl.dataset.chartRendered = '1';
      }

      var statAffluenzaHeatmapEl = document.querySelector('#bilancio-stat-affluenza-heatmap');
      if (statAffluenzaHeatmapEl && !statAffluenzaHeatmapEl.dataset.chartRendered && affluenzaHeatmapSeries.length) {
        var statAffluenzaHeatmapChart = new ApexCharts(statAffluenzaHeatmapEl, {
          chart: {
            height: 320,
            type: 'heatmap',
            toolbar: { show: false }
          },
          series: affluenzaHeatmapSeries,
          dataLabels: { enabled: false },
          plotOptions: {
            heatmap: {
              shadeIntensity: 0.4,
              radius: 5,
              colorScale: {
                ranges: [
                  { from: 0, to: 0, color: '#f5f5f9', name: 'Bassa' },
                  { from: 1, to: 3, color: '#d9f2e6', name: 'Media' },
                  { from: 4, to: 9999, color: '#198754', name: 'Alta' }
                ]
              }
            }
          },
          xaxis: {
            labels: { style: { colors: labelColor, fontSize: '11px' } },
            axisBorder: { show: false },
            axisTicks: { show: false }
          },
          yaxis: {
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          legend: { position: 'bottom' },
          grid: { borderColor: borderColor },
          tooltip: {
            y: {
              formatter: function (val) {
                return Number(val || 0) + ' pagamenti';
              }
            }
          }
        });
        statAffluenzaHeatmapChart.render();
        bilancioCharts.push(statAffluenzaHeatmapChart);
        statAffluenzaHeatmapEl.dataset.chartRendered = '1';
      }

      var statAffluenzaGiorniEl = document.querySelector('#bilancio-stat-affluenza-giorni-chart');
      if (statAffluenzaGiorniEl && !statAffluenzaGiorniEl.dataset.chartRendered && affluenzaGiorniSeries.length) {
        var statAffluenzaGiorniChart = new ApexCharts(statAffluenzaGiorniEl, {
          chart: { height: 320, type: 'bar', toolbar: { show: false } },
          series: [{ name: 'Pagamenti', data: affluenzaGiorniSeries }],
          colors: ['#696cff'],
          plotOptions: {
            bar: {
              borderRadius: 6,
              columnWidth: '45%'
            }
          },
          dataLabels: { enabled: false },
          xaxis: {
            categories: affluenzaGiorniLabels,
            labels: { style: { colors: labelColor, fontSize: '12px' } },
            axisBorder: { show: false },
            axisTicks: { show: false }
          },
          yaxis: {
            labels: { style: { colors: labelColor, fontSize: '12px' } }
          },
          tooltip: {
            y: {
              formatter: function (val) {
                return Number(val || 0) + ' pagamenti';
              }
            }
          },
          legend: { show: false },
          grid: { borderColor: borderColor, strokeDashArray: 6 }
        });
        statAffluenzaGiorniChart.render();
        bilancioCharts.push(statAffluenzaGiorniChart);
        statAffluenzaGiorniEl.dataset.chartRendered = '1';
      }

      var saldoColEl = document.querySelector('#bilancio-saldo-col-chart');
      if (saldoColEl && !saldoColEl.dataset.chartRendered) {
        var saldoChart = new ApexCharts(saldoColEl, {
          chart: {
            height: 280,
            type: 'line',
            stacked: false,
            toolbar: { show: false },
            zoom: { enabled: true }
          },
          series: [
            { name: 'Ricavi', type: 'column', data: ricaviSeries },
            { name: 'Costi', type: 'column', data: costiNegativeSeries },
            { name: 'Saldo', type: 'line', data: saldoSeries }
          ],
          colors: ['#198754', '#dc3545', '#ff9f43'],
          stroke: {
            width: [0, 0, 4],
            curve: 'smooth'
          },
          markers: {
            size: [0, 0, 0],
            strokeWidth: 0,
            hover: { size: 0 }
          },
          plotOptions: {
            bar: {
              horizontal: false,
              columnWidth: '42%',
              borderRadius: 6,
              borderRadiusApplication: 'end'
            }
          },
          dataLabels: { enabled: false },
          xaxis: {
            categories: labels,
            axisBorder: { show: false },
            axisTicks: { show: false },
            labels: {
              style: {
                colors: labelColor,
                fontSize: '13px'
              }
            }
          },
          yaxis: {
            labels: {
              formatter: function (val) {
                return '€ ' + Math.abs(Number(val || 0)).toFixed(0);
              },
              style: {
                colors: labelColor,
                fontSize: '13px'
              }
            }
          },
          tooltip: {
            shared: true,
            intersect: false,
            y: {
              formatter: function (val, opts) {
                var abs = Math.abs(Number(val || 0));
                var prefix = opts.seriesIndex === 1 ? '- ' : '';
                return prefix + '€ ' + abs.toFixed(2).replace('.', ',');
              }
            }
          },
          grid: {
            borderColor: borderColor,
            xaxis: { lines: { show: true } },
            yaxis: { lines: { show: true } }
          },
          legend: {
            show: true,
            position: 'top',
            horizontalAlign: 'left'
          }
        });
        saldoChart.render();
        bilancioCharts.push(saldoChart);
        saldoColEl.dataset.chartRendered = '1';
      }
    }

    renderBilancioCharts(10);
  });
</script>
@endsection
