@php
  $reportTitle = $reportTitle ?? 'Report Incassi';
  $attivitaNome = $attivitaNome ?? 'Attivita';
  $periodoLabel = $periodoLabel ?? 'Periodo non specificato';
  $generatoIl = $generatoIl ?? now()->format('d/m/Y H:i');
  $movimenti = collect($movimenti ?? [])
    ->map(function ($movimento) {
      $rawTs = $movimento['timestamp'] ?? $movimento['data'] ?? null;
      $parsedTs = $rawTs ? strtotime((string) $rawTs) : false;

      if ($parsedTs !== false) {
        $movimento['_sort_ts'] = $parsedTs;
        $movimento['_display_ts'] = date('Y-m-d H:i:s', $parsedTs);
        $movimento['_date_key'] = date('Y-m-d', $parsedTs);
        $movimento['_date_label'] = date('d/m/Y', $parsedTs);
      } else {
        $movimento['_sort_ts'] = 0;
        $movimento['_display_ts'] = '-';
        $movimento['_date_key'] = '0000-00-00';
        $movimento['_date_label'] = '-';
      }

      $movimento['_metodo'] = (string) ($movimento['metodo'] ?? 'N/D');
      $tipo = strtolower((string) ($movimento['tipo'] ?? 'entrata'));
      $importo = (float) ($movimento['importo'] ?? 0);
      // Per incassi i movimenti di uscita (es. rimborsi) impattano in negativo.
      $movimento['_signed_importo'] = $tipo === 'uscita' ? -abs($importo) : abs($importo);

      return $movimento;
    })
    ->sortByDesc('_sort_ts')
    ->values();

  $totEntrate = (float) ($totEntrate ?? $movimenti->where('tipo', 'entrata')->sum('importo'));
  $totUscite = (float) ($totUscite ?? $movimenti->where('tipo', 'uscita')->sum('importo'));
  $saldo = (float) ($saldo ?? ($totEntrate - $totUscite));

  $metodiPagamento = $movimenti
    ->pluck('_metodo')
    ->filter()
    ->unique()
    ->sort()
    ->values();

  $giorni = $movimenti
    ->groupBy('_date_key')
    ->sortKeysDesc()
    ->map(function ($items, $dateKey) use ($metodiPagamento) {
      $primaRiga = $items->first();
      $celle = [];
      foreach ($metodiPagamento as $metodo) {
        $celle[$metodo] = (float) $items
          ->where('_metodo', $metodo)
          ->sum('_signed_importo');
      }

      return [
        'date_key' => $dateKey,
        'date_label' => $primaRiga['_date_label'] ?? '-',
        'celle' => $celle,
        'totale' => array_sum($celle),
      ];
    })
    ->values();
@endphp

