<?php

namespace App\Livewire\Inventory;

use App\Models\Part;
use App\Models\PurchaseOrder;
use App\Models\StockMovement;
use App\Models\Supplier;
use Livewire\Component;

class Dashboard extends Component
{
    public function render()
    {
        // Get key inventory metrics
        $totalParts = Part::count();
        $lowStockParts = Part::lowStock()->count();
        $outOfStockParts = Part::outOfStock()->count();
        $totalStockValue = Part::selectRaw('SUM(quantity_on_hand * cost_price) as total')->value('total') ?? 0;
        
        // Get recent stock movements
        $recentMovements = StockMovement::with(['part', 'createdBy'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();
        
        // Get pending purchase orders
        $pendingOrders = PurchaseOrder::with('supplier')
            ->whereIn('status', ['pending', 'ordered'])
            ->orderBy('order_date', 'desc')
            ->limit(5)
            ->get();
        
        // Get low stock parts
        $lowStockPartsList = Part::with('supplier')
            ->lowStock()
            ->orderBy('quantity_on_hand', 'asc')
            ->limit(10)
            ->get();

        // Get stock by category
        $stockByCategory = Part::selectRaw('category, SUM(quantity_on_hand * cost_price) as total_value')
            ->groupBy('category')
            ->orderBy('total_value', 'desc')
            ->get();        // Get top suppliers by parts count
        $topSuppliers = Supplier::withCount('parts')
            ->having('parts_count', '>', 0)
            ->orderBy('parts_count', 'desc')
            ->limit(5)
            ->get();

        return view('livewire.inventory.dashboard', [
            'totalParts' => $totalParts,
            'lowStockParts' => $lowStockParts,
            'outOfStockParts' => $outOfStockParts,
            'totalStockValue' => $totalStockValue,
            'recentMovements' => $recentMovements,
            'pendingOrders' => $pendingOrders,
            'lowStockPartsList' => $lowStockPartsList,
            'stockByCategory' => $stockByCategory,
            'topSuppliers' => $topSuppliers,
        ]);
    }
}
