parfum/app/Livewire/Forms/Studio/Feature/ChooseUsForm.php

116 lines
3.1 KiB
PHP

<?php
namespace App\Livewire\Forms\Studio\Feature;
use App\Models\ChooseUs;
use Illuminate\Support\Facades\DB;
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): void
{
$this->chooseUs = $chooseUs;
$this->name = $chooseUs->name;
$this->description = $chooseUs->description;
}
public function store(): void
{
$this->validate();
DB::transaction(function () {
// Increment all existing choose us items' sort_order
ChooseUs::query()->increment('sort_order');
ChooseUs::create([
'name' => $this->name,
'description' => $this->description,
'sort_order' => 1,
]);
});
}
public function update(): void
{
$this->validate();
$this->chooseUs->update([
'name' => $this->name,
'description' => $this->description,
]);
}
public function delete(): void
{
$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): void
{
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(): void
{
$chooseUss = ChooseUs::orderBy('sort_order')->get();
foreach ($chooseUss as $index => $chooseUs) {
$chooseUs->update(['sort_order' => $index + 1]);
}
}
}