<?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\Support\Facades\Log;
use Livewire\Component;

class Create extends Component {

    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;

    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).',
    ];

    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 $service) {
        $validated = $this->validate();

        try {
            $client = Client::create([
                'title'          => $this->standardiseName($this->title),
                'name_first'     => $this->standardiseName($this->first_name),
                'name_middle'    => $this->standardiseName($this->middle_name),
                'name_last'      => $this->standardiseName($this->last_name),
                'name_preferred' => $this->standardiseName($this->preferred_name),
                'date_of_birth' => $this->dob,
                'email_address' => strtolower(trim($this->email ?: '')),
                'phone_number'  => str_replace(' ', '', $this->phone),
                'tranche_id' => null,
                'lead_source_id' => $this->lead_source_id,
            ]);

            $claim = $client->claim()->create([
                'status_id' => 1,
            ]);

            $service->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 standardiseName(?string $value): ?string
    {
        if (!$value) {
            return null;
        }

        $value = trim($value);

        $value = preg_replace('/\s+/', ' ', $value);

        $value = mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');

        return $value;
    }

    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'],
        ];
    }
}
