<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use Livewire\Component;

class Edit extends Component {
    public Solicitor $solicitor;

    public string $name           = '';
    public string $domain         = '';
    public string $email_address  = '';
    public string $phone_number   = '';
    public string $company_number = '';
    public string $sra_number     = '';

    public function mount(Solicitor $solicitor): void {
        $this->authorize('solicitors.edit');
        $this->solicitor = $solicitor;

        $this->name           = (string) $solicitor->name;
        $this->domain         = (string) ($solicitor->domain ?? '');
        $this->email_address  = (string) ($solicitor->email_address ?? '');
        $this->phone_number   = (string) ($solicitor->phone_number ?? '');
        $this->company_number = (string) ($solicitor->company_number ?? '');
        $this->sra_number     = (string) ($solicitor->sra_number ?? '');
    }

    public function save() {
        $this->authorize('solicitors.edit');
        $validated = $this->validate();

        $this->solicitor->update([
            'name'           => $validated['name'],
            'domain'         => $validated['domain'] ?: null,
            'email_address'  => $validated['email_address'] ?: null,
            'phone_number'   => $validated['phone_number'] ?: null,
            'company_number' => $validated['company_number'] ?: null,
            'sra_number'     => $validated['sra_number'] ?: null,
        ]);

        session()->flash('success', 'Solicitor updated successfully.');

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

    public function render() {
        return view('components.solicitor.edit');
    }

    protected function rules(): array {
        return [
            'name'           => ['required', 'string', 'max:255'],
            'domain'         => ['nullable', 'string', 'max:255'],
            'email_address'  => ['nullable', 'email', 'max:255'],
            'phone_number'   => ['nullable', 'string', 'max:50'],
            'company_number' => ['nullable', 'string', 'max:50'],
            'sra_number'     => ['nullable', 'string', 'max:50'],
        ];
    }

    protected function messages(): array {
        return [
            'name.required' => 'Please enter a solicitor name.',
            'email_address.email' => 'Please enter a valid email address.',
        ];
    }
}
