<?php

namespace App\Services;

use App\Models\Resource;
use App\Models\Dashboard;
use App\Repositories\DashboardRepository;

class DashboardService
{
    private $dashboardRepository;
    private $homeService;
    public function __construct(DashboardRepository $dashboardRepository, HomeService $homeService)
    {
        $this->homeService         = $homeService;
        $this->dashboardRepository = $dashboardRepository;

    }

    public function index()
    {
        return Dashboard::where('user_id', auth()->user()->user_ID)
            ->orderBy('order', 'asc')->withCount('widgets')->get();
    }

    public function show($dashboard)
    {
        $this->checkAccess($dashboard);

        $numberOfDashboardWidgets = config('srm_config.dashboard.max_dashboard_widgets', 20);

        $paginatedWidgets = $dashboard->widgets()->paginate($numberOfDashboardWidgets);

        foreach ($paginatedWidgets as $widget) {

            if (isset($widget->resource_id)) {
                $this->homeService->buildResource($widget->resource);
            }

        }

        return [$dashboard, $paginatedWidgets];
    }

    public function store($request)
    {
        $this->dashboardRepository->store($request);
    }

    public function update($request, $dashboard)
    {
        $this->dashboardRepository->update($request, $dashboard);
    }

    public function moveUp($dashboard)
    {
        $this->dashboardRepository->moveUp($dashboard);
    }

    public function moveDown($dashboard)
    {
        $this->dashboardRepository->moveDown($dashboard);

    }

    public function destory($dashboard)
    {
        $this->dashboardRepository->destory($dashboard);

    }

    public function checkAccess($dashboard)
    {

        if ($dashboard->user_id != auth()->user()->user_ID) {
            abort(403, 'Access denied');
        }

    }

    public function getRecentDashboard()
    {
        return $this->dashboardRepository->getRecentDashboard();
    }

}