<?php

namespace App\Repositories;

use App\Models\User;
use App\Models\Resource;
use App\Models\HomeDashboard;

class HomeRepository
{
    public function store($request)
    {
        HomeDashboard::create(
            [
                'user_id'      => auth()->user()->user_ID,
                'resource_id'  => $this->getResourceId($request),
                'report_lists' => $this->getReportLists($request),
                'widget_title' => $this->getWidgetTitle($request)

            ]
        );
    }

    public function update($request, $widget)
    {
        $widget->update([
            // 'resource_id' => $this->getResourceId($request),
            'report_lists' => $this->getReportLists($request),
            'widget_title' => $this->getWidgetTitle($request)
        ]);
    }

    private function getResourceId($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() == "Blank Reports") {
            return null;
        } else {
            return $request->resource;
        }

    }

    private function getReportLists($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() != "Blank Reports") {
            return null;
        }

        $resourcesArray = [];

        if (is_array($request->resource)) {

            foreach ($request->resource as $resource) {
                $resourcesArray[] = $this->buildResourceArray($resource);
            }

        }

        return $resourcesArray;
    }

    private function buildResourceArray($resourceId)
    {
        $resource = Resource::where('id', $resourceId)->first();

        return [
            'id'    => $resource->id,
            'name'  => $resource->name,
            'title' => $resource->getResourceConfiguration('title'),
            'url'   => $resource->url
        ];
    }

    private function getWidgetTitle($request)
    {
        $resourceType = Resource::where('id', $request->resource)->first();

        if (isset($resourceType) && $resourceType->getResourceType() != "Blank Reports") {
            return null;
        } else {
            return $request->title;
        }

    }

}
