<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\LeadSource\LeadSource;
use App\Models\Tranche;
use App\Services\HistoryService;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
use App\Services\ClientIntakeService;
use App\Rules\LandlineNumber;

class Create extends Component {
    use AuthorizesRequests;

    public $title;
    public $first_name;
    public $middle_name;
    public $last_name;
    public $preferred_name;
    public $dob;
    public $email;
    public $phone;
    public $tranche_id;
    public $lead_source_id;
    public $landline;

    protected $messages = [
        'first_name.regex' => 'First name contains invalid characters.',
        'middle_name.regex' => 'Middle name contains invalid characters.',
        'last_name.regex' => 'Last name contains invalid characters.',
        'preferred_name.regex' => 'Preferred name contains invalid characters.',
        'phone.regex' => 'Phone number must be a valid UK mobile number (try the prefix of +44).',
        'phone.unique' => 'Phone number already exists.',
        'landline.regex' => 'Landline number must be a valid UK landline number, for example 01511234567.',
    ];

    public function render() {
        return view('components.client.create', [
            'tranches' => Tranche::selectRaw("id, CONCAT(funder_name, ' - ', tranche_name) as name")->pluck('name', 'id')->toArray(),
            'lead_sources' => LeadSource::pluck('display_name', 'id')->toArray(),
        ]);
    }

    public function save(HistoryService $history, ClientIntakeService $clientIntake) {
        $this->authorize('clients.create');
        $validated = $this->validate();

        try {
            
            $client = $clientIntake->create([
                'title' => $this->title,
                'first_name' => $this->first_name,
                'middle_name' => $this->middle_name,
                'last_name' => $this->last_name,
                'preferred_name' => $this->preferred_name,
                'dob' => $this->dob,
                'email' => $this->email,
                'phone' => $this->phone,
                'landline' => $this->landline,
                'lead_source_id' => $this->lead_source_id,
            ]);

            $history->add($client, "New Claim Created.");

            $this->redirectRoute('clients.show', $client);

        } catch (\Exception $exception) {
            Log::error("Failed to create client: " . $exception->getMessage());
            $this->dispatch('toast', message: "Something unexpected occurred, please try again later.", type: 'error');
        }
    }


    protected function rules() {
        return [
            'title'  => ['required', 'string', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'first_name'  => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'middle_name' => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'preferred_name' => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'last_name'   => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'dob'         => ['required', 'date', 'before:-18 years', 'after:-120 years'],
            'email'       => ['nullable', 'email:rfc,dns', 'unique:clients,email_address'],
            'phone'       => ['required', 'regex:/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/', 'unique:clients,phone_number'],
            'lead_source_id' => ['nullable', 'exists:lead_sources,id'],
            'landline' => ['nullable', new LandlineNumber(),'unique:clients,landline_number'],
        ];
    }
}
