<?php

namespace Daylight\Core\Http\Controllers\Store;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Store\Labels\StoreLabelRequest;
use Daylight\Core\Http\Requests\Store\Labels\UpdateLabelRequest;
use Daylight\Core\Models\Label;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class LabelController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:create:labels', only: ['create', 'store']),
            new Middleware('can:read:labels', only: ['index', 'show']),
            new Middleware('can:update:labels', only: ['edit', 'update']),
            new Middleware('can:delete:labels', only: ['destroy']),
        ];
    }

    public function index(): View
    {
        return view('daylight::store.labels.index');
    }

    public function create(): View
    {
        return view('daylight::store.labels.create');
    }

    public function store(StoreLabelRequest $request)
    {
        $label = (daylightModel('label'))::create($request->safe()->only(['background', 'text_color']));

        collect($request->get('translations'))
            ->each(function ($translation, $locale) use ($label) {
                $label->translations()->create([
                    'locale' => $locale,
                    ...$translation,
                ]);
            });

        return redirect()->route('daylight.store.labels.edit', ['label' => $label, 'locale' => $request->get('locale')])
            ->with('success', __('daylight::store.label_created'));
    }

    public function edit(Label $label)
    {
        return view('daylight::store.labels.edit', [
            'label' => $label,
        ]);
    }

    public function update(UpdateLabelRequest $request, Label $label)
    {
        $label->update($request->safe()->only(['background', 'text_color']));

        collect($request->get('translations'))
            ->each(function ($translation, $locale) use ($label) {
                $label->translations()->updateOrCreate([
                    'locale' => $locale,
                ], $translation);
            });

        return redirect()->route('daylight.store.labels.edit', $label)
            ->with('success', __('daylight::store.label_updated'));
    }

    public function destroy(Label $label)
    {
        $label->delete();

        return redirect()->route('daylight.store.labels.index')
            ->with('success', __('daylight::store.label_deleted'));
    }
}
