<?php

namespace App\Command;

use App\Helper\Shopware;
use App\Repository\ProductRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'sw:push-stock',
    description: 'Übermittelt den Bestand an Shopware',
)]
class SwPushStockCommand extends Command
{

    private $productRepository;
    private $logger;

    public function __construct(ProductRepository $productRepository, LoggerInterface $logger)
    {
        $this->productRepository = $productRepository;
        $this->logger = $logger;
        parent::__construct();
    }


    protected function configure(): void
    {
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
//        $arg1 = $input->getArgument('arg1');

//        if ($arg1) {
//            $io->note(sprintf('You passed an argument: %s', $arg1));
//        }
//
//        if ($input->getOption('option1')) {
//            // ...
//        }

        $shopware = new Shopware($this->logger);


        $products = $this->getProducts();

        if (count($products) > 0) {

            foreach ($products as $product) {

                //prüfen ob Shopware ID vorhanden
                if($product->getShopwareId() == null) {

                   $swID = $this->getShopwareId($product);

                   if($swID != null) {
                       $product->setShopwareId($swID->id);
                   }else{
                       continue;
                   }
                }


                $shopware->setProduct($product);
            }
        }

        $io->success('Done.');

        return Command::SUCCESS;
    }

    protected function getProducts()
    {
        $products = $this->productRepository->findAll();
        $arrProducts = array();
        foreach ($products as $product) {
            $arrProducts[$product->getGtin()] = $product;
        }

        return $arrProducts;
    }

    /**
     * @param Product $product
     * @return int|null
     */
    protected function getShopwareId($product)
    {
        $shopware = new Shopware($this->logger);
        $shopwareProduct = $shopware->getShopwareIdbyGtin($product->getGtin());
        if($shopwareProduct != null) {
            //dump($shopwareProduct);
            $product->setShopwareId($shopwareProduct->id);
            $this->productRepository->save($product, true);
        }

        return $shopwareProduct;

    }



}
