<?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\Models\Page;
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', [
            'pages' => $this->getPagesList(),
        ]);
    }

    public function store(StoreBrandRequest $request)
    {
        $brand = (daylightModel('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', __('daylight::store.brand_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(),
            'pages' => $this->getPagesList(),
        ]);
    }

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

        $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'])
        );

        //        if ($request->components) {
        //            $this->syncComponentsFromRequest($request, $translation);
        //        }

        app(\Daylight\Core\Modules\PageBuilder\Services\ComponentSyncService::class)->sync(
            $request->getComponentsFromRequest(),
            $translation
        );

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

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

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

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

    private function getPagesList(): Collection
    {
        return Page::query()
            ->with(['defaultTranslation', 'translations'])
            ->get();
    }
}
