<?php

namespace App\Livewire\Customers;

use App\Models\Customer;
use Livewire\Component;

class CustomerForm extends Component
{
    public ?Customer $customer = null;
    public bool $editMode = false;

    // Form fields
    public string $name = '';
    public string $phone = '';
    public string $email = '';
    public string $address = '';
    public float $credit_limit = 0;
    public bool $is_active = true;
    public string $notes = '';

    protected function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:50|unique:customers,phone,' . ($this->customer?->id ?? 'NULL'),
            'email' => 'nullable|email|max:255|unique:customers,email,' . ($this->customer?->id ?? 'NULL'),
            'address' => 'nullable|string|max:500',
            'credit_limit' => 'required|numeric|min:0',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
        ];
    }

    public function mount(?int $id = null)
    {
        if ($id) {
            $this->customer = Customer::findOrFail($id);
            $this->editMode = true;
            $this->fillFromCustomer();
        }
    }

    protected function fillFromCustomer()
    {
        $this->name = $this->customer->name ?? '';
        $this->phone = $this->customer->phone ?? '';
        $this->email = $this->customer->email ?? '';
        $this->address = $this->customer->address ?? '';
        $this->credit_limit = $this->customer->credit_limit ?? 0;
        $this->is_active = $this->customer->is_active ?? true;
        $this->notes = $this->customer->notes ?? '';
    }

    public function save()
    {
        $validated = $this->validate();

        if ($this->editMode) {
            $this->customer->update($validated);
            session()->flash('success', __('Customer updated successfully.'));
        } else {
            Customer::create($validated);
            session()->flash('success', __('Customer created successfully.'));
        }

        return redirect()->route('customers.index');
    }

    public function render()
    {
        return view('livewire.customers.form');
    }
}
