<?php

namespace App\Livewire\Forms\Studio\Catalog;

use App\Models\Brand;
use App\Traits\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class BrandForm extends Form
{
    use WithMediaHandler;

    public ?Brand $brand = null;

    public string $name = '';

    public array $image = [];

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:20', Rule::unique('categories', 'name')->whereNull('deleted_at')->ignore($this->brand)],
            'image' => ['nullable', 'array'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'image' => 'gambar',
        ];
    }

    public function setBrand(Brand $brand)
    {
        $this->brand = $brand;

        $this->name = $brand->name;

        $this->image = $this->mapMediaCollection($brand->getMedia('image'));
    }

    public function store()
    {
        $this->validate();

        DB::transaction(function () {
            $brand = Brand::create([
                'name' => $this->name,
                'sort_order' => Brand::count() + 1,
            ]);

            $this->uploadMedia($this->image, $brand, 'image');
        });
    }

    public function update()
    {
        $this->validate();

        DB::transaction(function () {
            $this->brand->update([
                'name' => $this->name,
            ]);

            $this->syncMedia($this->image, $this->brand, 'image');
            $this->uploadMedia($this->image, $this->brand, 'image');
        });
    }

    public function delete()
    {
        $this->brand->delete();

        Brand::where('sort_order', '>', $this->brand->sort_order)
            ->orderBy('sort_order')
            ->get()
            ->each(function ($cat) {
                $cat->update(['sort_order' => $cat->sort_order - 1]);
            });
    }

    public function sortOrder(string $direction)
    {
        if (in_array($direction, ['up', 'down'])) {
            $swap = null;

            if ($direction === 'up') {
                $swap = Brand::where('sort_order', '<', $this->brand->sort_order)
                    ->orderByDesc('sort_order')
                    ->first();
            } else {
                $swap = Brand::where('sort_order', '>', $this->brand->sort_order)
                    ->orderBy('sort_order')
                    ->first();
            }

            if ($swap) {
                $temp = $this->brand->sort_order;
                $this->brand->update(['sort_order' => $swap->sort_order]);
                $swap->update(['sort_order' => $temp]);
            }
        } elseif ($direction === 'first') {
            $this->brand->update(['sort_order' => Brand::min('sort_order') - 1]);
            $this->normalizeSortOrder();
        } elseif ($direction === 'last') {
            $this->brand->update(['sort_order' => Brand::max('sort_order') + 1]);
            $this->normalizeSortOrder();
        }
    }

    protected function normalizeSortOrder()
    {
        $categories = Brand::orderBy('sort_order')->get();
        foreach ($categories as $index => $brand) {
            $brand->update(['sort_order' => $index + 1]);
        }
    }
}
