<?php

namespace App\Livewire\Products\Components;

use App\Models\Products\Product;
use Livewire\Component;

class ProductCard extends Component
{
    public Product $product;

    public function mount(Product $product)
    {
        $this->product = $product;
    }

    public function getLatestVersionProperty()
    {
        // Primero intentar obtener la versión del metadata
        if ($this->product->metadata && isset($this->product->metadata['version'])) {
            return $this->product->metadata['version'];
        }

        // Si no hay versión en metadata, buscar en los setups activos
        $latestSetup = $this->product->setups()
            ->where('status', 'active')
            ->orderByDesc('version')
            ->first();

        if ($latestSetup) {
            // Convertir formato YYYYMMDDXX a formato legible
            $version = $latestSetup->version;
            if (strlen($version) === 10) {
                $year = (int) substr($version, 0, 4);
                $month = (int) substr($version, 4, 2);
                $revision = (int) substr($version, 8, 2);
                
                // Formato simplificado: año.mes.revisión (ej: 2024.11.1 -> 1.21)
                // O simplemente usar mes.revisión si el año es reciente
                if ($year >= 2024) {
                    return $month . '.' . str_pad($revision, 2, '0', STR_PAD_LEFT);
                }
                return $year . '.' . $month . '.' . $revision;
            }
            return $version;
        }

        return null;
    }

    public function getEnvironmentsCountProperty()
    {
        return $this->product->environmentsQuery()->count();
    }

    public function render()
    {
        return view('livewire.products.components.product-card');
    }
}
