<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Stock;
use App\Models\Supplier;
use App\Models\Equipment;
use App\Models\MovementStock;
use App\Models\Request as RequestModel;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        if ($user->hasRole('Responsable du département') && $user->department_id) {
            return $this->dashboardResponsable($user);
        }

        return $this->dashboardStandard();
    }

    protected function dashboardResponsable($user)
    {
        $deptId = $user->department_id;
        $requestBase = RequestModel::whereDeletedAt(null)->where('department_id', $deptId);

        return view('dashboard', [
            'isResponsable' => true,
            'pendingRequests' => (clone $requestBase)->where('status', 'en_attente')->count(),
            'validatedRequests' => (clone $requestBase)->where('status', 'validée')->count(),
            'rejectedRequests' => (clone $requestBase)->where('status', 'rejetée')->count(),
            'totalRequests' => (clone $requestBase)->count(),
            'equipmentCount' => Equipment::whereDeletedAt(null)->where('department_id', $deptId)->count(),
        ]);
    }

    protected function dashboardStandard()
    {
        $requestModel = RequestModel::class;

        return view('dashboard', [
            'isResponsable' => false,
            'totalProducts' => Product::count(),
            'totalStock' => Stock::sum('actual_quantity'),
            'pendingRequests' => $requestModel::where('status', 'en_attente')->whereDeletedAt(null)->count(),
            'movementsToday' => MovementStock::whereDate('created_at', today())->count(),
            'validatedRequests' => $requestModel::where('status', 'validée')->whereDeletedAt(null)->count(),
            'rejectedRequests' => $requestModel::where('status', 'rejetée')->whereDeletedAt(null)->count(),
            'suppliersCount' => Supplier::count(),
            'equipmentCount' => Equipment::whereDeletedAt(null)->count(),
        ]);
    }
}
