<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Hooks;

use Easymailing\App\Api\Client;
use Easymailing\App\Core\Log\LogManager;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;
use Easymailing\App\Core\Provider\Woocommerce\Service\MetadataHelper;
use Easymailing\App\Core\Transient\FlashBag;
use Easymailing\App\Model\Category;
use Easymailing\App\Repository\ConfigRepository;

class CategoryHooks
{

    private $config;
    private $apiClient;
    private $flashBag;
    private $logManager;

    public function __construct(ConfigRepository $configRepository, Client $apiClient, FlashBag $flashBag, LogManager $logManager)
    {
        $this->config = $configRepository->getSynchronizationConfig();
        $this->apiClient = $apiClient;
        $this->flashBag = $flashBag;
        $this->logManager = $logManager;
    }

	public function synchronizeCategoryAdmin(int $categoryId): void
	{
		try {
			$this->updateCategory($categoryId);
			$this->flashBag->add('success', __("Categoría sincronizado en Easymailing correctamente", 'easymailing'));
		}catch(\Exception $e){
			$this->flashBag->add('error', __("Ocurrió un error al sincronizar la categoría", 'easymailing'));
		}
	}

    public function createCategory(int $categoryId): ?Category
    {
        try {
            $meta_key = MetadataHelper::getResourceId();
            $emCategoryId = get_term_meta($categoryId, $meta_key, true);
            if (!$emCategoryId) {;
                $emCategoryId = wp_generate_uuid4();
                update_term_meta($categoryId, $meta_key, $emCategoryId);
            }
            $categoryIri = "/stores" . "/" . $this->config->getShopId() . "/categories";
            $category = get_term($categoryId, 'product_cat');
            $thumbnailId = get_term_meta($categoryId, 'thumbnail_id', true);

            $body = [
                'resource_id' => $emCategoryId,
                'title' => $category->name,
                'image_url' => $thumbnailId ? wp_get_attachment_image_url($thumbnailId, 'full') : null
            ];

	        $category =  $this->apiClient->createCategory($categoryIri, $body);
	        update_term_meta($categoryId, MetadataHelper::getSynchronizationStatus(), 'success');
			return $category;

        } catch (\Exception $e) {
            $this->logManager->createLog(LogType::ERROR, sprintf("Error in createCategory: %s", $e->getMessage()));
            throw new \Exception($e);
        }
    }

    public function updateCategory($categoryId): ?Category
    {
        try {
            $meta_key = MetadataHelper::getResourceId();
            $emCategoryId = get_term_meta($categoryId, $meta_key, true);

            /** GET IF CATEGORY EXISTS IN EASYMAILING */
            $categoryIri = "/stores" . "/" . $this->config->getShopId() . "/categories" . "/" . $emCategoryId;
            $this->apiClient->getCategory($categoryIri);

            /** IF EXISTS UPDATE. ELSE ENTER CATCH BLOCK AND CALL TO CREATE */
            $category = get_term($categoryId, 'product_cat');
            $thumbnailId = get_term_meta($categoryId, 'thumbnail_id', true);

            $body = [
                'title' => $category->name,
                'image_url' => $thumbnailId ? wp_get_attachment_image_url($thumbnailId, 'full') : null
            ];
            $emCategory = $this->apiClient->updateCategory($categoryIri, $body);
            update_term_meta($categoryId, MetadataHelper::getSynchronizationStatus(), 'success');
            return $emCategory;

        } catch (\Exception $e) {
            if ($e instanceof \Easymailing\App\Api\Exception\NotFoundException) {
                return $this->createCategory($categoryId);
            } else {
                update_term_meta($categoryId, MetadataHelper::getSynchronizationStatus(), 'error');
	            $this->logManager->createLog(LogType::ERROR, sprintf("Error in update Category: %s", $e->getMessage()));
                throw new \Exception($e);
            }
        }
    }
}
