<?php

namespace App\Livewire\Customers;

use App\Models\Customer;
use App\Models\User;
use App\Models\Role;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class Create extends Component
{
    // Customer Information
    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';

    // User Account Options
    public $create_user_account = true;
    public $password = '';
    public $send_welcome_email = true;

    protected $rules = [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|email|unique:customers,email|unique:users,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',
        'password' => 'required_if:create_user_account,true|min:8|nullable',
    ];

    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.',
        'password.required_if' => 'Password is required when creating a user account.',
        'password.min' => 'Password must be at least 8 characters.',
    ];

    public function mount()
    {
        // Generate a random password by default
        $this->password = Str::random(12);
    }

    public function generatePassword()
    {
        $this->password = Str::random(12);
    }

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

        DB::transaction(function () {
            $user = null;
            
            // Create user account if requested
            if ($this->create_user_account) {
                $user = User::create([
                    'name' => $this->first_name . ' ' . $this->last_name,
                    'email' => $this->email,
                    'password' => Hash::make($this->password),
                    'phone' => $this->phone,
                    'status' => 'active',
                ]);

                // Assign customer_portal role
                $customerRole = Role::where('name', 'customer_portal')->first();
                if ($customerRole) {
                    $user->roles()->attach($customerRole->id, [
                        'is_active' => true,
                        'assigned_at' => now(),
                    ]);
                }
            }

            // Create customer record
            $customer = Customer::create([
                'user_id' => $user?->id,
                '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,
            ]);

            // TODO: Send welcome email if requested
            if ($this->create_user_account && $this->send_welcome_email) {
                // Implement welcome email logic here
            }

            session()->flash('success', 'Customer created successfully!' . 
                ($this->create_user_account ? ' User account also created with password: ' . $this->password : ''));
            
            $this->redirect(route('customers.show', $customer), navigate: true);
        });
    }

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