<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-cache-warmer
 * @version   1.11.13
 * @copyright Copyright (C) 2026 Mirasvit (https://mirasvit.com/)
 */




namespace Mirasvit\CacheWarmer\Controller\Adminhtml\Source;


use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Mirasvit\CacheWarmer\Api\Data\SourceInterface;
use Mirasvit\CacheWarmer\Api\Repository\PageRepositoryInterface;
use Mirasvit\CacheWarmer\Api\Repository\SourceRepositoryInterface;
use Mirasvit\CacheWarmer\Controller\Adminhtml\AbstractSource;
use Magento\Framework\Serialize\SerializerInterface;
use Mirasvit\CacheWarmer\Model\Config;

class Delete extends AbstractSource
{
    private $pageRepository;

    public function __construct(
        PageRepositoryInterface $pageRepository,
        SourceRepositoryInterface $sourceRepository,
        Registry $registry,
        Config $config,
        Context $context,
        SerializerInterface $serializer
    ) {
        $this->pageRepository = $pageRepository;

        parent::__construct($sourceRepository, $registry, $config, $context, $serializer);
    }

    /**
     * {@inheritdoc}
     * 
     * * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        $id       = $this->getRequest()->getParam(SourceInterface::ID);
        $selected = $this->getRequest()->getParam('selected');
        $excluded = $this->getRequest()->getParam('excluded');

        if ($id) {
            try {
                if (!$this->deleteById((int)$id)) {
                    $this->messageManager->addErrorMessage(__('The Default source can not be deleted'));

                    return $this->resultRedirectFactory->create()->setPath('*/*/');
                }
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            }

            $this->messageManager->addSuccessMessage(__('Source was removed'));
        } elseif ($selected && count($selected)) { // massDelete selected
            $sources = $this->sourceRepository->getCollection(false)
                ->addFieldToFilter(SourceInterface::ID, ['in' => $selected]);

            try {
                foreach ($sources as $source) {
                    if (!$this->deleteById((int)$source->getId())) {
                        $this->messageManager->addErrorMessage(__('The Default source can not be deleted'));

                        return $this->resultRedirectFactory->create()->setPath('*/*/');
                    }
                }
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            }

            $this->messageManager->addSuccessMessage(__('Sources were removed'));
        } elseif ($excluded && count($excluded)) { // massDelete excluded
            $sources = $this->sourceRepository->getCollection(false)
                ->addFieldToFilter(SourceInterface::ID, ['nin' => $excluded]);

            try {
                foreach ($sources as $source) {
                    if (!$this->deleteById((int)$source->getId())) {
                        $this->messageManager->addErrorMessage(__('The Default source can not be deleted'));

                        return $this->resultRedirectFactory->create()->setPath('*/*/');
                    }
                }
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            }

            $this->messageManager->addSuccessMessage(__('Sources were removed'));
        } else {
            $this->messageManager->addErrorMessage(__('Please select any Source except the Default source'));
        }

        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }

    private function deleteById(int $id): bool
    {
        /** @var SourceInterface $defaultSource */
        $defaultSource = $this->sourceRepository->getDefaultSource();

        if ($id == $defaultSource->getId()) {
            return false;
        }

        $model = $this->sourceRepository->get($id);

        $pageCollection = $this->pageRepository
            ->getCollection()
            ->addFieldToFilter('source_id', $model->getId());

        foreach ($pageCollection as $page) {
            if ($page->getPopularity() > 0 && $defaultSource) {
                $page->setSourceId($defaultSource->getId());
                $this->pageRepository->save($page);
            } else {
                $this->pageRepository->delete($page);
            }
        }

        $this->sourceRepository->delete($model);

        return true;
    }
}
