<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Attivita;
use Illuminate\Http\Request;
use App\Models\Segnalazione;
use App\Models\Reparto;
use App\Models\Manutentore;
use App\Models\TempoImpiegato;
use App\Models\Config;
use App\Models\ConfiguraSegnalazione;
use App\Models\Annotazione;
use App\Models\Ordine;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class HomePageController extends Controller
{
  public function welcome()
  {
    $pageConfigs = ['myLayout' => 'front'];
    $attivitaAttive = Attivita::query()
      ->where('is_attiva', true)
      ->orderBy('nome')
      ->get();

    return view('welcome', compact('pageConfigs', 'attivitaAttive'));
  }

  public function admin_dashboard()
  {
    return view('dashboard.index', [
      'statOrdini' => $this->getStatOrdini(),
      'totaleRedditi' => $this->getTotaleRedditi(),
    ]);
  }

  /**
   * Incassi da ordini (esclusi carrello / annullati): serie mensile anno corrente e KPI riepilogo.
   *
   * @return array<string, mixed>
   */
  private function getTotaleRedditi(): array
  {
    $now = Carbon::now();
    $year = (int) $now->year;
    $startYear = Carbon::create($year, 1, 1)->startOfDay();
    $endYear = Carbon::create($year, 12, 31)->endOfDay();

    $base = Ordine::query()
    ->where('attivita_id', session()->get('attivita_attuale'))
      ->whereNotNull('prezzo')
      ->where('prezzo', '>', 0)
      ->whereNotIn('stato', [
        Ordine::CARRELLO,
        Ordine::ANNULATO,
        Ordine::CANCELLATO,
        Ordine::CHECKOUT,
      ]);

    $chartSeries = [];
    for ($m = 1; $m <= 12; $m++) {
      $chartSeries[] = round((float) (clone $base)
        ->whereYear('created_at', $year)
        ->whereMonth('created_at', $m)
        ->sum('prezzo'), 2);
    }

    $categories = ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'];

    $ytdEnd = $now->copy()->endOfDay();
    if ($ytdEnd->gt($endYear)) {
      $ytdEnd = $endYear->copy();
    }

    $incassoYtd = (float) (clone $base)
      ->whereBetween('created_at', [$startYear, $ytdEnd])
      ->sum('prezzo');

    $prevYearStart = $startYear->copy()->subYear();
    $prevYearSameDay = $now->copy()->subYear();
    $incassoYtdAnnoPrec = (float) (clone $base)
      ->whereBetween('created_at', [$prevYearStart, $prevYearSameDay])
      ->sum('prezzo');

    $deltaYtdPct = $incassoYtdAnnoPrec > 0.009
      ? round((($incassoYtd - $incassoYtdAnnoPrec) / $incassoYtdAnnoPrec) * 100, 1)
      : null;

    $monthsElapsed = max(1, (int) $now->month);
    $mediaMensile = $incassoYtd / $monthsElapsed;

    $meseCorrenteStart = $now->copy()->startOfMonth();
    $meseCorrenteEnd = $now->copy()->endOfMonth();
    $incassoMeseCorrente = (float) (clone $base)
      ->whereBetween('created_at', [$meseCorrenteStart, $meseCorrenteEnd])
      ->sum('prezzo');

    $mesePrecStart = $now->copy()->subMonth()->startOfMonth();
    $mesePrecEnd = $now->copy()->subMonth()->endOfMonth();
    $incassoMesePrec = (float) (clone $base)
      ->whereBetween('created_at', [$mesePrecStart, $mesePrecEnd])
      ->sum('prezzo');

    $deltaMeseEuro = $incassoMeseCorrente - $incassoMesePrec;

    $maxChart = max($chartSeries) ?: 1.0;

    $nomiMesi = [
      1 => 'Gennaio', 2 => 'Febbraio', 3 => 'Marzo', 4 => 'Aprile',
      5 => 'Maggio', 6 => 'Giugno', 7 => 'Luglio', 8 => 'Agosto',
      9 => 'Settembre', 10 => 'Ottobre', 11 => 'Novembre', 12 => 'Dicembre',
    ];

    return [
      'year' => $year,
      'mese_corrente_nome' => $nomiMesi[(int) $now->month] ?? '',
      'chart_categories' => $categories,
      'chart_series' => $chartSeries,
      'chart_max' => max(100.0, $maxChart * 1.15),
      'incasso_ytd' => $incassoYtd,
      'incasso_ytd_fmt' => number_format($incassoYtd, 2, ',', '.'),
      'delta_ytd_pct' => $deltaYtdPct,
      'delta_ytd_positive' => $deltaYtdPct === null ? null : $deltaYtdPct >= 0,
      'media_mensile' => $mediaMensile,
      'media_mensile_fmt' => number_format($mediaMensile, 2, ',', '.'),
      'incasso_mese_corrente' => $incassoMeseCorrente,
      'incasso_mese_corrente_fmt' => number_format($incassoMeseCorrente, 2, ',', '.'),
      'delta_mese_euro' => $deltaMeseEuro,
      'delta_mese_fmt' => ($deltaMeseEuro >= 0 ? '+' : '-') . ' ' . number_format(abs($deltaMeseEuro), 2, ',', '.') . ' €',
      'delta_mese_positive' => $deltaMeseEuro >= 0,
      'delta_ytd_fmt' => $deltaYtdPct === null
        ? null
        : (($deltaYtdPct >= 0 ? '+' : '') . number_format($deltaYtdPct, 1, ',', '.') . ' %'),
    ];
  }

  private function getStatOrdini(): array
  {
    $total = Ordine::query()->where('attivita_id', session()->get('attivita_attuale'))->count();
    $totaleIncasso = (float) Ordine::query()->where('attivita_id', session()->get('attivita_attuale'))->whereNotNull('prezzo')->sum('prezzo');

    $byStato = Ordine::query()
    ->where('attivita_id', session()->get('attivita_attuale'))
      ->select('stato', DB::raw('COUNT(*) as totale'))
      ->groupBy('stato')
      ->orderByDesc('totale')
      ->get();

    $statiMap = Ordine::STATI;
    $colorCycle = ['#28c76f', '#696cff', '#03c3ec', '#ff9f43', '#8592a3', '#ff3e1d', '#7367f0', '#ea5455', '#00cfe8'];
    $bgCycle = ['primary', 'success', 'info', 'warning', 'secondary', 'danger', 'primary', 'danger', 'info'];

    $rows = [];
    $chartLabels = [];
    $chartSeries = [];
    $chartColors = [];

    $i = 0;
    foreach ($byStato as $row) {
      $key = (string) $row->stato;
      $count = (int) $row->totale;
      $meta = $statiMap[$key] ?? null;
      $label = is_array($meta) ? ($meta['label'] ?? $key) : $key;
      $subtitle = is_array($meta) ? ($meta['descrizione'] ?? $key) : $key;

      $rows[] = [
        'label' => $label,
        'count' => $count,
        'subtitle' => $subtitle,
        'icon' => $this->iconForOrdineStato($key),
        'bg' => 'bg-label-' . $bgCycle[$i % count($bgCycle)],
      ];
      $chartLabels[] = $label;
      $chartSeries[] = $count;
      $chartColors[] = $colorCycle[$i % count($colorCycle)];
      $i++;
    }

    if ($total === 0) {
      $chartLabels = ['Nessun ordine'];
      $chartSeries = [1];
      $chartColors = ['#8592a3'];
    }

    return [
      'total_ordini' => $total,
      'totale_incasso' => $totaleIncasso,
      'totale_incasso_fmt' => number_format($totaleIncasso, 2, ',', '.'),
      'rows' => $rows,
      'chart_labels' => $chartLabels,
      'chart_series' => $chartSeries,
      'chart_colors' => $chartColors,
    ];
  }

  private function iconForOrdineStato(string $stato): string
  {
    $meta = Ordine::STATI[$stato] ?? null;
    return is_array($meta) ? ($meta['icon'] ?? 'bx bx-receipt') : 'bx bx-receipt';

  }

}
