<?php

namespace App\Livewire\Forms;

use App\Models\Customer;
use Illuminate\Validation\Rule as ValidationRule;
use Livewire\Form;

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

    public $name = '';

    public $contact_person = '';

    public $email = '';

    public $phone_number = '';

    public $address = '';

    public $tax_id = '';

    public $status = 'active';

    public function setCustomer(Customer $customer)
    {
        $this->customer = $customer;
        $this->name = $customer->name;
        $this->contact_person = $customer->contact_person;
        $this->email = $customer->email;
        $this->phone_number = $customer->phone_number;
        $this->address = $customer->address;
        $this->tax_id = $customer->tax_id;
        $this->status = $customer->status;
    }

    public function store()
    {
        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'contact_person' => 'nullable|string|max:255',
            'email' => ['nullable', 'email', ValidationRule::unique('customers', 'email')],
            'phone_number' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'tax_id' => ['nullable', 'string', 'max:255', ValidationRule::unique('customers', 'tax_id')],
            'status' => 'required|in:active,inactive,on_hold',
        ]);

        Customer::create($validated);
    }

    public function update()
    {
        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'contact_person' => 'nullable|string|max:255',
            'email' => ['nullable', 'email', ValidationRule::unique('customers', 'email')->ignore($this->customer->id)],
            'phone_number' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'tax_id' => ['nullable', 'string', 'max:255', ValidationRule::unique('customers', 'tax_id')->ignore($this->customer->id)],
            'status' => 'required|in:active,inactive,on_hold',
        ]);

        $this->customer->update($validated);
    }
}
