<?php

namespace App\Livewire\Customers;

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

class Create extends Component
{
    public $first_name = '';
    public $last_name = '';
    public $email = '';
    public $phone = '';
    public $secondary_phone = '';
    public $address = '';
    public $city = '';
    public $state = '';
    public $zip_code = '';
    public $notes = '';
    public $status = 'active';

    protected $rules = [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|email|unique:customers,email',
        'phone' => 'required|string|max:255',
        'secondary_phone' => 'nullable|string|max:255',
        'address' => 'required|string|max:500',
        'city' => 'required|string|max:255',
        'state' => 'required|string|max:2',
        'zip_code' => 'required|string|max:10',
        'notes' => 'nullable|string|max:1000',
        'status' => 'required|in:active,inactive',
    ];

    protected $messages = [
        'first_name.required' => 'First name is required.',
        'last_name.required' => 'Last name is required.',
        'email.required' => 'Email address is required.',
        'email.email' => 'Please enter a valid email address.',
        'email.unique' => 'This email address is already registered.',
        'phone.required' => 'Phone number is required.',
        'address.required' => 'Address is required.',
        'city.required' => 'City is required.',
        'state.required' => 'State is required.',
        'zip_code.required' => 'ZIP code is required.',
    ];

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

        $customer = Customer::create([
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'email' => $this->email,
            'phone' => $this->phone,
            'secondary_phone' => $this->secondary_phone,
            'address' => $this->address,
            'city' => $this->city,
            'state' => $this->state,
            'zip_code' => $this->zip_code,
            'notes' => $this->notes,
            'status' => $this->status,
        ]);

        session()->flash('success', 'Customer created successfully!');
        return redirect()->route('customers.show', $customer);
    }

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