<?php

namespace App\Livewire\Forms\Studio\Loyalty;

use App\Models\Tier;
use App\Rules\UnsignedInteger;
use Livewire\Form;

class TierForm extends Form
{
    public ?Tier $tier = null;

    public string $name = '';

    public string $min_points = '';

    public ?string $max_points = null;

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'min_points' => ['required', new UnsignedInteger],
            'max_points' => ['nullable', new UnsignedInteger],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'min_points' => 'min. poin',
            'max_points' => 'maks. poin',
        ];
    }

    public function setTier(Tier $tier)
    {
        $this->tier = $tier;

        $this->name = $tier->name;
        $this->min_points = $tier->min_points;
        $this->max_points = $tier->max_points;
    }

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

        return Tier::create($this->prepareSavedData());
    }

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

        $this->tier->update($this->prepareSavedData());

        return $this->tier;
    }

    private function prepareSavedData()
    {
        return [
            'name' => $this->name,
            'min_points' => replaceCurrency($this->min_points),
            'max_points' => replaceCurrency($this->max_points),
        ];
    }
}
