<?php

namespace App\Http\Main\Users;

use App\Models\Team;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;

class Create extends Component
{

    public $first_name;
    public $last_name;
    public $email;
    public $phone;
    public $access_level;
    public $password;
    public $password_confirmation;

  public function mount(){
    $this->access_level='Engineer';
  }


    protected function rules()
    {
        return  [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email|unique:users',
            'phone' => 'required|unique:users',
            'password' => 'confirmed',
    
        ];
    }
    public function updated(){
        $this->validate();
    }
    public function save()
    {
        $this->validate();
        $user = new User();
        $user->first_name = $this->first_name;
        $user->last_name = $this->last_name;
        $user->email = $this->email;
        $user->phone = $this->phone;
        $user->password = Hash::make($this->password);
        $user->save();
        if($this->access_level=='Engineer'){
            $team = Team::find(1);
            $team->users()->attach(
                $newTeamMember = $user,
                ['role' => 'Editor']
            );
        }else if($this->access_level=='Front Desk'){
            $team = Team::find(2);
            $team->users()->attach(
                $newTeamMember = $user,
                ['role' => 'Editor']
            );
        }else{
            $team = Team::find(3);
            $team->users()->attach(
                $newTeamMember = $user,
                ['role' => 'Editor']
            ); 
        }
        $user->current_team_id=$team->id;
        $user->save();
        if(auth()->user()->currentTeam->id==1){
        return redirect()->to('engineers/dashboard');
        }
        else{
            return redirect()->to('frontdesk/dashboard');
        }
    }
    public function render()
    {
        return view('main.users.create')->layout('layouts.app-engineers');
    }
}
