<?php

namespace App\Http\Controllers\Painel;

use App\Http\Controllers\Controller;
use App\Models\NotaFiscal;
use App\Models\SyncLog;
use App\Support\Sql;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function __invoke(Request $request): View
    {
        $company = $request->user()->company;
        $inicioMes = Carbon::now()->startOfMonth();

        $totais = NotaFiscal::query()
            ->selectRaw('COUNT(*) as total')
            ->selectRaw('COALESCE(SUM(valor_total), 0) as valor')
            ->selectRaw('SUM(CASE WHEN tem_xml_completo = 1 THEN 1 ELSE 0 END) as completas')
            ->selectRaw('SUM(CASE WHEN situacao = ? THEN 1 ELSE 0 END) as canceladas', ['cancelada'])
            ->first();

        $mes = NotaFiscal::query()
            ->where('data_emissao', '>=', $inicioMes)
            ->selectRaw('COUNT(*) as total')
            ->selectRaw('COALESCE(SUM(valor_total), 0) as valor')
            ->first();

        return view('painel.dashboard', [
            'company' => $company,
            'totais' => $totais,
            'mes' => $mes,
            'serie' => $this->serieMensal(),
            'topFornecedores' => $this->topFornecedores(),
            'ultimasNotas' => NotaFiscal::query()->latest('data_emissao')->limit(8)->get(),
            'ultimasSyncs' => SyncLog::query()->latest()->limit(5)->get(),
        ]);
    }

    /**
     * Volume e valor dos últimos 12 meses, para o gráfico do topo.
     */
    private function serieMensal(): array
    {
        $desde = Carbon::now()->startOfMonth()->subMonths(11);

        $linhas = NotaFiscal::query()
            ->where('data_emissao', '>=', $desde)
            ->selectRaw(Sql::yearMonth('data_emissao').' as competencia')
            ->selectRaw('COUNT(*) as total')
            ->selectRaw('COALESCE(SUM(valor_total), 0) as valor')
            ->groupBy('competencia')
            ->pluck('total', 'competencia');

        $serie = [];

        for ($i = 0; $i < 12; $i++) {
            $mes = $desde->copy()->addMonths($i);
            $serie[] = [
                'label' => $mes->translatedFormat('M/y'),
                'total' => (int) ($linhas[$mes->format('Y-m')] ?? 0),
            ];
        }

        return $serie;
    }

    private function topFornecedores()
    {
        return NotaFiscal::query()
            ->whereNotNull('emit_cnpj')
            ->select('emit_cnpj', 'emit_nome')
            ->selectRaw('COUNT(*) as notas')
            ->selectRaw('COALESCE(SUM(valor_total), 0) as valor')
            ->groupBy('emit_cnpj', 'emit_nome')
            ->orderByDesc(DB::raw('SUM(valor_total)'))
            ->limit(6)
            ->get();
    }
}
