<?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 ScellierProvider implements CarrierProviderInterface
{
    public const TYPE = 'scellier';

    /**
     * @var array<string, array{0:int,1:int}>
     */
    private array $pal = [
        '1pal' => [240, 480],
        '2pal' => [480, 960],
        '3pal' => [960, 1440],
    ];

    public function __construct(
        private RequestStack $requestStack,
        private Filesystem $filesystem,
        private EntityManagerInterface $em,
    ) {
        /*
        $this->pal = [
            "+ 10 *"    => [60, 78],
            "1/2 pal"   => [78, 150],
            "Pal basse" => [150, 240],
            "1pal"      => [240, 480],
            "2pal"      => [480, 960],
            "3pal"      => [960, 1440],
        ];
        */
    }

    /**
     * @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', 'scellier.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 = [];

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

                    for ($c = 0; $c < $num; ++$c) {
                        if (($data[$c] ?? null) === 'DEP') {
                            for ($cc = 1; $cc < $num; ++$cc) {
                                if (($data[$cc] ?? '') === '') {
                                    continue;
                                }

                                if (\array_key_exists((string) $data[$cc], $this->pal)) {
                                    $shippingQtyCollection[$cc]['of'] = $this->pal[$data[$cc]][0];
                                    $shippingQtyCollection[$cc]['at'] = $this->pal[$data[$cc]][1];
                                } else {
                                    $pack = explode('/', (string) $data[$cc]);

                                    if (null !== $data[$cc] && 1 !== $cc) {
                                        $previous = explode('/', (string) ($data[$cc - 1] ?? '0/0'))[1] ?? 0;
                                        $shippingQtyCollection[$cc]['of'] = (int) $previous;
                                        $shippingQtyCollection[$cc]['at'] = (int) ($pack[1] ?? 0);
                                    } else {
                                        $shippingQtyCollection[$cc]['of'] = (int) ($pack[0] ?? 0);
                                        $shippingQtyCollection[$cc]['at'] = (int) ($pack[1] ?? 0);
                                    }
                                }
                            }
                        }

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

                                $shipping = new ShippingAuto();
                                $shipping->setCountry('FR');

                                $cell0 = (string) $data[0];
                                if (mb_strstr($cell0, 'HTE')) {
                                    $county = mb_substr($cell0, 0, 2);
                                    $shipping->setHM(1);
                                } elseif (mb_strlen($cell0) < 2) {
                                    $county = '0'.$cell0;
                                } else {
                                    $county = $cell0;
                                }

                                $shipping->setCounty($county);

                                $value = (float) str_replace(',', '.', (string) $data[$cc]);

                                $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());

                $row = 0;
                while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                    ++$row;

                    if (!isset($data[0]) || !is_numeric(mb_substr((string) $data[0], 0, 2))) {
                        continue;
                    }

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

                        if (isset($data[3]) && 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($splitPostal[0]));
                            $city = mb_trim((string) $data[3]);
                            $shippingSup1->setOldName($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($splitPostal[1]));
                            $city = mb_trim((string) $data[3]);
                            $shippingSup2->setOldName($splitCity[1] ?? '');
                            $shippingSup2->setCity($city);
                            $this->em->persist($shippingSup2);
                        } else {
                            $city = mb_trim((string) ($data[3] ?? ''));

                            $shippingSup1 = new ShippingAutoSup();
                            $shippingSup1->setCountry('FR');
                            $shippingSup1->setCounty(mb_substr((string) $data[0], 0, 2));
                            $shippingSup1->setPostal(mb_trim($splitPostal[0]));
                            $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($splitPostal[1]));
                            $shippingSup2->setOldName(mb_trim((string) ($data[3] ?? '')));
                            $shippingSup2->setCity($city);
                            $this->em->persist($shippingSup2);
                        }
                    } else {
                        if (isset($data[2]) && 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;
    }
}
