<?php

namespace App\Livewire\LicenseTokens;

use App\Models\Clients\Client;
use App\Models\Products\LicenseToken;
use Livewire\Component;
use Livewire\WithPagination;

class Edit extends Component
{
    use WithPagination;

    public LicenseToken $licenseToken;
    public ?int $client_id = null;
    public ?string $name = null;
    public string $token = '';
    public bool $active = false;
    public ?string $mode = null;
    public ?int $usage_limit = null;
    public ?string $start_at = null;
    public ?string $end_at = null;
    public ?string $metadata = null;
    public ?string $observation = null;
    public string $clientSearchQuery = '';

    protected $paginationTheme = 'tailwind';

    public function mount(LicenseToken $license_token)
    {
        $this->licenseToken = $license_token;
        $this->client_id = $license_token->client_id ?? null;
        $this->name = $license_token->name;
        $this->token = $license_token->token ?? '';
        $this->active = $license_token->active ?? false;
        $this->mode = $license_token->mode;
        $this->usage_limit = $license_token->usage_limit;
        $this->start_at = $license_token->start_at ? $license_token->start_at->format('Y-m-d') : null;
        $this->end_at = $license_token->end_at ? $license_token->end_at->format('Y-m-d') : null;
        $this->metadata = $license_token->metadata ? json_encode($license_token->metadata, JSON_PRETTY_PRINT) : null;
        $this->observation = $license_token->observation;
    }

    public function updatedClientSearchQuery()
    {
        // Resetear paginación cuando cambia la búsqueda
        $this->resetPage();
    }

    public function getClientsProperty()
    {
        $query = Client::query();

        if (!empty($this->clientSearchQuery)) {
            $query->where(function($q) {
                $q->where('name', 'like', '%' . $this->clientSearchQuery . '%')
                  ->orWhere('shortname', 'like', '%' . $this->clientSearchQuery . '%');
            });
        }

        return $query->orderBy('name')->paginate(10);
    }

    protected function rules()
    {
        return [
            'client_id' => 'required|exists:clients,id',
            'name' => 'nullable|string|max:255',
            'token' => 'required|string|max:100|unique:license_tokens,token,' . $this->licenseToken->id,
            'active' => 'nullable|boolean',
            'start_at' => 'nullable|date',
            'end_at' => 'nullable|date|after_or_equal:start_at',
            'mode' => 'nullable|string|max:50',
            'usage_limit' => 'nullable|integer|min:1',
            'metadata' => 'nullable|string',
            'observation' => 'nullable|string',
        ];
    }

    public function generateToken()
    {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        do {
            // Generar token con patrón: 3IP-XXXX-XXXX-XXXX-XXXX
            $blocks = [];
            for ($i = 0; $i < 4; $i++) {
                $block = '';
                for ($j = 0; $j < 4; $j++) {
                    $block .= $characters[random_int(0, strlen($characters) - 1)];
                }
                $blocks[] = $block;
            }
            $generatedToken = '3IP-' . implode('-', $blocks);
        } while (LicenseToken::where('token', $generatedToken)->where('id', '!=', $this->licenseToken->id)->exists());

        $this->token = $generatedToken;
    }

    public function update()
    {
        $this->authorize('admin.license-tokens.edit');

        $validated = $this->validate();
        $validated['active'] = $this->active;

        // Procesar metadata JSON
        if (!empty($validated['metadata'])) {
            $decoded = json_decode($validated['metadata'], true);
            $validated['metadata'] = json_last_error() === JSON_ERROR_NONE ? $decoded : null;
        } else {
            $validated['metadata'] = null;
        }

        $this->licenseToken->update($validated);

        session()->flash('success', 'Token actualizado correctamente.');

        return $this->redirect(route('license_tokens.show', $this->licenseToken), navigate: true);
    }

    public function render()
    {
        return view('livewire.license-tokens.edit')
            ->layout('layouts.app');
    }
}

