<?php

namespace App\Livewire\Studio\Master\User;

use App\Models\Employee;
use App\Models\User;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithRequestNotification;
use Flux\Flux;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Pegawai')]
class Index extends Component
{
    use WithAuthorization, WithConfirmation, WithRequestNotification, WithSubscribeNotification, WithToast;

    public string $search = '';

    public array $status = [];

    public function delete(User $user): void
    {
        $this->canOrAbort('delete user');

        $user->delete();

        $this->toast('Pegawai berhasil dihapus.');

        Flux::modals()->close();
    }

    public function resetPassword(User $user): void
    {
        $this->canOrAbort('reset password user');

        $user->update(['password' => Hash::make(config('myconfig.password_default'))]);

        $this->toast('Kata sandi pegawai berhasil direset.');

        Flux::modals()->close();
    }

    public function render(): View
    {
        $employees = Employee::with(['user', 'user.referralCode', 'user.outlets'])
            ->when(! empty($this->search), function ($query) {
                return $query->where('full_name', 'like', '%'.$this->search.'%')
                    ->orWhere('code', 'like', '%'.$this->search.'%')
                    ->orWhereHas('user', fn ($q) => $q->where('email', 'like', '%'.$this->search.'%'))
                    ->orWhereHas('user', fn ($q) => $q->where('username', 'like', '%'.$this->search.'%'));
            })
            ->when(! empty($this->status), fn ($query) => $query->whereHas('user', fn ($q) => $q->whereIn('status', $this->status)))
            ->withoutDeveloper()
            ->latest()
            ->get();

        return view('livewire.studio.master.user.index', [
            'pageTitle' => 'Pegawai',
            'employees' => $employees,
        ]);
    }
}
