<?php

namespace App\Repositories;

use App\Models\Module;
use App\Models\Resource;
use Illuminate\Support\Str;
use App\Models\ResourcePermission;
use Illuminate\Support\Facades\DB;
use App\Models\ResourceConfiguration;

class ChartRepository
{
    public function store()
    {
        $session = session()->get('chart_session_wizard_configuration');
        DB::transaction(function () use ($session) {
            $resource = Resource::create([
                'name'                => $session["name"],
                'url'                 => $this->getUrl(Str::slug($session["name"], '_')),
                'access_control_type' => ucfirst($session["security_type"]),
                'module_id'           => $this->getChartModuleId(),
                'category_id'         => intval($session["category"]),
                'resource_creator'    => auth()->id(),
                'data_connection_id'  => strtolower($session["connection"]) != "default" ? intval($session["connection"]) : null,
                'widget_size'         => $this->widgetSize($session["widget_size"])
            ]);

            if (!is_null($session["groups"])) {

                if (auth()->user()->isAdminOrOwner()) {

                    foreach ($session["groups"] as $group) {
                        ResourcePermission::create([
                            'group_id'    => $group,
                            'resource_id' => $resource->id,
                            'can_view'    => true
                        ]);

                    }

                } else {
                    ResourcePermission::create([
                        'group_id'    => auth()->user()->group->group_ID,
                        'resource_id' => $resource->id,
                        'can_view'    => true
                    ]);

                }

            }

            ResourceConfiguration::create([
                'Resource_id'         => $resource->id,
                'Json_configurations' => $session,
                'chart_type'          => $session["chart_type"]
            ]);
            session()->forget('chart_session_wizard_configuration');

        });
    }

    public function update($chart)
    {
        $session = session()->get('chart_session_wizard_configuration');
        DB::transaction(function () use ($session, $chart) {

            $resource = $chart->update([
                'name'                => isset($session["name"]) ? $session["name"] : $chart->name,
                'url'                 => isset($session["name"]) ? $this->getUrl(Str::slug($session["name"], '_')) : $chart->url,
                'access_control_type' => isset($session["security_type"]) ? ucfirst($session["security_type"]) : $chart->access_control_type,
                'module_id'           => $this->getChartModuleId(),
                'category_id'         => isset($session["category"]) ? intval($session["category"]) : $chart->category_id,
                'widget_size'         => isset($session["widget_size"]) ? $this->widgetSize($session["widget_size"]) : $chart->widget_size
            ]);

            if (isset($session["groups"])) {

                ResourcePermission::where('resource_id', $chart->id)->delete();

                if (auth()->user()->isAdminOrOwner()) {

                    foreach ($session["groups"] as $group) {

                        ResourcePermission::create([
                            'group_id'    => $group,
                            'resource_id' => $chart->id,
                            'can_view'    => true
                        ]);

                    }

                } else {
                    ResourcePermission::create([
                        'group_id'    => auth()->user()->group->group_ID,
                        'resource_id' => $chart->id,
                        'can_view'    => true
                    ]);

                }

            }

            ResourceConfiguration::updateOrCreate(
                ['Resource_id' => $chart->id],
                [
                    'Json_configurations' => $this->getUpdatedSession($session, $chart),
                    'chart_type'          => isset($session["chart_type"]) ? $session["chart_type"] : $chart->getResourceConfiguration("chart_type")

                ]
            );
            session()->forget('chart_session_wizard_configuration');
        });
    }

    private function getChartModuleId()
    {
        return Module::where('name', 'Charts')->first()->id;
    }

    private function widgetSize($size)
    {

        switch ($size) {
            case 'full':
                return 1;
                break;
            case 'half':
                return 2;
                break;
            case 'quarter':
                return 3;
                break;
        }

    }

    private function getUrl($chartName)
    {
        return substr(getBaseUrl(), -1) == "/"
        ? getBaseUrl() . "srm_charts/" . $chartName
        : getBaseUrl() . "/srm_charts/" . $chartName;
    }

    private function getUpdatedSession($session, $chart)
    {
        return array_merge($chart->configurations->Json_configurations, $session);
    }

}
