<?php

namespace Easymailing\App\Controller\Admin;


use Easymailing\App\Core\Http\Request;
use Easymailing\App\Core\Provider\Woocommerce\Model\BatchSynchronizationStatus;
use Easymailing\App\Core\Provider\Woocommerce\Service\MetadataHelper;



class SynchronizationConfigurationController extends BaseSynchronizationController
{

    public function indexAction(): void
    {
        $request = $this->getRequest();
        $this->checkConfig();

        if ($request->getMethod() === Request::METHOD_GET) {
            $this->renderGeneralData();
        } else {
            $this->processPostRequest($request);
        }
    }

    private function renderGeneralData($errors = []): void
    {
        $client = $this->getApiClient();
	    $synchronizationConfig = $this->getSynchronizationConfig();
        $audiences = $client->getAudiences();

        $this->render('Admin/Synchronization/Config/configuration.php', [
            'current_page' => 1,
            'audiences' => $audiences,
            'errors' => $this->processErrors($errors),
            'shop_name' => !empty($synchronizationConfig->getShopName()) ? $synchronizationConfig->getShopName(): get_option('blogname'),
            'shop_domain' => !empty($synchronizationConfig->getShopDomain()) ? $synchronizationConfig->getShopDomain() : get_site_url(),
            'shopId' => $synchronizationConfig->getShopId(),
            'use_account_email' => $synchronizationConfig->isUseAccountEmail(),
            'validate_checkout_phone' => $synchronizationConfig->isValidateCheckoutPhone(),
            'timezones' => timezone_identifiers_list(),
        ]);

    }

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

        // Si la tienda ya está creada, los datos iniciales son inmutables (readonly).
        // Solo actualizamos las opciones avanzadas editables.
        if (!empty($synchronizationConfig->getShopId())) {
            $synchronizationConfig->setUseAccountEmail($request->request->get('use_account_email') === '1');
            $synchronizationConfig->setValidateCheckoutPhone($request->request->get('validate_checkout_phone') === '1');
            $repository->saveSynchronizationConfig($synchronizationConfig);
            $this->getFlashBag()->add('success', __('Opciones avanzadas guardadas correctamente.', 'easymailing'));
            $this->redirectToMenuPage('easymailing_synchronization_configuration');
            return;
        }

        $errors = $this->validateRequest($request);

        if (empty($errors)) {
            $this->syncShop($request);
	        $this->redirectToMenuPage('easymailing_synchronization_configuration_settings');
	        $this->getFlashBag()->add('success', __('Datos guardados correctamente','easymailing'));
        }

	    $this->renderGeneralData($errors);
    }

    private function validateRequest($request): array
    {
        $errors = [];
        $shopName = $request->request->get('shopname');
        $shopDomain = $request->request->get('shopdomain');
        $language = $request->request->get('language');
        $timeZone = $request->request->get('timezone');
        $audience = $request->request->get('audience-select');
        $enableLogs = $request->request->get('enableLogs');


        if (empty($shopName)) $errors['name'] = __('Rellena el nombre','easymailing');
        if (empty($shopDomain)) $errors['domain'] = __('Rellena el dominio', 'easymailing');
        if(!filter_var($shopDomain, FILTER_VALIDATE_URL)) $errors['domain'] = __('Introduce un dominio válido. ejemplo: https://mi-tienda.com', 'easymailing');
        if (!isset($language)) $errors['language'] = __('Selecciona el idioma', 'easymailing');
        if (!isset($timeZone)) $errors['timezone'] = __('Selecciona la zona horaria'. 'easymailing');
        if (!isset($audience)) $errors['audience'] = __('Selecciona la audiencia', 'easymailing');
        if (!isset($enableLogs)) $errors['enableLogs'] = __('Selecciona la opción logs de depuración', 'easymailing');

        return $errors;
    }

    private function updateConfig($shopId, $request): void
    {
		$repository = $this->getContainer()->get('config_repository');
	    $synchronizationConfig = $this->getSynchronizationConfig();
	    $config = $this->getConfig();

	    $synchronizationConfig->setShopId($shopId);
	    $synchronizationConfig->setShopName($request->request->get('shopname'));
	    $synchronizationConfig->setShopDomain($request->request->get('shopdomain'));
	    $synchronizationConfig->setLanguage($request->request->get('language'));
	    $synchronizationConfig->setAudience($request->request->get('audience-select'));
	    $synchronizationConfig->setGroup($request->request->get('group-select'));
	    $synchronizationConfig->setTimeZone($request->request->get('timezone'));
	    $synchronizationConfig->setEnableLogs($request->request->get('enableLogs'));
	    $synchronizationConfig->setUseAccountEmail($request->request->get('use_account_email') === '1');
	    $synchronizationConfig->setValidateCheckoutPhone($request->request->get('validate_checkout_phone') === '1');
	    $synchronizationConfig->setAppDomain($config->getMySuscription()->domain);
//	    $synchronizationConfig->setOnlyCustomers($request->request->get('only_customers'));

	    $audience = $this->getApiClient()->getAudienceArrayById($request->request->get('audience-select'));
	    $synchronizationConfig->setAudienceJson(json_encode($audience));

        $repository->saveSynchronizationConfig($synchronizationConfig);
    }



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

        if (empty($synchronizationConfig->getShopId())) {
            $this->createShop($client, $request);
            $this->enqueueSynchronization();

        }
    }

    private function createShop($client, $request): void
    {
        $uuid = wp_generate_uuid4();
        $store = $client->createStore([
            "resource_id" => $uuid,
            "name" => $request->request->get('shopname'),
            "domain" => $request->request->get('shopdomain'),
            "locale" => $request->request->get('language'),
            "timezone" => $request->request->get('timezone'),
            "group" => $request->request->get('group-select'),
            "platform" => "Woocommerce",
            "audience" => $request->request->get('audience-select')
        ]);

        $this->updateConfig($uuid, $request);
    }

    private function enqueueSynchronization(): void
    {
        update_option(MetadataHelper::getBatchSynchronizationStatus(), BatchSynchronizationStatus::SCHEDULED);
        $batchEnqueueManager = $this->getContainer()->get('batch_enqueue_manager');
        $batchEnqueueManager->enqueue(false);
    }

    private function processErrors($errors): array
    {
        return array_map(function ($key, $value) {
            return $value;
        }, array_keys($errors), $errors);
    }


    private function renderError($message): void
    {
        $this->render('Admin/Synchronization/error.php', ['message' => $message]);
    }
}
