<?php

namespace App\Livewire\Pengaturan;

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithoutUrlPagination;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;
use App\Models\User as UM;
use Livewire\Attributes\On;


class User extends Component
{
    use WithPagination, WithoutUrlPagination;
    public $key;
    public $paginationTheme = 'bootstrap';
    public $name, $email, $password, $password_confirmation, $roles, $status, $selectedId;
    public $cgpassword, $cgpassword_confirmation;
    public $usernameEd, $nameEd, $emailEd, $rolesEd, $statusEd;
    public $dataOpd = [];
    protected $messages = [
        '*.required' => 'Tidak Boleh Kosong',
        '*.email' => 'Format Email Tidak Valid',
        '*.unique' => 'Email Sudah Ada',
        '*.confirmed' => 'Password Tidak Sama',
        '*.min' => 'Panjang Karakter Minimal 6',
        '*.same' => 'Password Tidak Sama'
    ];

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

    public function store()
    {
        $this->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => ['required', 'confirmed', Password::defaults()],
            'password_confirmation' => 'required|same:password',
            'roles' => 'required',
            'status' => 'required',
        ]);

        try {
            $data = [
                'name' => $this->name,
                'email' => $this->email,
                'password' => Hash::make($this->password),
                'roles' => $this->roles,
                'is_active' => $this->status,
            ];
            UM::create($data);
            $this->success();
            $this->resetUser();
            $this->close_modal();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    public function edit($id)
    {
        $this->resetData();
        $data = UM::find($id);
        $this->selectedId = $id;
        $this->nameEd = $data->name;
        $this->emailEd = $data->email;
        $this->rolesEd = $data->roles;
        $this->statusEd = $data->is_active;
        $this->open_modal_edit();
    }

    public function edit_password($id)
    {
        $this->resetPassword();
        $this->selectedId = $id;
        $this->open_modal_pass();
    }

    public function update()
    {
        $this->validate([
            'nameEd' => 'required',
            'rolesEd' => 'required',
            'statusEd' => 'required',
        ]);

        try {
            $data = [
                'name' => $this->nameEd,
                'roles' => $this->rolesEd,
                'is_active' => $this->statusEd,
            ];
            UM::find($this->selectedId)->update($data);
            $this->success();
            $this->resetData();
            $this->close_modal_edit();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    public function update_password()
    {
        $this->validate([
            'cgpassword' => ['required', 'confirmed', Password::defaults()],
            'cgpassword_confirmation' => ['required', 'same:cgpassword']
        ]);


        try {
            UM::find($this->selectedId)->update(['password' => Hash::make($this->cgpassword)]);
            $this->success();
            $this->resetPassword();
            $this->close_modal_pass();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    #[On('destroy')] 
    public function destroy($id)
    {
        try {
            UM::find($id)->delete();
            $this->remove();
            $this->resetUser();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    #[On('set-status')] 
    public function set_status($id, $status)
    {
        try {
            UM::find($id)->update(['is_active' => $status]);
            $this->success();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    public function resetUser()
    {
        $this->reset(['name', 'email', 'roles', 'status', 'password', 'password_confirmation']);
        $this->resetValidation();
        $this->resetPage();
    }

    public function resetData()
    {
        $this->reset(['usernameEd', 'nameEd', 'emailEd', 'rolesEd', 'statusEd']);
        $this->resetValidation();
        $this->resetPage();
    }

    public function resetPassword()
    {
        $this->reset(['cgpassword', 'cgpassword_confirmation']);
        $this->resetValidation();
        $this->resetPage();
    }

    public function open_modal()
    {
        $this->resetUser();
        $this->dispatch('show-modal');
    }

    public function close_modal()
    {
        $this->dispatch('close-modal');
    }

    public function open_modal_edit()
    {
        $this->dispatch('show-modal-edit');
    }

    public function close_modal_edit()
    {
        $this->dispatch('close-modal-edit');
    }

    public function open_modal_pass()
    {
        $this->dispatch('show-modal-password');
    }

    public function close_modal_pass()
    {
        $this->dispatch('close-modal-password');
    }

    public function success()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Berhasil Simpan Data!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function error($msg = null)
    {
        $this->dispatch('swal:modal', [
            'type' => 'error',
            'message' => 'Operasi Gagal! ' . $msg,
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function confirm($id)
    {
        $this->dispatch('swal:confirm', [
            'type' => 'warning',
            'message' => 'Hapus Data?',
            'text' => 'Data Tidak Dapat Dikembalikan!',
            'id' => $id
        ]);
    }

    public function remove()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Data Berhasil Dihapus!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function render()
    {
        $term = $this->key;
        $data = UM::when(!empty($term), function($q) use($term){
            $q->where('name', 'like', '%'.$term.'%');
        })
        ->orderBy('roles')->paginate(10);
        return view('livewire.pengaturan.user', compact('data'));
    }
}
