<?php

namespace App\Livewire\Forms\Studio\Loyalty\Tier;

use App\Models\TierReward;
use App\Rules\UnsignedInteger;
use Illuminate\Validation\Rule;
use Livewire\Form;

class RewardForm extends Form
{
    public ?TierReward $tierReward = null;

    public string $tier_id = '';

    public string $name = '';

    public string $value = '';

    public function rules(): array
    {
        return [
            'tier_id' => ['required', Rule::exists('tiers', 'id')],
            'name' => ['required', 'string', 'max:100'],
            'value' => ['required', new UnsignedInteger],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'value' => 'nilia',
        ];
    }

    public function setRewards(TierReward $tierReward)
    {
        $this->tierReward = $tierReward;

        $this->tier_id = $tierReward->tier_id;
        $this->name = $tierReward->name;
        $this->value = currency($tierReward->value);
    }

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

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

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

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

        return $this->tierReward;
    }

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