<?php

namespace Easymailing\App\Controller\Admin;

use Easymailing\App\Core\Http\Request;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;
use Easymailing\App\Core\Provider\Woocommerce\Service\BatchEnqueueManager;
use Easymailing\App\Core\Provider\Woocommerce\Service\MetadataHelper;
use Easymailing\App\Core\Provider\WoocommerceHooksProvider;
use Easymailing\App\Model\SynchronizationConfig;

class ResetController extends BaseSynchronizationController
{
    public function indexAction(): void
    {
	    $this->checkConfig();
	    $this->checkGeneralData();
        $request = $this->getRequest();
	    $synchronizationConfig = $this->getSynchronizationConfig();


        if ($request->getMethod() === Request::METHOD_GET) {
	        $this->render('Admin/Synchronization/reset.php', [
		        'current_page' => 3,
		        'synchronizationConfig' => $synchronizationConfig
	        ]);
            return;
        }

        if ($request->getMethod() === Request::METHOD_POST) {

            $this->handlePostRequest($request);
        }
    }


    /**
     * Maneja la solicitud POST para eliminar la configuración.
     */
    private function handlePostRequest($request): void
    {
        $key = $request->request->get("key");

        if ($key !== "DELETE") {
	        $this->getFlashBag()->add('warning', __('Escribe DELETE para confirmar el borrado','easymailing'));
	        $this->redirectToMenuPage('easymailing_synchronization_reset');
            return;
        }

		try {
			$this->resetPlugin();
//			$this->getFlashBag()->add('success', __('Configuración eliminada correctamente','easymailing'));
			$this->redirectToMenuPage('easymailing_synchronization_configuration');
		}catch(\Exception $e){
			$this->getContainer()->get('log_manager')->createLog(LogType::ERROR, $e->getMessage());
			$this->getFlashBag()->add('error', sprintf("%s: %s", __('Error al eliminar la tienda','easymailing'), $e->getMessage()));
			$this->redirectToMenuPage('easymailing_synchronization_reset');
		}

    }

    private function resetPlugin(): void
    {
        $repository = $this->getContainer()->get('config_repository');
	    $synchronizationConfig = $repository->getSynchronizationConfig();
        $client = $this->getApiClient();

        if (empty($synchronizationConfig->getShopId())) {
            throw new \Exception(__('No tienes ninguna tienda configurada','easymailing'));
        }

		try {
			$client->deleteStore($synchronizationConfig->getShopId());
		}catch(\Exception $e){

		}

        $this->resetConfig($synchronizationConfig);
        $repository->saveSynchronizationConfig($synchronizationConfig);
        MetadataHelper::reset();
		$this->getContainer()->get('log_manager')->deleteAllLogs();

		WoocommerceHooksProvider::unschedulePendingActions(BatchEnqueueManager::SYNCHRONIZATION_BACKGROUND_TASK, BatchEnqueueManager::ENQUEUE_GROUP);
		WoocommerceHooksProvider::unschedulePendingActions(BatchEnqueueManager::SYNCHRONIZATION_CHECK_BACKGROUND_TASK, BatchEnqueueManager::ENQUEUE_GROUP);
    }

    /**
     * Resetea la configuración de la tienda en el objeto $config.
     */
    private function resetConfig(SynchronizationConfig $config): void
    {
        $config->setShopId("");
        $config->setShopName("");
        $config->setShopDomain("");
        $config->setLanguage("");
        $config->setTimeZone("");
        $config->setAudience("");
        $config->setGroup("");
        $config->setLastBatchOperationId("");
        $config->setTreatmentPurposes([]);
        $config->setBooleanListFields([]);
        $config->setOnlyCustomers(false);
    }


}
