<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Categories\Edit;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Catalog\Model\CategoryFactory;
use WriteTextAI\WriteTextAI\Model\AiCategoryManager;
use WriteTextAI\WriteTextAI\Model\Categories\GeneratedText;
use WriteTextAI\WriteTextAI\Helper\Categories\Fields as FieldHelper;
use WriteTextAI\WriteTextAI\Model\Categories\MarkReview;
use WriteTextAI\WriteTextAI\Model\Categories\ReviewStatus;
use WriteTextAI\WriteTextAI\Helper\ReviewStatus as ReviewHelper;
use WriteTextAI\WriteTextAI\Helper\Categories\RepresentativeProducts as RepresentativeProductsHelper;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Helper\Html;
use Magento\Store\Model\StoreManagerInterface;

class Transfer extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::transfer';

    /**
     * @var CategoryFactory
     */
    private $categoryFactory;

    /**
     * @var AiCategoryManager
     */
    private $aiCategoryManager;

    /**
     * @var GeneratedText
     */
    private $generatedText;

    /**
     * @var FieldHelper
     */
    private $fieldHelper;

    /**
     * @var MarkReview
     */
    private $markReview;

    /**
     * @var ReviewHelper
     */
    private $reviewHelper;

    /**
     * @var ReviewStatus
     */
    private $reviewStatus;

    /**
     * @var RepresentativeProductsHelper
     */
    private $representativeProductsHelper;

    /**
     * @var StoreHelper
     */
    private $storeHelper;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * @var ProductHelper
     */
    private $productHelper;

    /**
     * @var Html
     */
    private $htmlHelper;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param CategoryFactory $categoryFactory
     * @param AiCategoryManager $aiCategoryManager
     * @param GeneratedText $generatedText
     * @param FieldHelper $fieldHelper
     * @param MarkReview $markReview
     * @param ReviewHelper $reviewHelper
     * @param ReviewStatus $reviewStatus
     * @param RepresentativeProductsHelper $representativeProductsHelper
     * @param StoreHelper $storeHelper
     * @param ProductRepositoryInterface $productRepository
     * @param ProductHelper $productHelper
     * @param Html $htmlHelper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        CategoryFactory $categoryFactory,
        AiCategoryManager $aiCategoryManager,
        GeneratedText $generatedText,
        FieldHelper $fieldHelper,
        MarkReview $markReview,
        ReviewHelper $reviewHelper,
        ReviewStatus $reviewStatus,
        RepresentativeProductsHelper $representativeProductsHelper,
        StoreHelper $storeHelper,
        ProductRepositoryInterface $productRepository,
        ProductHelper $productHelper,
        Html $htmlHelper,
        StoreManagerInterface $storeManager
    ) {
        $this->categoryFactory = $categoryFactory;
        $this->aiCategoryManager = $aiCategoryManager;
        $this->generatedText = $generatedText;
        $this->fieldHelper = $fieldHelper;
        $this->markReview = $markReview;
        $this->reviewHelper = $reviewHelper;
        $this->reviewStatus = $reviewStatus;
        $this->representativeProductsHelper = $representativeProductsHelper;
        $this->storeHelper = $storeHelper;
        $this->productRepository = $productRepository;
        $this->productHelper = $productHelper;
        $this->htmlHelper = $htmlHelper;
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        try {
            $params = $this->getRequest()->getParams();

            $mappingSettings = $this->fieldHelper->getMappingSettings();

            $selectedRepresentativeProducts = $this->getSelectedRepresentativeProducts($params);
            $categories = [];
            $resultFields = [];

            foreach ($params['selected_stores'] as $storeId) {
                $language = $this->storeHelper->getFormattedLanguage($storeId);

                /** get image alt texts for representative products */
                $imageAltTexts = [];
                foreach ($selectedRepresentativeProducts as $productData) {
                    try {
                        $product = $this->productRepository->getById($productData->value, false, $storeId, true);
                    } catch (\Exception $e) {
                        continue;
                    }

                    $productImages = $this->productHelper->getPublishedImages($product, $storeId, $language);
                    if (is_array($productImages)) {
                        $imageAltTexts = array_merge($imageAltTexts, $productImages);
                    }
                }

                /** process transfer */
                $category = $this->categoryFactory->create()->setStoreId($storeId)->load($params['category_id']);
                foreach ($params['selected_fields'] as $field => $value) {
                    if ($field === 'category_description') {
                        $value = $this->convertMediaUrl($value);
                    }
                    if ($imageAltTexts) {
                        $value = $this->htmlHelper->addAltTextToContentViaPreg($value, $imageAltTexts);
                    }
                    $category->setData($mappingSettings[$field], $value);
                    $resultFields[$field] = $value;
                }

                $category->save();
                $categories[$storeId] = $category;
            }

            $this->generatedText->saveCategoryText(
                $params['store_id'],
                $params['category_id'],
                $params['selected_fields']
            );
            
            $this->aiCategoryManager->saveDate($params['category_id'], $params['store_id'], 'transferred');
            $this->aiCategoryManager->saveDate($params['category_id'], $params['store_id'], 'reviewed');

            $this->reviewStatus->updateReview(
                array_keys($params['selected_fields']),
                $params['category_id'],
                $params['selected_stores'],
                $categories
            );

            $useDefault = [];
            foreach ($mappingSettings as $field => $value) {
                $useDefault[$field] = $this->fieldHelper->isUsingDefaultValues(
                    $category,
                    $params['store_id'],
                    $value
                );
            }

            $result = [
                'success' => true,
                'reviewed' => $this->markReview->getReviewed($params['category_id'], $params['store_id']),
                'fields' => $resultFields,
                'updatedReview' => $this->reviewHelper->getCategoryReviewStatus(
                    $params['category_id'],
                    $params['store_id']
                ),
                'use_default' => $useDefault
            ];
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }

            $result = [
                'success' => false,
                'message' => $message
            ];
        }

        $response->setData($result);

        return $response;
    }

    /**
     * Get selected representative products
     *
     * @param array $params
     * @return array
     */
    private function getSelectedRepresentativeProducts($params)
    {
        $aiCategory = $this->aiCategoryManager->getCategory(
            $params['category_id'],
            $params['store_id']
        );
        $selectedRepresentativeProducts = $this->representativeProductsHelper
            ->getRepresentativeProductsSelected($aiCategory);

        return $selectedRepresentativeProducts;
    }

    /**
     * Convert media URL
     *
     * @param string $content
     *
     * @return string
     */
    public function convertMediaUrl($content)
    {
        if (empty($content)) {
            return $content;
        }

        $mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

        // Decode HTML entities (e.g., &quot; → ")
        $decodedContent = html_entity_decode($content);

        // Replace {{media url="..."}} with real media URL
        $convertedContent = preg_replace_callback(
            '/{{media url=["\']([^"\']+)["\']}}/',
            function ($matches) use ($mediaBaseUrl) {
                return $mediaBaseUrl . ltrim($matches[1], '/');
            },
            $decodedContent
        );

        return $convertedContent;
    }
}
