<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\Carrier;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\Filesystem;
use CpCreation\VitiCore\Shop\Model\ShippingAuto;
use CpCreation\VitiCore\Shop\Model\ShippingAutoSup;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use Symfony\Component\HttpFoundation\RequestStack;

final class TransvinsProvider implements CarrierProviderInterface
{
    public const TYPE = 'transvins';

    public function __construct(
        private RequestStack $requestStack,
        private Filesystem $filesystem,
        private EntityManagerInterface $em,
    ) {
    }

    /**
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function setData(ShippingConfig $config): void
    {
        $request = $this->requestStack->getCurrentRequest();
        if (!$request) {
            return;
        }

        $files = $request->files->get('shipping_config');
        if (!\is_array($files)) {
            return;
        }

        $file = $files['file']['file'] ?? null;
        $fileSup = $files['fileSup']['file'] ?? null;

        $reader = new Xlsx();
        $reader->setReadDataOnly(true);

        // =========================
        // FICHIER PRINCIPAL
        // =========================
        if ($file) {
            $xlsxPath = $this->filesystem->absolutePath('file', $config->getFile()->getPath());
            $spreadsheet = $reader->load($xlsxPath);

            $writer = new Csv($spreadsheet);
            $csvPath = $this->filesystem->absolutePath('file', 'transvins.csv');
            $writer->save($csvPath);

            $handle = fopen($csvPath, 'r');
            if (false === $handle) {
                return;
            }

            $classMetaData = $this->em->getClassMetadata(ShippingAuto::class);
            $connection = $this->em->getConnection();

            $connection->beginTransaction();
            try {
                (new CarrierTableTruncator())->truncate($connection, $classMetaData->getTableName());

                $shippingQtyCollection = [];
                $firstQty = false;

                while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                    $num = \count($data);

                    for ($c = 0; $c < $num; ++$c) {
                        $cell = $data[$c] ?? null;

                        if (
                            !$firstQty
                            && (
                                'Nombre maxi de cols' === $cell
                                || 'Nombre maxi de bouteilles' === $cell
                            )
                        ) {
                            for ($cc = 1; $cc < $num; ++$cc) {
                                if (($data[$cc] ?? '') === '') {
                                    continue;
                                }

                                if (1 === $cc) {
                                    $shippingQtyCollection[$cc]['of'] = 0;
                                    $shippingQtyCollection[$cc]['at'] = $data[$cc];
                                } elseif (mb_strstr((string) $data[$cc], '/')) {
                                    $integer = explode('/', (string) $data[$cc]);
                                    $shippingQtyCollection[$cc]['of'] = mb_trim((string) ($integer[0] ?? 0));
                                    $shippingQtyCollection[$cc]['at'] = mb_trim((string) ($integer[1] ?? 0));
                                } else {
                                    $shippingQtyCollection[$cc]['of'] = $data[$cc - 1];
                                    $shippingQtyCollection[$cc]['at'] = $data[$cc];
                                }
                            }

                            $firstQty = true;
                        }

                        if (
                            isset($data[0])
                            && is_numeric(mb_substr((string) $data[0], 0, 2))
                            && !str_contains((string) $data[0], 'Avenue de New-York')
                        ) {
                            for ($cc = 1; $cc < $num; ++$cc) {
                                if (($data[$cc] ?? '') === '') {
                                    continue;
                                }

                                $value = (float) str_replace(',', '.', (string) $data[$cc]);
                                if ($value <= 0) {
                                    continue;
                                }

                                $shipping = new ShippingAuto();
                                $shipping->setCountry('FR');
                                $shipping->setCounty(mb_substr((string) $data[0], 0, 2));

                                $shipping->setQtyOf($shippingQtyCollection[$cc]['of'] ?? 0);
                                $shipping->setQtyAt($shippingQtyCollection[$cc]['at'] ?? null);

                                if ($value > 10) {
                                    $shipping->setPackagePrice((int) ($value * 100));
                                } else {
                                    $shipping->setBottlePrice((int) ($value * 100));
                                }

                                $this->em->persist($shipping);
                            }
                        }
                    }
                }

                $this->em->flush();
                fclose($handle);

                $connection->commit();
            } catch (\Throwable $e) {
                fclose($handle);
                $connection->rollBack();
                throw $e;
            }
        }

        // =========================
        // FICHIER SUP
        // =========================
        if ($fileSup) {
            $xlsxSupPath = $this->filesystem->absolutePath('file', $config->getFileSup()->getPath());
            $spreadsheetSup = $reader->load($xlsxSupPath);

            $writerSup = new Csv($spreadsheetSup);
            $csvSupPath = $this->filesystem->absolutePath('file', 'transvins_sup.csv');
            $writerSup->save($csvSupPath);

            $handle = fopen($csvSupPath, 'r');
            if (false === $handle) {
                return;
            }

            $classMetaData = $this->em->getClassMetadata(ShippingAutoSup::class);
            $connection = $this->em->getConnection();

            $connection->beginTransaction();
            try {
                (new CarrierTableTruncator())->truncate($connection, $classMetaData->getTableName());

                while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                    $num = \count($data);

                    for ($c = 0; $c < $num; ++$c) {
                        if (!isset($data[0]) || !is_numeric(mb_substr((string) $data[0], 0, 2))) {
                            continue;
                        }

                        if (mb_strpos((string) ($data[2] ?? ''), '/')) {
                            $splitPostal = explode('/', (string) $data[2]);
                            if (mb_strlen((string) ($splitPostal[0] ?? '')) < 5) {
                                $splitPostal[0] = '0'.$splitPostal[0];
                            }
                            if (mb_strlen((string) ($splitPostal[1] ?? '')) < 5) {
                                $splitPostal[1] = '0'.$splitPostal[1];
                            }

                            if (mb_strpos((string) ($data[3] ?? ''), '/')) {
                                $splitCity = explode('/', (string) $data[3]);

                                $shippingSup1 = new ShippingAutoSup();
                                $shippingSup1->setCountry('FR');
                                $shippingSup1->setCounty(mb_substr((string) $data[0], 0, 2));
                                $shippingSup1->setPostal(mb_trim((string) ($splitPostal[0] ?? '')));
                                $city = mb_trim((string) $data[3]);
                                $shippingSup1->setOldName((string) ($splitCity[0] ?? ''));
                                $shippingSup1->setCity($city);
                                $this->em->persist($shippingSup1);

                                $shippingSup2 = new ShippingAutoSup();
                                $shippingSup2->setCountry('FR');
                                $shippingSup2->setCounty(mb_substr((string) $data[0], 0, 2));
                                $shippingSup2->setPostal(mb_trim((string) ($splitPostal[1] ?? '')));
                                $city = mb_trim((string) $data[3]);
                                $shippingSup2->setOldName((string) ($splitCity[1] ?? ''));
                                $shippingSup2->setCity($city);
                                $this->em->persist($shippingSup2);
                            } else {
                                $shippingSup1 = new ShippingAutoSup();
                                $shippingSup1->setCountry('FR');
                                $shippingSup1->setCounty(mb_substr((string) $data[0], 0, 2));
                                $shippingSup1->setPostal(mb_trim((string) ($splitPostal[0] ?? '')));
                                $city = mb_trim((string) $data[3]);
                                $shippingSup1->setOldName(mb_trim((string) ($data[3] ?? '')));
                                $shippingSup1->setCity($city);
                                $this->em->persist($shippingSup1);

                                $shippingSup2 = new ShippingAutoSup();
                                $shippingSup2->setCountry('FR');
                                $shippingSup2->setCounty(mb_substr((string) $data[0], 0, 2));
                                $shippingSup2->setPostal(mb_trim((string) ($splitPostal[1] ?? '')));
                                $city = mb_trim((string) $data[3]);
                                $shippingSup2->setOldName(mb_trim((string) ($data[3] ?? '')));
                                $shippingSup2->setCity($city);
                                $this->em->persist($shippingSup2);
                            }
                        } else {
                            if (mb_strlen((string) ($data[2] ?? '')) < 5) {
                                $data[2] = '0'.$data[2];
                            }

                            $shippingSup = new ShippingAutoSup();
                            $shippingSup->setCountry('FR');
                            $shippingSup->setCounty(mb_substr((string) $data[0], 0, 2));
                            $shippingSup->setPostal((string) ($data[2] ?? ''));
                            $city = mb_trim((string) ($data[3] ?? ''));
                            $shippingSup->setOldName(mb_trim((string) ($data[3] ?? '')));
                            $shippingSup->setCity($city);
                            $this->em->persist($shippingSup);
                        }

                        break;
                    }
                }

                $this->em->flush();
                fclose($handle);

                $connection->commit();
            } catch (\Throwable $e) {
                fclose($handle);
                $connection->rollBack();
                throw $e;
            }
        }
    }

    public function getCarrier(): string
    {
        return self::TYPE;
    }
}
