<?php

namespace Daylight\Core\Http\Controllers\Store;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Store\Variants\UpdateVariantRequest;
use Daylight\Core\Models\Variant;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

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

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

    public function edit(Variant $variant): View
    {
        return view('daylight::store.variants.edit', [
            'variant' => $variant,
        ]);
    }

    public function update(UpdateVariantRequest $request, Variant $variant)
    {
        $gallery = collect($request->get('gallery'))->mapWithKeys(function ($media, $order) {
            return [$media['id'] => [
                'order' => $order,
            ]];
        });

        $variant->media()->sync($gallery);

        $variant->update($request->safe()->only([
            'video_url',
        ]));

        if ($variant->product) {
            $variant->product->searchable();
        }

        return redirect()
            ->route('daylight.store.variants.edit', $variant)
            ->with('success', __('Variant has been updated.'));
    }
}
