<?php
declare(strict_types=1);

namespace Leadlion\Autogedal\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class AddLinksToOrderEmailCategoryList implements DataPatchInterface
{
    private const TEMPLATE_CODE = 'AutoGedal.Ro - Comandă nouă';

    private const CATEGORY_PATHS = [
        'Carlige de Remorcare' => 'carlige-de-remorcare.html',
        'Scuturi Auto Metalice' => 'scut-motor-metalic.html',
        'Cutii Portbagaj Externe' => 'cutii-portbagaj-auto.html',
        'Suporturi Auto pentru Biciclete' => 'suporti-biciclete.html',
        'Accesorii Carlige de Remorcare' => 'accesorii-remorcare.html',
        'Covorase Auto' => 'covorase-auto.html',
        'Tavite Portbagaj' => 'tavite-portbagaj.html',
    ];

    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    public function __construct(ModuleDataSetupInterface $moduleDataSetup)
    {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * @inheritDoc
     */
    public function apply(): AddLinksToOrderEmailCategoryList
    {
        $connection = $this->moduleDataSetup->getConnection();
        $table = $this->moduleDataSetup->getTable('email_template');

        $row = $connection->fetchRow(
            $connection->select()
                ->from($table, ['template_id', 'template_text'])
                ->where('template_code = ?', self::TEMPLATE_CODE)
        );

        if (!$row) {
            return $this;
        }

        $newText = $this->linkifyCategories($row['template_text']);

        if ($newText !== $row['template_text']) {
            $connection->update(
                $table,
                ['template_text' => $newText],
                ['template_id = ?' => $row['template_id']]
            );
        }

        return $this;
    }

    /**
     * Replaces "- Category Name</span>" with a linked version, for each known category.
     * A no-op if the category name is not present in plain-text form (e.g. already linked).
     */
    private function linkifyCategories(string $content): string
    {
        foreach (self::CATEGORY_PATHS as $name => $path) {
            $search = '>- ' . $name . '</span>';
            $replace = '>- <a href="{{store direct_url="' . $path . '"}}" '
                . 'style="color:#3184ca; text-decoration:none;" target="_blank">' . $name . '</a></span>';

            $content = str_replace($search, $replace, $content);
        }

        return $content;
    }

    /**
     * @inheritDoc
     */
    public function getAliases(): array
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public static function getDependencies(): array
    {
        return [];
    }
}
