<?php

namespace App\Livewire\Suppliers;

use App\Models\Supplier;
use Livewire\Component;

class SupplierForm extends Component
{
    public ?Supplier $supplier = null;
    public bool $editMode = false;

    // Form fields
    public string $company_name = '';
    public string $contact_name = '';
    public string $phone = '';
    public string $email = '';
    public string $address = '';
    public string $tax_number = '';
    public string $payment_terms = '';
    public bool $is_active = true;
    public string $notes = '';

    protected function rules(): array
    {
        return [
            'company_name' => 'required|string|max:255',
            'contact_name' => 'nullable|string|max:255',
            'phone' => 'required|string|max:50',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string|max:500',
            'tax_number' => 'nullable|string|max:100',
            'payment_terms' => 'nullable|string|max:255',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
        ];
    }

    public function mount(?int $id = null)
    {
        if ($id) {
            $this->supplier = Supplier::findOrFail($id);
            $this->editMode = true;
            $this->fillFromSupplier();
        }
    }

    protected function fillFromSupplier()
    {
        $this->company_name = $this->supplier->company_name ?? '';
        $this->contact_name = $this->supplier->contact_name ?? '';
        $this->phone = $this->supplier->phone ?? '';
        $this->email = $this->supplier->email ?? '';
        $this->address = $this->supplier->address ?? '';
        $this->tax_number = $this->supplier->tax_number ?? '';
        $this->payment_terms = $this->supplier->payment_terms ?? '';
        $this->is_active = $this->supplier->is_active ?? true;
        $this->notes = $this->supplier->notes ?? '';
    }

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

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

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

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