<?php

namespace App\Livewire\Admin;

use App\Models\Room;

use Livewire\Component;
use App\Services\ApiClient;
use Illuminate\Support\Facades\Auth;

class RoomDetailModal extends Component
{
    

    protected $listeners = [
        'openModal', 'closeModal', 
        'startNotify', 'stopNotify', 'fireNotify', 
        'openAccountNotify','closeAccountNotify'
    ];

    public $room;
    public bool $showModal = false;

    public function openModal($roomId)
    {
        $this->room = Room::find($roomId);
        $this->showModal = true;
    }
    public function closeModal()
    {
        $this->showModal = false;
    }
    public function startNotify()
    {
        $data = $this->buildNotifyData('active', now(), null);
        $this->send($data);
    }

    public function stopNotify()
    {
        $data = $this->buildNotifyData('closed', null, null);
        $this->send($data);
    }

    public function fireNotify()
    {
        $data = $this->buildNotifyData('fire', null, null);
        $this->send($data);
    }

    public function openAccountNotify()
    {
        $data = $this->buildNotifyData('active', now(), null);
        $this->send($data);
    }

    public function closeAccountNotify()
    {
        $data = $this->buildNotifyData('closed', now(), null);
        $this->send($data);
    }
    protected function buildNotifyData(string $command, $startedAt = null, $endedAt = null): array
    {
        return [
            'branch_id'  => $this->room->branch_id ?? 0,  
            'room_name'  => $this->room->name ?? '',
            'command'    => $command,
            'started_at' => $startedAt ? $startedAt->toDateTimeString() : null,
            'ended_at'   => $endedAt ? $endedAt->toDateTimeString() : null,
        ];
    }

    function send(array $data){
        $user = Auth::user();
        $token = $user->api_plain_token ?? null;

        if (!$token) {
            $this->addError('api', 'API token is missing.');
            return false;
        }

        $apiClient = new ApiClient();
        $response = $apiClient->setToken($token)->post('/room/sendSwitch', $data);
        if ($response->failed()) {
            $this->addError('api', 'API request failed: ' . $response->body());
            return false;
        }

        // 可以加入成功提示或事件
        return true;
    }
    
    public function render()
    {
        return view('livewire.admin.room-detail-modal');
    }
}
