<?php

namespace App\Livewire\Inventory\Suppliers;

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

class Edit extends Component
{
    public Supplier $supplier;
    
    public $name = '';
    public $company_name = '';
    public $email = '';
    public $phone = '';
    public $address = '';
    public $city = '';
    public $state = '';
    public $zip_code = '';
    public $contact_person = '';
    public $payment_terms = '';
    public $rating = 0;
    public $is_active = true;

    public function mount(Supplier $supplier)
    {
        $this->supplier = $supplier;
        $this->name = $supplier->name;
        $this->company_name = $supplier->company_name;
        $this->email = $supplier->email;
        $this->phone = $supplier->phone;
        $this->address = $supplier->address;
        $this->city = $supplier->city;
        $this->state = $supplier->state;
        $this->zip_code = $supplier->zip_code;
        $this->contact_person = $supplier->contact_person;
        $this->payment_terms = $supplier->payment_terms;
        $this->rating = $supplier->rating ?: 0;
        $this->is_active = $supplier->is_active;
    }

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'email' => 'required|email|unique:suppliers,email,' . $this->supplier->id,
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'zip_code' => 'nullable|string|max:20',
            'contact_person' => 'nullable|string|max:255',
            'payment_terms' => 'nullable|string|max:255',
            'rating' => 'nullable|numeric|min:0|max:5',
            'is_active' => 'boolean',
        ];
    }

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

        $this->supplier->update([
            'name' => $this->name,
            'company_name' => $this->company_name,
            'email' => $this->email,
            'phone' => $this->phone,
            'address' => $this->address,
            'city' => $this->city,
            'state' => $this->state,
            'zip_code' => $this->zip_code,
            'contact_person' => $this->contact_person,
            'payment_terms' => $this->payment_terms,
            'rating' => $this->rating ?: null,
            'is_active' => $this->is_active,
        ]);

        session()->flash('success', 'Supplier updated successfully!');
        
        return $this->redirect(route('inventory.suppliers.index'), navigate: true);
    }

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