<?php

namespace App\Services;

use App\Models\Bien;
use App\Models\Prestamo;
use App\Models\RegistroStock;
use App\Models\TipoInsumo;

class DashboardService
{
    /**
     * @return array<string, mixed>
     */
    public function buildDashboardData(): array
    {
        $tiposMap = TipoInsumo::query()->pluck('nombre', 'id')->toArray();

        $categoryRows = Bien::query()
            ->selectRaw('tipo, COUNT(*) as total, SUM(cantidadUnidadUtil) as stock')
            ->groupBy('tipo')
            ->get();

        $catLabels = [];
        $catData = [];
        $totalStock = 0;
        $activeCategories = 0;

        foreach ($categoryRows as $row) {
            $tipo = (int) $row->tipo;
            $stock = (int) ($row->stock ?? 0);

            $catLabels[] = $tiposMap[$tipo] ?? 'Otro';
            $catData[] = $stock;
            $totalStock += $stock;
            if ($stock > 0) {
                $activeCategories++;
            }
        }

        $dates = [];
        $loads = [];
        $unloads = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i);
            $dates[] = $date->format('d M');

            $loads[] = (int) RegistroStock::query()
                ->whereDate('fechaOperacion', $date->toDateString())
                ->sum('cantidad');

            $unloads[] = (int) Prestamo::query()
                ->whereDate('fechaEntrega', $date->toDateString())
                ->sum('cantidad');
        }

        return [
            'catLabels' => $catLabels,
            'catData' => $catData,
            'dates' => $dates,
            'loads' => $loads,
            'unloads' => $unloads,
            'totalStock' => $totalStock,
            'activeCategories' => $activeCategories,
            'totalLoads7d' => array_sum($loads),
            'totalUnloads7d' => array_sum($unloads),
        ];
    }
}
