<?php

namespace App\Http\Controllers;

use App\Models\InventoryItem;
use Illuminate\Support\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $totalItems = InventoryItem::count();
        $brokenItems = InventoryItem::where('status_barang', 'broken')->count();
        $maintenanceItems = InventoryItem::where('status_barang', 'maintenance')
            ->orWhereDate('tanggal_jadwal_pemeliharaan', '<=', Carbon::now()->addDays(30))
            ->count();
        $replacementItems = InventoryItem::where('status_barang', 'replace')
            ->orWhere('pengajuan_penggantian', true)
            ->count();

        $stats = [
            ['label' => 'Total Barang', 'value' => number_format($totalItems, 0, ',', '.'), 'description' => 'Aset aktif tercatat di database', 'icon' => 'boxes', 'tone' => 'navy'],
            ['label' => 'Barang Rusak', 'value' => number_format($brokenItems, 0, ',', '.'), 'description' => 'Perlu verifikasi petugas lapangan', 'icon' => 'triangle-alert', 'tone' => 'red'],
            ['label' => 'Perlu Pemeliharaan', 'value' => number_format($maintenanceItems, 0, ',', '.'), 'description' => 'Jatuh tempo dalam 30 hari', 'icon' => 'calendar-clock', 'tone' => 'amber'],
            ['label' => 'Perlu Diganti', 'value' => number_format($replacementItems, 0, ',', '.'), 'description' => 'Menunggu tindak lanjut admin', 'icon' => 'replace', 'tone' => 'violet'],
        ];

        $inventoryItems = InventoryItem::with(['category', 'room'])->latest()->limit(8)->get();
        $conditionCounts = InventoryItem::selectRaw('status_barang, count(*) as total')->groupBy('status_barang')->pluck('total', 'status_barang');
        $conditionChart = collect([
            ['label' => 'Baik', 'status' => 'good', 'class' => 'good'],
            ['label' => 'Perawatan', 'status' => 'maintenance', 'class' => 'maintenance'],
            ['label' => 'Rusak', 'status' => 'broken', 'class' => 'broken'],
            ['label' => 'Ganti', 'status' => 'replace', 'class' => 'replace'],
        ])->map(function (array $condition) use ($conditionCounts, $totalItems) {
            $count = $conditionCounts[$condition['status']] ?? 0;
            $condition['value'] = $totalItems > 0 ? (int) round(($count / $totalItems) * 100) : 0;
            $condition['count'] = $count;

            return $condition;
        });

        return view('dashboard', compact(
            'stats',
            'inventoryItems',
            'conditionChart'
        ));
    }
}
