<?php

namespace App\Helper;

use App\Repository\ProductRepository;
use App\Repository\StockRepository;
use App\Repository\WarehouseRepository;
use Psr\Log\LoggerInterface;
use League\Csv\Writer;


class Jtl
{
    private $productRepository;
    private $stockRepository;
    private $warehouseRepository;
    private $logger;

    /**
     * @var string[] $arrLager
     * Lagernamen aus der JTL Wawi
     */
    private $arrLager = array(
        1 => 'Lager 1 - Standardlager',
        3 => 'Lager 3 - DLX',
        5 => 'Lager 5 - Verkaufsfilale',
        8 => 'Lager 8 - Standardlager',
        10 => 'Lager 10 - OJ EF',
    );

    public function __construct(ProductRepository $productRepository,WarehouseRepository $warehouseRepository,StockRepository $stockRepository, LoggerInterface $logger)
    {
        $this->productRepository = $productRepository;
        $this->warehouseRepository = $warehouseRepository;
        $this->stockRepository = $stockRepository;
        $this->logger = $logger;
    }

    /**
     * Holt alle Produkte und deren Lagerbestände
     * @return array
     */
    public function getProducts(): array
    {

        $r = $this->productRepository->findAll();

        $data = array();

        foreach($r as $product){
            $stock = $this->stockRepository->findBy(['product_id'=>$product->getId()]);

            if($stock){
                foreach($stock as $s){
                    $warehouse = $s->getWarehouse();
                    $warehouseName = $warehouse->getName();

                    $data[$product->getId().$warehouseName] = [
                        'gtin' => $product->getGtin(),
                        'stock' => $s->getInstock(),
                        'warehouse' => $this->arrLager[$warehouseName] ?? 'Lager ' . $warehouseName
                    ];

                }
            }else{
                $data[$product->getId()] = [
                    'gtin' => $product->getGtin(),
                    'stock' => 0,
                    'warehouse' => 0
                ];

                $this->logger->info('No stock for product '.$product->getId());
            }
        //   dump($data);

        }

        return $data;
    }


    /**
     * @param $data
     * @return void
     */
    public function createExportFile($data): void
    {
        try {
            $writer = Writer::createFromPath(getcwd().'/jtl/cds-export.csv', 'w+');
            $bytes = $writer->insertAll(new \ArrayIterator($data));

            if($bytes){
                $this->logger->info('Exported '.$bytes.' bytes');

                $FTP = new Ftp();
                $FTP->uploadFile(getcwd().'/jtl/cds-export.csv');
            }

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




}