<?php

namespace Daylight\Core\Http\Controllers\Store;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Store\Brands\StoreBrandRequest;
use Daylight\Core\Http\Requests\Store\Brands\UpdateBrandRequest;
use Daylight\Core\Models\Brand;
use Daylight\Core\Modules\Multilingualism\Multilingualism;
use Daylight\Core\Modules\PageBuilder\Concerns\InteractsWithPageBuilderRequest;
use Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Collection;
use Illuminate\View\View;

class BrandController extends Controller implements HasMiddleware
{
    use InteractsWithPageBuilderRequest;

    public static function middleware(): array
    {
        return [
            new Middleware('can:create:brands', only: ['create', 'store']),
            new Middleware('can:read:brands', only: ['index', 'show']),
            new Middleware('can:update:brands', only: ['edit', 'update']),
            new Middleware('can:delete:brands', only: ['destroy']),
        ];
    }

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

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

    public function store(StoreBrandRequest $request)
    {
        $brand = Brand::create($request->validated());
        
        Multilingualism::getAvailableLocales()->map(function (string $locale) use ($brand) {
            $brand->translations()->create([
                'locale' => $locale,
                'meta_title' => $brand->name,
            ]);
        });

        return redirect()
            ->route('daylight.store.brands.edit', $brand)
            ->with('success', __('Brand has been created.'));
    }

    public function edit(Brand $brand)
    {
        $translation = $brand->translations()
            ->where('locale', request()->get('locale', app()->getLocale()))
            ->first();

        return view('daylight::store.brands.edit', [
            'brand' => $brand,
            'translation' => $translation,
            'components' => $translation->formattedComponentData ?? [],
            'availableComponents' => $this->getAvailableComponents(),
        ]);
    }

    public function update(UpdateBrandRequest $request, Brand $brand)
    {
        $brand->update([
            'name' => $request->get('name'),
            'color' => $request->get('color'),
        ]);

        $media = collect($request->get('logo'))
            ->mapWithKeys(function ($media, $order) {
                return [$media['id'] => [
                    'order' => $order,
                    'properties' => [
                        'field' => 'gallery',
                    ],
                ]];
            });

        $brand->media()->sync($media);

        $translation = $brand->translations()->updateOrCreate(
            ['locale' => $request->get('locale')],
            $request->safe(['meta_title', 'meta_description', 'robots'])
        );

        $this->syncComponentsFromRequest($request, $translation);

        return redirect()->route('daylight.store.brands.edit', ['brand' => $brand, 'locale' => $request->get('locale')])
            ->with('success', __('Brand updated'));
    }

    public function destroy(Brand $brand)
    {
        $brand->delete();

        return redirect()->route('daylight.store.brands.index')
            ->with('success', __('Brand has been deleted.'));
    }

    private function getAvailableComponents(): Collection
    {
        return app(ComponentRegistry::class)
            ->availableFor(Brand::class)
            ->map(fn($component) => $component->toArray())
            ->values();
    }
}
