<?php

namespace App\Services;

use App\Models\DashboardWidget;
use App\Repositories\DashboardWidgetRepository;

class DashboardWidgetService
{
    private $homeService;
    private $dashboardWidgetRepository;

    public function __construct(DashboardWidgetRepository $dashboardWidgetRepository, HomeService $homeService)
    {
        $this->homeService               = $homeService;
        $this->dashboardWidgetRepository = $dashboardWidgetRepository;

    }

    public function store($request, $dashboard)
    {
        $this->dashboardWidgetRepository->store($request, $dashboard);
    }

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

    public function destroy($dashboard, $widget)
    {
        $this->dashboardWidgetRepository->destroy($dashboard, $widget);

    }

    public function checkAccess($dashboard)
    {

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

    }

    private function getWidgetsByPage()
    {
        return config('srm_config.dashboard.max_dashboard_widgets', 20);
    }

    private function getNumberOfPages($request, $dashboard)
    {
        $widgetsPerPage = $this->getWidgetsByPage();
        return $dashboard->widgets()->paginate($widgetsPerPage);
    }

    public function getDashboardLastPage($request, $dashboard)
    {
        return $this->getNumberOfPages($request, $dashboard)->lastPage();
    }

    public function getRecentWidget($dashboard)
    {
        return DashboardWidget::where('dashboard_id', $dashboard->id)
            ->with('resource')
            ->orderBy('created_at', 'desc')
            ->first();
    }

}