<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Sale;
use App\Models\SaleItem;
use App\Models\Partner;
use App\Models\Product;
use App\Models\Inventory;

class Dashboard extends Component
{
    public $todaySales = 0; // Keeping original var names ? No, earlier it was 'todaysSales'
    public $todaysSales = 0;
    public $productsSold = 0;
    public $totalCustomers = 0;
    public $lowStockItems = 0;
    public $recentSales = [];

    public function mount()
    {
        $this->fetchStats();
    }

    public function fetchStats()
    {
        $today = now()->startOfDay();

        // Today's Sales Amount
        $this->todaysSales = Sale::whereDate('created_at', $today)->sum('total');

        // Products Sold Today (Quantity)
        $this->productsSold = SaleItem::whereHas('sale', function ($query) use ($today) {
            $query->whereDate('created_at', $today);
        })->sum('quantity');

        // Total Customers
        $this->totalCustomers = Partner::customers()->count();

        // Low Stock Items
        $this->lowStockItems = Product::active()
            ->join('inventory', 'products.id', '=', 'inventory.product_id')
            ->whereColumn('inventory.quantity', '<=', 'products.min_stock_level')
            ->count();

        // Recent Sales
        $this->recentSales = Sale::with('partner')->latest()->take(5)->get();
    }

    public function render()
    {
        return view('livewire.dashboard')->layout('layouts.app');
    }
}
