<?php

namespace App\Livewire\Admin;

use Livewire\Component;

use App\Models\User;
use App\Enums\UserGender;
use App\Enums\UserStatus;
use Spatie\Permission\Models\Role;

class UserForm extends Component
{
    protected $listeners = ['openCreateUserModal','openEditUserModal', 'deleteUser'];

    public bool $showCreateModal = false;


    public array $genderOptions =[];
    public array $statusOptions =[];
    public $rolesOptions = []; // 所有角色清單
    public $selectedRoles = []; // 表單中選到的權限
    public ?int $userId = null;
    public array $fields = [
        'name' =>'',
        'email' => '',
        'phone' => '',
        'birthday' => '',
        'gender' => 'unset',
        'status' => 0,
    ];
    

    protected $rules = [
        'fields.name' => 'required|string|max:255',
        'fields.email' => 'required|string|email|max:255',
        'fields.phone' => 'nullable|regex:/^09\d{8}$/',
        'fields.birthday' =>'nullable|date',
        'fields.gender' => 'required|in:male,female,other,unset',
        'fields.status' => 'required|integer|in:0,1,2',
    ];

    public function mount()
    {
        $this->fields['birthday'] = now()->toDateString();
        $this->genderOptions = collect(UserGender::cases())->map(fn ($gender) => [
            'name' => $gender->labels(),
            'value' => $gender->value,
        ])->toArray();
        $this->statusOptions = collect(UserStatus::cases())->map(fn ($status) => [
            'name' => $status->labels(),
            'value' => $status->value,
        ])->toArray();
        $this->rolesOptions = Role::all();
    }

    public function openCreateUserModal()
    {
        $this->resetFields();
        $this->showCreateModal = true;
    }

    public function openEditUserModal($id)
    {
        $user = User::findOrFail($id);
        $this->userId = $user->id;
        $this->fields = $user->only(array_keys($this->fields));

        $this->selectedRoles = $user->roles()->pluck('id')->toArray();
        $this->showCreateModal = true;
    }

    public function save()
    {
        $this->validate();

        if ($this->userId) {
            $user = User::findOrFail($this->userId);
            $user->update($this->fields);
            $user->syncRoles($this->selectedRoles);
            session()->flash('message', '使用者已更新');
        } else {
            $user = User::create($this->fields);
            $user->syncRoles($this->selectedRoles);
            session()->flash('message', '使用者已新增');
        }

        $this->resetFields();
        $this->showCreateModal = false;
        $this->dispatch('pg:eventRefresh-user-table');
    }
    
    public function deleteUser($id)
    {
        User::findOrFail($id)->delete();
        session()->flash('message', '使用者已刪除');
    }

    public function resetFields()
    {
        foreach ($this->fields as $key => $value) {
            if ($key == 'gender') {
                $this->fields[$key] = 'unset';
            } elseif ($key == 'status') {
                $this->fields[$key] = 0;
            } elseif ($key == 'birthday') {
                $this->fields[$key] = now()->toDateString();
            } else {
                $this->fields[$key] = '';
            }
        }
        $this->userId = null;
        $this->selectedRoles = [];
    }
    
    public function render()
    {
        return view('livewire.admin.user-form');
    }
}
