<?php

namespace App\Livewire\Forms;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;

use Livewire\Component;
use WireUi\Traits\WireUiActions;

use Illuminate\Validation\Rules\Enum;
use App\Models\User;
use App\Enums\UserGender;
use App\Enums\UserStatus;
use Spatie\Permission\Models\Role;

class UserForm extends Component
{
    use WireUiActions;

    protected $listeners = ['openModal','closeModal', 'deleteUser'];

    public bool $canCreate;
    public bool $canEdit;
    public bool $canDelect;

    public bool $showModal = 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,
        'password' => '', // 新增
        'password_confirmation' => '', // 新增
    ];
    
    public function rules()
    {
        return [
            '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', new Enum(UserGender::class)],
            'fields.status' => ['required', new Enum(UserStatus::class)],
        ];
    }

    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();
        $this->canCreate = Auth::user()?->can('user-edit') ?? false;
        $this->canEdit = Auth::user()?->can('user-edit') ?? false;
        $this->canDelect = Auth::user()?->can('user-delete') ?? false;
    }

    public function openModal($id = null)
    {
        $this->resetFields();
        if($id){
            $obj = User::findOrFail($id);
            $this->userId = $obj->id;
            $this->fields = $obj->only(array_keys($this->fields));
            $this->selectedRoles = $obj->roles()->pluck('id')->toArray();
        }
        $this->showModal = true;
    }
    
    public function closeModal()
    {
        $this->resetFields();
        $this->showModal = false;
    }

    public function save()
    {
        //dd($this->fields);
        $rules = $this->rules();
        // 加入 email / phone 唯一性驗證，排除自己（編輯時）
        $rules['fields.email'] .= '|unique:users,email' . ($this->userId ? ",{$this->userId}" : '');
        $rules['fields.phone'] .= '|unique:users,phone' . ($this->userId ? ",{$this->userId}" : '');

        // 新增時才驗證密碼
        if (!$this->userId) {
            $rules['fields.password'] = ['required', 'string', 'min:8', 'confirmed'];
        }
        $validated = $this->validate($rules);

        if ($this->userId) {
            if ($this->canEdit) {
                $user = User::findOrFail($this->userId);
                $user->update($this->fields);
                $user->syncRoles($this->selectedRoles);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '使用者已更新',
                ]);
            }
        } else {
            if ($this->canCreate) {
                $user = User::create($this->fields);
                $user->syncRoles($this->selectedRoles);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '使用者已新增',
                ]);
            }
        }

        $this->resetFields();
        $this->showModal = false;
        $this->dispatch('pg:eventRefresh-user-table');
    }
    
    public function deleteUser($id)
    {
        if ($this->canDelect) {
            User::findOrFail($id)->delete();
            $this->notification()->send([
                'icon' => 'success',
                'title' => '成功',
                'description' => '使用者已刪除',
            ]);
            $this->dispatch('pg:eventRefresh-user-table');
        }
    }

    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.forms.user-form');
    }
}
