<?php

namespace App\Livewire\Forms\Studio\Feature;

use App\Models\ChooseUs;
use Livewire\Form;

class ChooseUsForm extends Form
{
    public ?ChooseUs $chooseUs = null;

    public string $name = '';

    public string $description = '';

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'description' => ['required', 'string'],
        ];
    }

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

    public function setChooseUs(ChooseUs $chooseUs)
    {
        $this->chooseUs = $chooseUs;

        $this->name = $chooseUs->name;
        $this->description = $chooseUs->description;
    }

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

        ChooseUs::create([
            'name' => $this->name,
            'description' => $this->description,
            'sort_order' => ChooseUs::count() + 1,
        ]);
    }

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

        $this->chooseUs->update([
            'name' => $this->name,
            'description' => $this->description,
        ]);
    }

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

        ChooseUs::where('sort_order', '>', $this->chooseUs->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 = ChooseUs::where('sort_order', '<', $this->chooseUs->sort_order)
                    ->orderByDesc('sort_order')
                    ->first();
            } else {
                $swap = ChooseUs::where('sort_order', '>', $this->chooseUs->sort_order)
                    ->orderBy('sort_order')
                    ->first();
            }

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

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