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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Setup;
use Magento\Framework\App\CacheInterface;

class Reset extends \Magento\Backend\App\Action
{
    /**
     * Cache key prefix for premium credit
     */
    const CACHE_KEY_PREFIX_PREMIUM_CREDIT = 'wtai_premium_credit_';

    /**
     * Cache key prefix for user web tokens
     */
    const CACHE_KEY_PREFIX_USER_WEB_TOKEN = 'wtai_user_web_token_';

    /**
     * @var \Magento\Framework\Controller\ResultFactory
     */
    protected $resultFactory;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory
     */
    protected $configCollectionFactory;

    /**
     * @var \Magento\Config\Model\ResourceModel\Config\Data
     */
    protected $configResource;

    /**
     * @var \Magento\Framework\App\Cache\Manager
     */
    protected $cacheManager;

    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resource;

    /**
     * @var \WriteTextAI\WriteTextAI\Model\Api\Session
     */
    protected $session;

    /**
     * @var CacheInterface
     */
    protected $cache;

    /**
     * Constructor
     *
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory $configCollection
     * @param \Magento\Config\Model\ResourceModel\Config\Data $configResource
     * @param \Magento\Framework\App\Cache\Manager $cacheManager
     * @param \Magento\Framework\App\ResourceConnection $resource
     * @param CacheInterface $cache
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory $configCollection,
        \Magento\Config\Model\ResourceModel\Config\Data $configResource,
        \Magento\Framework\App\Cache\Manager $cacheManager,
        \Magento\Framework\App\ResourceConnection $resource,
        \WriteTextAI\WriteTextAI\Model\Api\Session $session,
        CacheInterface $cache
    ) {
        $this->messageManager = $messageManager;
        $this->configCollectionFactory = $configCollection;
        $this->configResource = $configResource;
        $this->cacheManager = $cacheManager;
        $this->resource = $resource;
        $this->session = $session;
        $this->cache = $cache;
        parent::__construct($context);
    }

    /**
     * Reset action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $collection = $this->configCollectionFactory->create();
        $collection->addPathFilter('writetextai_settings');

        foreach ($collection as $config) {
            $this->configResource->delete($config);
        }
        $connection = $this->resource->getConnection();
        $this->dropTables($connection);

        $this->cacheManager->clean(['config']);
        
        $getUser = $this->session->getCurrentUser();
        if ($getUser) {
            $userId = $getUser->getId();
            $this->cache->remove(self::CACHE_KEY_PREFIX_USER_WEB_TOKEN . $userId);
        }

        $this->cache->remove(self::CACHE_KEY_PREFIX_PREMIUM_CREDIT);

        $this->messageManager->addSuccess(__('Reset successful!'));

        $resultRedirect = $this->resultRedirectFactory->create();

        return $resultRedirect->setPath('wtai/setup/index');
    }

    /**
     * Drop tables
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     */
    protected function dropTables($connection)
    {
        $tablesToDrop = [
            "writetextai_writetextai_products_store",
            "writetextai_writetextai_categories_store",
            "writetextai_writetextai_settings",
            "writetextai_writetextai_user_fields_selected",
            "writetextai_writetextai_user_web_token",
            "writetextai_writetextai_bulk_generate_requests",
            "writetextai_writetextai_bulk_transfer_requests",
            "writetextai_writetextai_bulk_keyword_analysis_requests",
            "writetextai_writetextai_user_feedback",
            "writetextai_writetextai_single_generate_requests",
            "writetextai_writetextai_product_reference_product",
            "writetextai_writetextai_product_keywords",
            "writetextai_writetextai_user_request_status",
            "writetextai_writetextai_product_keyword_ideas_filters",
            "writetextai_writetextai_product_keyword_ranked_filters",
            "writetextai_writetextai_product_keyword_competitor_filters"
        ];

        foreach ($tablesToDrop as $table) {
            $tableName = $this->resource->getTableName($table);
            if ($connection->isTableExists($tableName)) {
                $connection->truncateTable($tableName);
            }
        }
    }
}
