<?php

namespace Modules\MultiPOS\Livewire\Machines;

use Livewire\Component;
use Modules\MultiPOS\Entities\PosMachine;
use Modules\MultiPOS\Services\PosMachineService;
use Illuminate\Support\Facades\Cookie;
use Jantinnerezo\LivewireAlert\LivewireAlert;

class RegisterMachine extends Component
{
    use LivewireAlert;

    public $branchId;
    public $alias;
    public $deviceId;
    public $showModal = false;
    public $limitReached = false;
    public $limitMessage = '';

    protected $rules = [
        'branchId' => 'required|exists:branches,id',
        'alias' => 'nullable|string|max:255',
    ];

    public function mount()
    {
        $this->branchId = branch()->id ?? null;
        $this->checkLimit();
        $this->loadDeviceId();
    }

    public function loadDeviceId()
    {
        $cookieName = config('multipos.cookie.name', 'pos_token');
        $this->deviceId = request()->cookie($cookieName);
        
        if (!$this->deviceId) {
            // Generate a new device ID
            $this->deviceId = PosMachine::generateDeviceId();
        }
    }

    public function checkLimit()
    {
        if (!$this->branchId) {
            return;
        }

        $canRegister = PosMachineService::canRegisterNewMachine($this->branchId);
        
        if (!$canRegister) {
            $this->limitReached = true;
            $remaining = PosMachineService::getRemainingSlots($this->branchId);
            $this->limitMessage = __('multipos::messages.registration.limit_reached.message', [
                'limit' => $remaining ?? 0
            ]);
        }
    }

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

        if ($this->limitReached) {
            $this->alert('error', $this->limitMessage);
            return;
        }

        // Check if device is already registered
        if ($this->deviceId) {
            $existing = PosMachine::where('device_id', $this->deviceId)
                ->where('branch_id', $this->branchId)
                ->first();

            if ($existing) {
                $this->alert('info', __('multipos::messages.registration.already_registered'));
                $this->dispatch('machineRegistered', ['machine' => $existing->id]);
                return;
            }
        }

        // Register the machine
        $machine = PosMachineService::registerMachine([
            'restaurant_id' => restaurant()->id,
            'branch_id' => $this->branchId,
            'device_id' => $this->deviceId,
            'alias' => $this->alias ?: "POS " . (PosMachineService::getMachineCount($this->branchId) + 1),
            'registered_by' => auth()->id(),
            'status' => 'pending',
        ]);

        // Set cookie for device ID
        $cookieName = config('multipos.cookie.name', 'pos_token');
        Cookie::queue($cookieName, $this->deviceId, config('multipos.cookie.lifetime', 525600));

        $this->alert('success', __('multipos::messages.registration.registered_successfully'));
        $this->reset(['alias', 'showModal']);
        $this->dispatch('machineRegistered', ['machine' => $machine->id]);
        $this->dispatch('refreshMachines');
    }

    public function openModal()
    {
        $this->checkLimit();
        $this->showModal = true;
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->reset(['alias']);
    }

    public function render()
    {
        return view('multipos::livewire.machines.register-machine');
    }
}

