<?php

namespace App\Http\Livewire;

use Livewire\Component;

use Livewire\WithPagination;

use Hash;
use Illuminate\Support\Facades\Hash as FacadesHash;

class User extends Component
{

    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public $title = 'Utenti';

    public $groups = [];

    public $search, $firstname, $lastname, $username, $email, $group_id, $password, $old_password, $dataId, $update = false, $add = false;

    protected $rules = [
        'firstname' => 'required',
        'lastname' => 'required',
        'username' => 'required',
        'email' => 'required'
    ];

    protected $messages = [
        'firstname.required' => 'Il nome è obbligatorio',
        'lastname.required' => 'Il cognome è obbligatorio',
        'username.required' => 'Lo username è obbligatorio',
        'email.required' => 'Il nome è obbligatorio',
    ];

    public function resetFields(){
        $this->firstname = '';
        $this->lastname = '';
        $this->username = '';
        $this->email = '';
        $this->password = '';
        $this->old_password = '';
        $this->group_id = null;
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function render()
    {
        $this->groups = \App\Models\UserGroup::orderBy('name')->get();
        $rows = \App\Models\User::where('firstname', 'like', '%'.$this->search.'%')->orWhere('lastname', 'like', '%'.$this->search.'%')->orderBy('firstname')->paginate(10);
        return view('livewire.users', ['records' => $rows]);
    }

    public function add()
    {
        $this->resetFields();
        $this->add = true;
        $this->update = false;
    }

    public function store()
    {
        $this->validate();
        try {
            $u = \App\Models\User::create([
                'firstname' => $this->firstname,
                'lastname' => $this->lastname,
                'username' => $this->username,
                'email' => $this->email,
                'password' => FacadesHash::make($this->password),
            ]);
            \App\Models\UserUserGroup::create([
                'group_id' => $this->group_id,
                'user_id' => $u->id
            ]);
            session()->flash('success','Record creato');
            $this->resetFields();
            $this->add = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore in fase di salvataggio' . $ex->getMessage());
        }
    }

    public function edit($id){
        try {
            $record = \App\Models\User::findOrFail($id);
            if( !$record) {
                session()->flash('error','Record non trovato');
            } else {
                $this->firstname = $record->firstname;
                $this->lastname = $record->lastname;
                $this->username = $record->username;
                $this->email = $record->email;
                $this->old_password = $record->password;
                $this->dataId = $record->id;
                $this->update = true;
                $this->add = false;
                $this->group_id = \App\Models\UserUserGroup::where('user_id', $this->dataId)->first()->group_id;
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            $updateData = [
                'firstname' => $this->firstname,
                'lastname' => $this->lastname,
                'username' => $this->username,
                'email' => $this->email,
            ];

            if ($this->password !== '') {
                $updateData['password'] = FacadesHash::make($this->password);
            }

            \App\Models\User::whereId($this->dataId)->update($updateData);
            \App\Models\UserUserGroup::where('user_id', $this->dataId)->delete();
            \App\Models\UserUserGroup::create([
                'group_id' => $this->group_id,
                'user_id' => $this->dataId
            ]);
            session()->flash('success','Record aggiornato');
            $this->resetFields();
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore ' . $ex->getMessage());
        }
    }

    public function cancel()
    {
        $this->add = false;
        $this->update = false;
        $this->resetFields();
    }

    public function delete($id)
    {
        try{
            \App\Models\User::find($id)->delete();
            session()->flash('success',"Record eliminato");
        }catch(\Exception $e){
            session()->flash('error',"Errore");
        }
    }
}