<style>
  .report-print {
    background: #fff;
    color: #111827;
    padding: 24px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    font-family: Arial, Helvetica, sans-serif;
  }

  .report-head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 18px;
  }

  .report-title {
    font-size: 24px;
    font-weight: 700;
    margin: 0 0 4px;
    color: #111827;
  }

  .report-title-row {
    display: flex;
    align-items: baseline;
    gap: 10px;
    flex-wrap: wrap;
  }

  .report-title-periodo {
    font-size: 20px;
    font-weight: 700;
    color: #374151;
    margin: 0;
  }

  .report-subtitle {
    margin: 0;
    font-size: 13px;
    color: #4b5563;
  }

  .report-meta {
    text-align: right;
    font-size: 12px;
    color: #6b7280;
  }

  .report-currency {
    margin-bottom: 10px;
    font-size: 12px;
    color: #6b7280;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .report-cards {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
    margin-bottom: 18px;
  }

  .report-card {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 10px 12px;
    background: #f9fafb;
  }

  .report-card .label {
    display: block;
    font-size: 12px;
    color: #6b7280;
    margin-bottom: 4px;
  }

  .report-card .value {
    font-size: 18px;
    font-weight: 700;
    color: #111827;
  }

  .report-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #e5e7eb;
  }

  .report-table thead th {
    font-size: 12px;
    font-weight: 700;
    text-align: left;
    padding: 8px 10px;
    color: #374151;
    background: #f3f4f6;
    border-bottom: 1px solid #e5e7eb;
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .report-table tbody td {
    font-size: 12px;
    padding: 8px 10px;
    border-bottom: 1px solid #f3f4f6;
    color: #1f2937;
  }

  .report-table tbody tr:nth-child(even) {
    background: #fcfcfd;
  }

  .text-right {
    text-align: right;
  }

  .report-table th.text-right,
  .report-table td.text-right {
    text-align: right;
  }

  .font-mono {
    font-family: "Consolas", "Courier New", monospace;
    font-variant-numeric: tabular-nums;
  }

  .report-causale {
    font-weight: 600;
    color: #111827;
  }

  .cell-negative {
    color: #991b1b;
  }

  .report-table tfoot td {
    font-size: 12px;
    font-weight: 700;
    padding: 8px 10px;
    border-top: 2px solid #d1d5db;
    background: #f9fafb;
  }

  .report-table .total-col {
    font-weight: 700;
    background: #fcfcfd;
  }

  .report-footer {
    margin-top: 12px;
    font-size: 11px;
    color: #6b7280;
  }

  @media print {
    body {
      background: #fff !important;
    }

    .report-print {
      border: 0;
      border-radius: 0;
      padding: 0;
    }
  }
</style>

<section class="report-print">
  <header class="report-head">
    <div>
      <div class="report-title-row">
        <h1 class="report-title">{{ $reportTitle }}</h1>
    
        <h2 class="report-title-periodo">Periodo: {{ $periodoLabel }}</h2>
      </div>
      <p class="report-subtitle">
        {{ $attivitaNome }}
      </p>
    </div>
    <div class="report-meta">
      Generato il<br>
      <strong>{{ $generatoIl }}</strong>
    </div>
  </header>

  <div class="report-currency">Valuta: EUR</div>

  <div class="report-cards">
    <div class="report-card">
      <span class="label">Totale Mov. Avere</span>
      <span class="value">{{ number_format($totEntrate, 2, ',', '.') }}</span>
    </div>
    <div class="report-card">
      <span class="label">Totale Mov. Dare</span>
      <span class="value">{{ number_format($totUscite, 2, ',', '.') }}</span>
    </div>
    <div class="report-card">
      <span class="label">Saldo</span>
      <span class="value">{{ number_format($saldo, 2, ',', '.') }}</span>
    </div>
  </div>

  <table class="report-table">
    <thead>
      <tr>
        <th>Data</th>
        @foreach($metodiPagamento as $metodo)
          <th class="text-right font-mono">{{ $metodo }}</th>
        @endforeach
        <th class="text-right font-mono">Totale</th>
      </tr>
    </thead>
    <tbody>
      @forelse($giorni as $giorno)
        <tr>
          <td class="font-mono">{{ $giorno['date_label'] }}</td>
          @foreach($metodiPagamento as $metodo)
            @php $val = (float) ($giorno['celle'][$metodo] ?? 0); @endphp
            <td class="text-right font-mono {{ $val < 0 ? 'cell-negative' : '' }}">
              {{ number_format($val, 2, ',', '.') }}
            </td>
          @endforeach
          <td class="text-right font-mono total-col {{ $giorno['totale'] < 0 ? 'cell-negative' : '' }}">
            {{ number_format((float) $giorno['totale'], 2, ',', '.') }}
          </td>
        </tr>
      @empty
        <tr>
          <td colspan="{{ 2 + $metodiPagamento->count() }}">Nessun incasso trovato nel periodo selezionato.</td>
        </tr>
      @endforelse
    </tbody>
    @if($giorni->isNotEmpty())
      <tfoot>
        <tr>
          <td>Totale periodo</td>
          @foreach($metodiPagamento as $metodo)
            @php
              $totMetodo = (float) $movimenti->where('_metodo', $metodo)->sum('_signed_importo');
            @endphp
            <td class="text-right font-mono {{ $totMetodo < 0 ? 'cell-negative' : '' }}">
              {{ number_format($totMetodo, 2, ',', '.') }}
            </td>
          @endforeach
          <td class="text-right font-mono total-col {{ $saldo < 0 ? 'cell-negative' : '' }}">
            {{ number_format($saldo, 2, ',', '.') }}
          </td>
        </tr>
      </tfoot>
    @endif
  </table>

  <div class="report-footer">
    Documento a uso interno. Valori espressi in euro.
  </div>
</section>
