forked from eatvio/eatvio-infra
121 lines
2.8 KiB
PHP
121 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Diet;
|
|
|
|
use App\Models\Diet;
|
|
use Illuminate\Contracts\View\Factory as ViewFactory;
|
|
use Illuminate\Contracts\View\View;
|
|
use Livewire\Component;
|
|
|
|
class Edit extends Component
|
|
{
|
|
public Diet $diet;
|
|
|
|
public string $name = '';
|
|
|
|
public string $image;
|
|
|
|
public int $duration = 7;
|
|
|
|
public string $state = 'draft';
|
|
|
|
public array $type = [];
|
|
|
|
public string $details = '';
|
|
|
|
public array $days = [];
|
|
|
|
public int $copyedDay;
|
|
|
|
public array $copyedDayData;
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $listeners = ['dayUpdated', 'makeCopy', 'makePaste'];
|
|
|
|
public function mount(Diet $diet): void
|
|
{
|
|
$this->name = $diet->name;
|
|
$this->image = $diet->image;
|
|
$this->duration = $diet->duration;
|
|
$this->state = $diet->state;
|
|
$this->type = json_decode($diet->type, true);
|
|
$this->details = $diet->details;
|
|
$this->days = json_decode($diet->daily_schedule, true);
|
|
}
|
|
|
|
public function render(): View|ViewFactory
|
|
{
|
|
return view('livewire.diet.edit');
|
|
}
|
|
|
|
public function dayUpdated(int $dayIndex, array $data): void
|
|
{
|
|
$this->days[$dayIndex] = $data;
|
|
}
|
|
|
|
public function showPreview(): void
|
|
{
|
|
$this->state = 'draft';
|
|
$this->publish();
|
|
}
|
|
|
|
public function addToDrafts(): void
|
|
{
|
|
$this->state = 'draft';
|
|
$this->publish();
|
|
}
|
|
|
|
public function makeCopy(int $day): void
|
|
{
|
|
/* dd($day); */
|
|
$this->copyedDay = $day;
|
|
}
|
|
|
|
public function makePaste(int $copyToDay): void
|
|
{
|
|
$data = $this->days[$this->copyedDay];
|
|
$this->dispatch(
|
|
'takePaste',
|
|
day: $copyToDay,
|
|
data: $data
|
|
)->to('diet.day-edit');
|
|
}
|
|
|
|
public function publish(): void
|
|
{
|
|
$this->validate();
|
|
|
|
$diet = $this->diet;
|
|
|
|
$diet->name = $this->name;
|
|
/* $diet->image = $this->image->store('diets', 'public'); */
|
|
$diet->duration = $this->duration;
|
|
$diet->state = $this->state;
|
|
$diet->type = json_encode($this->type);
|
|
$diet->details = $this->details;
|
|
$diet->daily_schedule = json_encode($this->days);
|
|
$diet->save();
|
|
|
|
/* $user = Auth::user(); */
|
|
/* $user->author_of_diets()->attach($diet->id); */
|
|
|
|
// return redirect()->route('diet.show', $diet->id);
|
|
|
|
$this->redirectRoute('diet.show', $diet->id);
|
|
}
|
|
|
|
protected function rules(): array
|
|
{
|
|
return [
|
|
'name' => 'required|min:3',
|
|
/* 'image' => 'required|image|max:2048', */
|
|
'duration' => 'required|numeric|min:7',
|
|
'state' => 'required|in:draft,active,inactive',
|
|
'type' => ['required', 'array:meat,veg,corb,alko', 'min:1'],
|
|
'details' => 'required|min:3',
|
|
];
|
|
}
|
|
}
|