<?php

namespace App\Http\Controllers\Metrics;

use App\Models\Module;
use App\Models\Resource;
use Illuminate\Http\Request;
use App\Services\MetricService;
use App\Services\CategoryService;
use App\Http\Controllers\Controller;
use App\Http\Middleware\OnlyFullVersion;
use App\Http\Requests\UpdateMetricCategoryRequest;

class MetricController extends Controller
{
    public $metricService;
    public $categoryService;
    public function __construct(MetricService $metricService, CategoryService $categoryService)
    {
        $this->metricService   = $metricService;
        $this->categoryService = $categoryService;

        $this->middleware(OnlyFullVersion::class)->only([
            'changeCategory',
            'destroy'
        ]);

    }

    public function index(Request $request)
    {
        $metrics = $this->metricService->index($request);

        $categories = $this->categoryService->getCategories();

        if (isset($request->metricTitle) || isset($request->metricCategory)) {
            $search = true;
        } else {
            $search = false;
        }

        $metricModule = Module::getMetricModule();

        return view('dashboard.metrics.index', compact('metrics', 'categories', 'search', 'metricModule'));
    }

    public function show($metric)
    {
        $metric = $this->metricService->show($metric);

        return view('dashboard.metrics.show', compact('metric'));
    }

    public function getCategories(Resource $metric)
    {
        $categories = $this->categoryService->getCategories();

        return view('dashboard.metrics.change-category', compact('metric', 'categories'));
    }

    public function changeCategory(Resource $metric, UpdateMetricCategoryRequest $request)
    {
        $this->metricService->changeMetricCategory($metric, $request->validated());
        return response()->json([
            'message' => trans('metrics.messages.updated')
        ]);
    }

    public function drill(Resource $metric)
    {
        set_time_limit(300);

        [$data, $keys] = $this->metricService->drill($metric);

        if (is_null(auth()->user()) && strtolower($metric->access_control_type) == "public") {
            return view('dashboard.metrics.drill-public', compact('metric', 'data', 'keys'));
        }

        return view('dashboard.metrics.drill', compact('metric', 'data', 'keys'));
    }

    public function destroy(Resource $metric)
    {
        $this->metricService->destroy($metric);
        return response()->json([
            'message'   => trans('metrics.messages.delete', [
                'metric' => $metric->name
            ]),
            'last_page' => $this->metricService->getMetricLastPage(request())

        ]);
    }

}
