<?php
declare(strict_types=1);

namespace Autogedal\Extend\Model\Product;

use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;

class SpecsDescriptionManager
{

    public function __construct(
        private readonly Escaper $escaper
    ) {}


    public function updateDescription(Product $product): bool
    {
        $attributes = $product->getAttributes();
        if (!$attributes) {
            return false;
        }

        $specsHtml = $this->generateSpecsHtml($product, $attributes);
        $description = (string)$product->getData('description');
        
        $pattern = '/<div class="autogedal-specs-wrapper">.*?<\/div>/is';
        $cleanDescription = preg_replace($pattern, '', $description);
        $cleanDescription = trim((string)$cleanDescription);

        if (empty($specsHtml)) {
            if ($description !== $cleanDescription) {
                $product->setData('description', $cleanDescription);
                return true;
            }
            return false;
        }

        $finalSpecsHtml = '<div class="autogedal-specs-wrapper">' . "\n" . $specsHtml . "\n" . '</div>';

        $pos = stripos($cleanDescription, 'Observatii generale');
        if ($pos !== false) {
            $blockStartPos = strrpos(substr($cleanDescription, 0, $pos), '<p');
            if ($blockStartPos === false) {
                $blockStartPos = $pos;
            }
            
            $newDescription = substr_replace($cleanDescription, $finalSpecsHtml . "\n\n", $blockStartPos, 0);
        } else {
            $newDescription = $cleanDescription . "\n<br/>\n" . $finalSpecsHtml;
        }

        if ($description !== $newDescription) {
            $product->setData('description', $newDescription);
            return true;
        }

        return false;
    }

    protected function generateSpecsHtml(Product $product, array $attributes): string
    {
        $data = [];
        
        foreach ($attributes as $attribute) {
            if (!$attribute->getIsVisibleOnFront() || !$product->hasData($attribute->getAttributeCode())) {
                continue;
            }

            $value = $attribute->getFrontend()->getValue($product);
            
            if ($value instanceof \Magento\Framework\Phrase) {
                $value = (string)$value;
            }

            if ($value === 'Yes') {
                $value = 'Da';
            } elseif ($value === 'No') {
                $value = 'Nu';
            }

            if ($value === null || $value === false || (string)$value === '') {
                continue;
            }

            if (is_array($value)) {
                $value = implode(', ', $value);
            }

            if (is_string($value) && strlen(trim($value)) > 0) {
                $data[] = [
                    'label' => $attribute->getStoreLabel(),
                    'value' => $value
                ];
            }
        }

        if (empty($data)) {
            return '';
        }

        $html = '<p class="product-description-specs">';
        $html .= '<strong>' . $this->escaper->escapeHtml(__('Specificatii:')) . '</strong><br/>';
        
        foreach ($data as $item) {
            $label = $this->escaper->escapeHtml((string)$item['label']);
            $value = $this->escaper->escapeHtml((string)$item['value']);
            
            $html .= '<strong>' . $label . ':</strong> ' . $value . '<br/>';
        }
        
        $html .= '</p>';

        return $html;
    }
}
