<?php

namespace App\Livewire\Forms\Studio\Loyalty;

use App\Enums\Gender;
use App\Models\Customer;
use App\Rules\PhoneNumber;
use Illuminate\Validation\Rule;
use Livewire\Form;

class CustomerForm extends Form
{
    public ?Customer $customer = null;

    public string $name = '';

    public ?string $phone_number = null;

    public string $gender = '';

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'phone_number' => ['nullable', 'string', new PhoneNumber],
            'gender' => ['required', Rule::in(Gender::cases())],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'phone_number' => 'nomor telepon',
            'gender' => 'jenis kelamin',
        ];
    }

    public function setCustomer(Customer $customer)
    {
        $this->customer = $customer;

        $this->name = $customer->name;
        $this->phone_number = $customer->phone_number;
        $this->gender = $customer->gender->value;
    }

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

        Customer::create([
            'name' => $this->name,
            'phone_number' => $this->phone_number,
            'gender' => $this->gender,
        ]);
    }

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

        $this->customer->update([
            'name' => $this->name,
            'phone_number' => $this->phone_number,
            'gender' => $this->gender,
        ]);
    }
}
