<?php

namespace App\Livewire\User;

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

class Create extends Component
{
    public $roles, $roleId, $email, $first_name, $second_name, $first_surname, $second_surname, $phone, $birth_date;

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

    public function mount()
    {
        $this->roles = Role::where('id','=',1)->get();
        $this->roleId = $this->roles->first()->id;
        info($this->roles);
    }

    public function store()
    {   
        $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',
            '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'   => $this->roleId,
                'person_id' => $employee->id,
            ]);
            
            Utility::sendEmail($user->email, new NewUserMail($user, $password));

            DB::commit();
            session()->flash('status', 'Los datos se guardaron correctamente.');
            return redirect()->route('users.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
        }
    }
}