<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\AssetStatus;
use Facades\App\Repositories\Dashboard\DashboardRepository;
use App\Services\Dashboard\DashboardService;
use Carbon\Carbon;
use App\Models\AssetType;
use App\User;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    protected $dashboardService;

    public function __construct(DashboardService $dashboardService)
    {
        $this->dashboardService = $dashboardService;
    }

    public function index()
    {
        $count = [];
        $donutAllStatusData = [];
        $donutSelectedStatusData = [];

        $user = User::with('userType')->find(Auth::id());
        if ($user->hasRole('Employee')) {
            return redirect(route('my-teq-assets'));
        }

        $count = $this->dashboardService->getAssetCounts();

        $assetStatuses = AssetStatus::withCount('assets')->orderBy('slug')->get();

        foreach ($assetStatuses as $status) {

            $count[$status->slug] = $status->assets_count;

            $donutAllStatusData[] = ['label' => $status->name, 'value' => $count[$status->slug]];

            if (in_array($status->slug, ['assigned', 'installed', 'loaned'])) {
                $donutSelectedStatusData[] = ['label' => $status->name, 'value' => $count[$status->slug]];
            }
        }

        $months = generateRecentYearMonthsArrayWithMonthNumber();
        $monthNames = generateRecentMonthsArray();
        $assetLineGraphData = DashboardRepository::getAssetCreated($months);

        $regionCount = $this->dashboardService->getAssetsInRegionCount();

        $assetTypes = AssetType::withCount('assets')->get();

        $computersWidgetData = $this->dashboardService->getcomputerWidgetdata();

        return view('dashboard.index', compact('count', 'monthNames', 'assetLineGraphData', 'donutAllStatusData', 'donutSelectedStatusData', 'regionCount', 'assetTypes', 'assetStatuses', 'computersWidgetData'));
    }
}
