<?php

namespace App\Helper;




use Psr\Log\LoggerInterface;

use Vin\ShopwareSdk\Client\AdminAuthenticator;
use Vin\ShopwareSdk\Client\GrantType\ClientCredentialsGrantType;
use Vin\ShopwareSdk\Data\Context;
use Vin\ShopwareSdk\Data\Criteria;
use Vin\ShopwareSdk\Data\Entity\Order\OrderDefinition;
use Vin\ShopwareSdk\Data\Entity\Product\ProductDefinition;
use Vin\ShopwareSdk\Data\Filter\EqualsFilter;
use Vin\ShopwareSdk\Factory\RepositoryFactory;

class Shopware
{
    private $logger;
    public function __construct(LoggerInterface $logger)
    {

        $this->logger = $logger;

        //parent::__construct();
    }

    /**
     * Anmeldung bei der Shopwar API
     * @return \Vin\ShopwareSdk\Data\AccessToken|void
     */
    public function shopwareAuth()
    {

        try {
            $grantType = new ClientCredentialsGrantType($_ENV['SHOPWARE_API_ID'], $_ENV['SHOPWARE_API_KEY']);
            $adminClient = new AdminAuthenticator($grantType, $_ENV['SHOPWARE_API_URL']);

            return $adminClient->fetchAccessToken();
        } catch (\Exception $e) {
            dump($e->getMessage());
            $this->logger->error($e->getMessage());
        }
    }

    /**
     * @param string $orderId
     * @return OrderDefinition
     */
    public function getOrders(string $orderId):OrderDefinition{
        $context = new Context($_ENV['SHOPWARE_API_URL'], $this->shopwareAuth());

        // Create the repository for the entity
        $orderRepository = RepositoryFactory::create(OrderDefinition::ENTITY_NAME);

        // Create the criteria
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('id', $orderId));

        //Beziehungen zu Produkten holen
        $criteria->addAssociation('lineItems');
        $orders = false;


        try {
            $orders = $orderRepository->search($criteria, $context);

            //$value->setData((array)$orders->getEntities());
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
        }

        return $orders->getEntities();
    }

    /**
     * @param $prod
     */
    public function setProduct($prod): void
    {
        $context = new Context($_ENV['SHOPWARE_API_URL'], $this->shopwareAuth());

        //prüfen ob Shopware Produktid schon bekannt ist
        if($prod->getShopwareId() == null){
            $this->logger->error('Shopware Produkt ID ist nicht bekannt');
            return;
        }

        $productRepository = RepositoryFactory::create(ProductDefinition::ENTITY_NAME);

        #dump($prod->getShopwareId());

        try {
            $productRepository->update([
                'id' => $prod->getShopwareId(),
                'stock' => $prod->getStock()->getInStock()
            ], $context);
        } catch (\ShopwareResponseException $e) {
            $this->logger->error($e->getResponse());
        }

    }

    public function getShopwareIdbyGtin($gtin)
    {
        $context = new Context($_ENV['SHOPWARE_API_URL'], $this->shopwareAuth());

        // Create the repository for the entity
        $productRepository = RepositoryFactory::create(ProductDefinition::ENTITY_NAME);

        // Create the criteria
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('ean', $gtin));

        $products = $productRepository->search($criteria, $context);

        //dump($products->getEntities()->first());

        if($products->count() > 0){
            $productCollection = $products->getEntities();
            return $productCollection->first();
            //$prod->setShopwareId($products->getEntities()->first()->getId());
            //return $products->getEntities()->first();
        }else{
            return null;
        }

    }

}