parfum/app/Livewire/Forms/Studio/Loyalty/RewardForm.php

92 lines
2.4 KiB
PHP

<?php
namespace App\Livewire\Forms\Studio\Loyalty;
use App\Models\Reward;
use App\Rules\UnsignedInteger;
use App\Traits\Media\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Livewire\Form;
class RewardForm extends Form
{
use WithMediaHandler;
public ?Reward $reward = null;
public string $name = '';
public string $points = '';
public ?string $stock = null;
public string $how_to_get = '';
public array $thumbnail = [];
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:100'],
'points' => ['required', new UnsignedInteger],
'stock' => ['nullable', new UnsignedInteger],
'how_to_get' => ['required', 'string'],
'thumbnail' => 'array',
];
}
public function validationAttributes(): array
{
return [
'name' => 'nama',
'points' => 'poin',
'stock' => 'stok',
'how_to_get' => 'cara mendapatkan',
];
}
public function setReward(Reward $reward): void
{
$this->reward = $reward;
$this->name = $reward->name;
$this->points = formatCurrencyNumber($reward->points);
$this->stock = formatCurrencyNumber($reward->stock);
$this->how_to_get = $reward->how_to_get ?? '';
$this->thumbnail = $this->mapMediaCollection($reward->getMedia('thumbnail'));
}
public function store(): void
{
$this->validate();
DB::transaction(function () {
$reward = Reward::create([
'name' => $this->name,
'points' => parseRupiahToInt($this->points),
'stock' => parseRupiahToInt($this->stock),
'how_to_get' => $this->how_to_get,
]);
$this->uploadMedia($this->thumbnail, $reward, 'thumbnail');
});
}
public function update(): void
{
$this->validate();
DB::transaction(function () {
$this->reward->update([
'name' => $this->name,
'points' => parseRupiahToInt($this->points),
'stock' => $this->stock ? parseRupiahToInt($this->stock) : null,
'how_to_get' => $this->how_to_get,
]);
$this->syncMedia($this->thumbnail, $this->reward, 'thumbnail');
$this->uploadMedia($this->thumbnail, $this->reward, 'thumbnail');
});
}
}