<?php

namespace App\Http\Controllers\Master;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\DfePendente;
use App\Models\NotaFiscal;
use App\Models\SyncLog;
use App\Models\User;
use App\Support\Sql;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function __invoke(): View
    {
        $desde = Carbon::now()->startOfMonth()->subMonths(11);

        $porMes = NotaFiscal::withoutGlobalScopes()
            ->where('data_emissao', '>=', $desde)
            ->selectRaw(Sql::yearMonth('data_emissao').' as competencia')
            ->selectRaw('COUNT(*) as total')
            ->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) ($porMes[$mes->format('Y-m')] ?? 0),
            ];
        }

        return view('master.dashboard', [
            'empresas' => Company::count(),
            'empresasAtivas' => Company::ativas()->count(),
            'monitorAtivo' => Company::comMonitor()->whereNotNull('cert_path')->count(),
            'usuarios' => User::whereNot('role', User::ROLE_MASTER)->count(),
            'notas' => NotaFiscal::withoutGlobalScopes()->count(),
            'notasMes' => NotaFiscal::withoutGlobalScopes()
                ->where('data_emissao', '>=', Carbon::now()->startOfMonth())
                ->count(),
            'valorTotal' => NotaFiscal::withoutGlobalScopes()->sum('valor_total'),
            'serie' => $serie,
            'certificadosVencendo' => Company::ativas()
                ->whereNotNull('cert_valid_to')
                ->whereBetween('cert_valid_to', [now(), now()->addDays(30)])
                ->orderBy('cert_valid_to')
                ->get(),
            'pendentes' => DfePendente::withoutGlobalScopes()
                ->with('company')
                ->abertos()
                ->latest()
                ->limit(8)
                ->get(),
            'totalPendentes' => DfePendente::withoutGlobalScopes()->abertos()->count(),
            'ultimosErros' => SyncLog::withoutGlobalScopes()
                ->with('company')
                ->where('status', 'error')
                ->latest()
                ->limit(8)
                ->get(),
            'topEmpresas' => Company::query()
                ->withCount('notasFiscais')
                ->orderByDesc('notas_fiscais_count')
                ->limit(6)
                ->get(),
        ]);
    }
}
