Files
eatvio-infra/app/Livewire/Diet/DayEdit.php
2023-10-04 17:57:09 +03:00

87 lines
2.4 KiB
PHP

<?php
namespace App\Livewire\Diet;
use Livewire\Component;
class DayEdit extends Component
{
public $day;
public $eatingTypes = ['breakfast', 'dinner', 'supper', 'lunch', 'snacks'];
public $activeType = 'breakfast';
public $portions = [];
public $name = "";
public $quantity = 0;
public $portion = "gram";
protected $listeners = ['takePaste'];
protected $rules = [
'name' => 'required|min:3',
'quantity' => 'required|numeric|min:1',
'portion' => 'required|min:3',
];
public function render()
{
return view('livewire.diet.day-edit');
}
public function addPortion($type)
{
$this->validate();
$newData = [
'name' => $this->name,
'quantity' => $this->quantity,
'portion' => $this->portion,
'uniq' => $this->name . "-" . time()
];
$this->portions[$type][] = $newData;
$this->reset(['name', 'quantity', 'portion']);
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
public function delete($uniq, $type)
{
$newPortions = collect($this->portions[$type])
->filter(function($item) use ($uniq) {
return $item['uniq'] != $uniq;
}
);
$this->portions[$type] = $newPortions->toArray();
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
public function edit($uniq, $type)
{
$elemKey = collect($this->portions[$type])
->search(function($item) use ($uniq) {
return $item['uniq'] == $uniq;
});
if ($elemKey !== false) {
$item = $this->portions[$type][$elemKey];
$this->fill([
'name' => $item['name'],
'quantity' => $item['quantity'],
'portion' => $item['portion']
]);
$this->delete($item['uniq'], $type);
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
}
public function takePaste($day, $data)
{
if (intval($day) === intval($this->day)) {
foreach($data as $type => $props) {
$this->portions[$type] = $props;
}
$this->dispatch('dayUpdated', dayIndex: $this->day, data: $this->portions);
}
}
}