<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 26.06.24
 */


namespace App\Service;


use App\Entity\Partner;
use App\Entity\Product;
use App\Entity\User;
use App\Enum\PartnerType;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\HttpKernel\KernelInterface;

class NavisionDataImportService
{
    private User $systemUser;

    public function __construct(
        private KernelInterface $kernel,
        private EntityManagerInterface $em
    )
    {
        $this->systemUser = $this->em->getRepository(User::class)->findOneBy(['email' => $_ENV['ADMIN_EMAIL']]);
        if ($this->systemUser === null) {
            throw new \Exception('System user not found!');
        }
    }

    public function importCustomers()
    {
        $customers = $this->em->getRepository(Partner::class)->findBy(['type' => PartnerType::Customer]);
        $customersByNavisionId = [];
        /** @var Partner $customer */
        foreach ($customers as $customer) {
            if ($customer->getNavisionId() !== null) {
                $customersByNavisionId[$customer->getNavisionId()] = $customer;
            }
        }

        $data = $this->readExcelFile($this->kernel->getProjectDir()."/import/Stammdaten-Kreditoren-2024-12-16.xlsx");
        $i = 0;
        $customer = null;
        foreach ($data as $row) {
            if ($i >= 3) {
                $name = $row[2];
                $navisionId = $row[0];
                if ($name !== "" && ctype_digit($navisionId)) {
                    if (array_key_exists($navisionId, $customersByNavisionId)) {
                        $customer = $customersByNavisionId[$navisionId];
                    } else {
                        $customer = new Partner($this->systemUser);
                        $customer->setType(PartnerType::Customer);
                        $customer->setNavisionId($navisionId);
                    }
                    $customer->setName($row[2]);
                    $customer->setNameAddition($row[3]);
                    $customer->setStreet($row[4]);
                    $customer->setAddressAddition($row[5]);
                    $customer->setZip($row[6]);
                    $customer->setCity($row[7]);
                    $customer->setCountry($row[8]);
                    $customer->setPhone($row[9]);
                    $customer->setLanguage($row[10]);
                    $customer->setCurrency($row[11]);
                    $customer->setPaymentCondition($row[12]);
                    $customer->setDeliveryCondition($row[13]);
                    $customer->setBusinessGroup($row[15]);
                    $customer->setVatBusinessGroup($row[16]);
                    $this->em->persist($customer);
                }
            }
            $i++;
        }
        $this->em->flush();
    }

    public function importSuppliers()
    {
        $suppliers = $this->em->getRepository(Partner::class)->findBy(['type' => PartnerType::Supplier]);
        $suppliersByNavisionId = [];
        /** @var Partner $supplier */
        foreach ($suppliers as $supplier) {
            if ($supplier->getNavisionId() !== null) {
                $suppliersByNavisionId[$supplier->getNavisionId()] = $supplier;
            }
        }

        $data = $this->readExcelFile($this->kernel->getProjectDir()."/import/Stammdaten-Debitoren-2024-12-16.xlsx");
        $i = 0;
        $supplier = null;
        foreach ($data as $row) {
            if ($i >= 3) {
                $name = $row[2];
                $navisionId = $row[0];
                if ($name !== "" && ctype_digit($navisionId)) {
                    if (array_key_exists($navisionId, $suppliersByNavisionId)) {
                        $supplier = $suppliersByNavisionId[$navisionId];
                    } else {
                        $supplier = new Partner($this->systemUser);
                        $supplier->setType(PartnerType::Supplier);
                        $supplier->setNavisionId($navisionId);
                    }
                    $supplier->setName($row[2]);
                    $supplier->setNameAddition($row[3]);
                    $supplier->setStreet($row[4]);
                    $supplier->setAddressAddition($row[5]);
                    $supplier->setZip($row[6]);
                    $supplier->setCity($row[7]);
                    $supplier->setCountry($row[8]);
                    $supplier->setPhone($row[9]);
                    $supplier->setLanguage($row[10]);
                    $supplier->setCurrency($row[11]);
                    $supplier->setPaymentCondition($row[12]);
                    $supplier->setCreditLimit($row[13]);
                    $supplier->setBusinessGroup($row[15]);
                    $supplier->setVatBusinessGroup($row[16]);
                    $supplier->setRoutePoint($row[17]);
                    $this->em->persist($supplier);
                }
            }
            $i++;
        }
        $this->em->flush();
    }

    public function importProducts()
    {
        $products = $this->em->getRepository(Product::class)->findAll();
        $productsByNavisionId = [];
        /** @var Product $product */
        foreach ($products as $product) {
            if ($product->getNavisionId() !== null) {
                $productsByNavisionId[$product->getNavisionId()] = $product;
            }
        }

        $data = $this->readExcelFile($this->kernel->getProjectDir()."/import/Stammdaten-Artikel-2024-12-16.xlsx");
        $i = 0;
        $product = null;
        foreach ($data as $row) {
            if ($i >= 3) {
                $name = $row[2];
                $navisionId = $row[0];
                if ($name !== "" && ctype_digit($navisionId)) {
                    if (array_key_exists($navisionId, $productsByNavisionId)) {
                        $product = $productsByNavisionId[$navisionId];
                    } else {
                        $product = new Product($this->systemUser);
                        $product->setNavisionId($navisionId);
                    }
                    $product->setName($row[2]);
                    $product->setDescription($row[3]);
                    $product->setBlocked($row[4] === "Ja" || $row[4] === "TRUE");
                    $product->setInventory($row[5]);
                    $product->setBaseUnit($row[6]);
                    $product->setBuyUnit($row[7]);
                    $product->setSellUnit($row[8]);
                    $product->setTrackingCode($row[9]);
                    $product->setProductGroup($row[10]);
                    $product->setCustomsPosition($row[11]);
                    $product->setProductBookingGroup($row[12]);
                    $product->setVatProductBookingGroup($row[13]);
                    $this->em->persist($product);
                }
            }
            $i++;
        }
        $this->em->flush();
    }

    private function readExcelFile(string $filePath): array
    {
        // Load the spreadsheet
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $data = [];

        // Iterate through each row in the spreadsheet
        foreach ($sheet->getRowIterator() as $row) {
            $rowData = [];
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);

            foreach ($cellIterator as $cell) {
                $rowData[] = $cell->getValue();
            }

            $data[] = $rowData;
        }

        return $data;
    }
}