<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Sale;
use App\Models\SaleItem;
use App\Models\Price;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        $today = Carbon::today();

        $omzetHariIni = Sale::whereDate('date_sale', $today)
            ->sum('total');

        $transaksiHariIni = Sale::whereDate('date_sale', $today)
            ->count();

        $produkTerjual = SaleItem::whereDate('created_at', $today)
            ->sum('qty');

        $stokMenipis = Product::where('stock', '<=', 10)
            ->orderBy('stock')
            ->take(5)
            ->get();

        $produkTerlaris = SaleItem::select(
            'product_id',
            DB::raw('SUM(qty) as total_qty')
        )
            ->with('product')
            ->groupBy('product_id')
            ->orderByDesc('total_qty')
            ->take(5)
            ->get();

        $hargaHariIni = Price::with('product')
            ->whereDate('date_price', $today)
            ->take(5)
            ->get();

        return view('dashboard', compact(
            'omzetHariIni',
            'transaksiHariIni',
            'produkTerjual',
            'stokMenipis',
            'produkTerlaris',
            'hargaHariIni'
        ));
    }
}
