<?php

namespace App\Livewire\Forms;

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

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

use App\Models\Branch;
use App\Models\Room;
use App\Enums\RoomType;

class BranchForm extends Component
{
    use WireUiActions;
    
    protected $listeners = ['openModal','closeModal', 'deleteBranch'];

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

    public bool $showModal = false;
    public ?int $branchId = null;
    
    public array $fields = [
        'name' =>'',
        'external_ip' =>'',
        'enable' => true,
        'roomNotes' =>''
    ];
    public function rules()
    {
        return [
            'fields.name'         => 'required|string|max:255',
            'fields.external_ip'  => 'required|string|max:255',
            'fields.enable'       => 'required|boolean', // 或 new Enum(...) 如果你用了 Enum
            'fields.roomNotes'    => 'nullable|string',
        ];
    }

    public function mount()
    {
        $this->canCreate = Auth::user()?->can('room-edit') ?? false;
        $this->canEdit = Auth::user()?->can('room-edit') ?? false;
        $this->canDelect = Auth::user()?->can('room-delete') ?? false;
    }

    public function openModal($id = null)
    {
        $this->resetFields();

        if ($id) {
            $branch = Branch::findOrFail($id);
            $this->branchId = $branch->id;
            $this->fields = $branch->only(array_keys($this->fields));
        }
    
        $this->showModal = true;
    }

    public function closeModal()
    {
        $this->resetFields();
        $this->showModal = false;
    }
    
    public function save()
    {
        $validated = $this->validate($this->rules());
        if ($this->branchId) {
            if ($this->canEdit) {
                $branch = Branch::findOrFail($this->branchId);
                $branch->update($this->fields);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '分店已更新',
                ]);
            }
        } else {
            if ($this->canCreate) {
                $branch = Branch::create([
                    'name' => $this->fields['name'],
                    'external_ip' => $this->fields['external_ip'],
                    'enable' => $this->fields['enable'],
                ]);

                // 解析 roomNotes
                $roomLines = explode("\n", trim($this->fields['roomNotes']));
                $rooms = [];

                foreach ($roomLines as $line) {
                    [$floor, $roomList] = explode(';', $line);
                    $floor = (int) filter_var($floor, FILTER_SANITIZE_NUMBER_INT); // 抽出 1F 的數字

                    $roomNames = array_map('trim', explode(',', $roomList));

                    foreach ($roomNames as $roomName) {
                        $type = match (true) {
                            str_starts_with($roomName, 'svr') => RoomType::SVR,
                            str_starts_with($roomName, 'pc') => RoomType::PC,
                            default => RoomType::Unset,
                        };
                        $rooms[] = new Room([
                            'floor' => $floor,
                            'type' => $type->value,
                            'name' => preg_replace('/^(pc|svr)/', '', $roomName),
                        ]);
                    }
                }

                // 儲存所有 Room
                $branch->rooms()->saveMany($rooms);
                $this->notification()->send([
                    'icon' => 'success',
                    'title' => '成功',
                    'description' => '分店已新增',
                ]);
            }
        }
        $this->resetFields();
        $this->showModal = false;
        $this->dispatch('pg:eventRefresh-branch-table');
    }
    
    public function deleteBranch($id)
    {
        if ($this->canDelect) {
            Branch::findOrFail($id)->delete();
            $this->notification()->send([
                'icon' => 'success',
                'title' => '成功',
                'description' => '分店已刪除',
            ]);
            
            $this->dispatch('pg:eventRefresh-branch-table');
        }
    }

    public function resetFields()
    {
        foreach ($this->fields as $key => $value) {
            if ($key == 'enable') {
                $this->fields[$key] = true;
            } else {
                $this->fields[$key] = '';
            }
        }
        $this->branchId = null;
    }

    public function render()
    {
        return view('livewire.forms.branch-form');
    }
}
