<?php

namespace App\Livewire\Auth;

use App\Helpers\Utility;
use App\Mail\NewClientMail;
use App\Mail\NewUserMail;
use App\Models\Person;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Livewire\Component;

class CustomerRegistration extends Component
{
    public $product, $first_name, $second_name, $first_surname, $second_surname, $phone, $birth_date, $email, $url;

    public function render()
    {
        return view('livewire.auth.customer-registration');
    }

    public function mount()
    {
        $this->url = is_null($this->product) ? route('login') : route('login',['product' => $this->product]) ;
    }

    public function save()
    {
        // session()->flash('success', 'Tu cuenta ha sido creada correctamente. Revisa tu correo electrónico, ahí encontrarás tus credenciales de acceso e instrucciones para ingresar al sistema.');
        // return redirect()->route('login',['product' => $this->product]);
        $this->validate([
            'first_name' => 'required|string|max:100',
            'second_name' => 'nullable|string|max:100',
            'first_surname' => 'required|string|max:100',
            'second_surname' => 'nullable|string|max:100',
            'phone' => 'required|integer|regex:/^\d{10}$/',
            'birth_date' => 'required|date_format:Y-m-d',
            'email' => 'required|string|email|max:200|unique:users,email'

            // 'names'     => 'required|string|max:100',
            // 'surnames'  => 'required|string|max:100',
            // 'email'     => 'required|string|email|max:200|unique:users,email',
            // 'roleId'   => 'required|integer|exists:roles,id',
            // 'sales_point_id'    => $this->role_id == 2 ? 'required|integer|exists:sales_points,id' : ''
        ]);

        DB::beginTransaction();
        try {
            $employee = Person::create([
                'first_name' => $this->first_name,
                'second_name' => $this->second_name,
                'first_surname' => $this->first_surname,
                'second_surname' => $this->second_surname,
                'phone' => $this->phone,
                'birth_date' => $this->birth_date,
            ]);

            $password = Str::random(10);
            $user = User::create([
                'email'     => $this->email,
                'password'  => Hash::make($password),
                'status_id' => 1,
                'role_id'   => 2,
                'person_id' => $employee->id,
            ]);
            Utility::sendEmail($this->email, new NewClientMail($user, $password));
            DB::commit();
            session()->flash('success', 'Tu cuenta ha sido creada correctamente. Revisa tu correo electrónico, ahí encontrarás tus credenciales de acceso e instrucciones para ingresar al sistema.');
            return redirect()->route('login',['product' => $this->product]);
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
            $this->addError('server', 'Error del Servidor.');
        }
    }
}