<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Inertia\Inertia;

class DashboardController extends Controller
{
    public function index()
    {
        $totalProducts = \App\Models\Product::count();
        $todaySales = \App\Models\Sale::whereDate('date', today())->sum('total');
        $totalProfit = \App\Models\Sale::join('products', 'sales.product_id', '=', 'products.id')
            ->selectRaw('SUM((products.selling_price - products.cost_price) * sales.quantity) as profit')
            ->value('profit') ?? 0;

        $todayIncome = $todaySales + \App\Models\Repair::whereDate('date', today())->where('status', 'done')->sum('charge_amount');
        $totalExpense = \App\Models\SecondHandBuy::sum('buy_price') + \App\Models\Tool::where('type', 'buy')->sum('price');
        $pendingRepairs = \App\Models\Repair::where('status', 'pending')->count();

        return Inertia::render('Admin/Pages/Dashboard', [
            'stats' => [
                'total_products' => $totalProducts,
                'today_income' => (float) $todayIncome,
                'total_profit' => (float) $totalProfit,
                'total_expense' => (float) $totalExpense,
                'pending_repairs' => $pendingRepairs,
            ],
        ]);
    }
}
