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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\KeywordsOptimization;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Store\Model\StoreManagerInterface;
use WriteTextAI\WriteTextAI\Model\Api\Keywords;
use WriteTextAI\WriteTextAI\Model\Magento\Category;

class Update extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::keyword_analysis';

    /**
     * @var Keywords
     */
    protected $keywords;

    /**
     * @var Category
     */
    protected $category;

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

    /**
     * @var CategoryCollectionFactory
     */
    private $categoryCollectionFactory;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param Keywords $keywords
     * @param Category $category
     * @param ProductRepositoryInterface $productRepository
     * @param CategoryCollectionFactory $categoryCollectionFactory
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        Keywords $keywords,
        Category $category,
        ProductRepositoryInterface $productRepository,
        CategoryCollectionFactory $categoryCollectionFactory,
        StoreManagerInterface $storeManager
    ) {
        $this->keywords = $keywords;
        $this->category = $category;
        $this->productRepository = $productRepository;
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $entityType = $this->getRequest()->getParam('entity_type') ?? 'Product';
        $categoryProducts = [];
        $productCategories = [];
        if ($entityType === 'Category') {
            $categoryProducts = $this->category->getAllProductsNameRandomly(
                $this->getRequest()->getParam('record_id'),
                $this->getRequest()->getParam('store_id')
            );
        } else {
            $productCategories = $this->getProductCategoryPaths(
                (int) $this->getRequest()->getParam('record_id'),
                (int) $this->getRequest()->getParam('store_id')
            );
        }
        // try {
            $apiParams = [
                'store_id' => $this->getRequest()->getParam('store_id'),
                'record_id' => $this->getRequest()->getParam('record_id'),
                'url' => $this->getRequest()->getParam('url'),
                'name' => $this->getRequest()->getParam('name'),
                'search_intent_selected' => $this->getRequest()->getParam('search_intent_selected'),
                'seed_keywords' => $this->getRequest()->getParam('seed_keywords') ?? [],
                'entity_type' => $entityType,
                'products' => $categoryProducts,
                'categories' => $productCategories,
                'image_id' => $this->getRequest()->getParam('image_id'),
                'product_type' => $this->getRequest()->getParam('product_type')
            ];
            $apiResponse = $this->keywords->updateOptimization(
                $this->getRequest()->getParam('store_id'),
                $this->getRequest()->getParam('record_id'),
                $this->getRequest()->getParam('url'),
                $this->getRequest()->getParam('name'),
                $this->getRequest()->getParam('search_intent_selected'),
                $this->getRequest()->getParam('seed_keywords') ?? [],
                $entityType,
                $categoryProducts,
                $productCategories,
                $this->getRequest()->getParam('image_id'),
                $this->getRequest()->getParam('product_type')
            );
            $result = [
                'success' => true,
                'api_response' => $apiResponse,
                'api_params' => $apiParams
            ];
        // } 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,
        //         'error' => $message,
        //         'trace' => $e->getTrace()
        //     ];
        // }

            $response->setData($result);

            return $response;
    }

    /**
     * Get product category paths
     *
     * @param int $productId
     * @param int $storeId
     * @return array
     */
    private function getProductCategoryPaths(int $productId, int $storeId): array
    {
        try {
            try {
                $product = $this->productRepository->getById($productId, false, $storeId);
            } catch (\Exception $e) {
                return [];
            }

            $categoryIds = $product->getCategoryIds();
            if (!is_array($categoryIds) || empty($categoryIds)) {
                return [];
            }

            $rootCategoryId = null;
            try {
                $rootCategoryId = (int) $this->storeManager->getStore($storeId)->getRootCategoryId();
            } catch (\Exception $e) {
                $rootCategoryId = null;
            }

            $collection = $this->categoryCollectionFactory->create();
            $collection->setStoreId($storeId);
            $collection->addAttributeToSelect(['name', 'path']);
            $collection->addFieldToFilter('entity_id', ['in' => $categoryIds]);

            $allPathIds = [];
            $categoryPathIdsByCategoryId = [];
            foreach ($collection as $category) {
                $pathIds = $category->getPathIds();
                $filteredPathIds = [];
                foreach ($pathIds as $pathId) {
                    $pathId = (int) $pathId;
                    if ($pathId <= 2) {
                        continue;
                    }
                    if ($rootCategoryId !== null && $pathId === $rootCategoryId) {
                        continue;
                    }
                    $filteredPathIds[] = $pathId;
                    $allPathIds[$pathId] = true;
                }
                $categoryPathIdsByCategoryId[(int) $category->getId()] = $filteredPathIds;
            }

            if (empty($allPathIds)) {
                return [];
            }

            $allCategoriesCollection = $this->categoryCollectionFactory->create();
            $allCategoriesCollection->setStoreId($storeId);
            $allCategoriesCollection->addAttributeToSelect(['name']);
            $allCategoriesCollection->addFieldToFilter('entity_id', ['in' => array_keys($allPathIds)]);

            $nameLookup = [];
            foreach ($allCategoriesCollection as $category) {
                $nameLookup[(int) $category->getId()] = (string) $category->getName();
            }

            $paths = [];
            foreach ($categoryPathIdsByCategoryId as $categoryId => $pathIds) {
                $pathData = [];
                $pathNames = [];
                // Only include parent categories, not the current category
                foreach ($pathIds as $pathId) {
                    if (isset($nameLookup[$pathId]) && $nameLookup[$pathId] !== '') {
                        $pathNames[] = $nameLookup[$pathId];
                    }
                }
                
                // Create a single entry with the full path
                if (!empty($pathNames)) {
                    $categoryName = array_pop($pathNames);
       
                    $fullPath = implode('/', $pathNames);
                    $paths[] = [
                        'id' => (string) end($pathIds), // Use the last parent category ID as string
                        'name' => $categoryName, // Use the last parent category name
                        'path' => $fullPath
                    ];
                }
            }

            return $paths;
        } catch (\Exception $e) {
            return [];
        }
    }
}
