<?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 RegisterMachineModal extends Component
{
    use LivewireAlert;

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

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

    protected $listeners = ['openRegistrationModal' => 'open', 'closeRegistrationModal' => 'close'];

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

    public function open()
    {
        $this->checkLimit();
        $this->show = true;
    }

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

    public function loadDeviceId()
    {
        $cookieName = config('multipos.cookie.name', 'pos_token');
        $this->deviceId = request()->cookie($cookieName);
        
        if (!$this->deviceId) {
            $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
            ]);
        } else {
            $this->limitReached = false;
        }
    }

    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', ['machineId' => $existing->id]);
                $this->close();
                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->dispatch('machineRegistered', ['machineId' => $machine->id]);
        $this->close();
    }

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

