<?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 StefProvider implements CarrierProviderInterface
{
    public const string TYPE = 'Stef';

    public function __construct(
        private readonly RequestStack $requestStack,
        private readonly Filesystem $filesystem,
        private readonly 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', 'stef.csv');
            $writer->save($csvPath);

            // 1er passage (historique : ne fait "rien" à part parcourir)
            $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());

                while (false !== fgetcsv($handle, 1000, ',')) {
                    // noop (conserve le comportement)
                }
                fclose($handle);

                // 2e passage : parsing réel
                $handle = fopen($csvPath, 'r');
                if (false === $handle) {
                    $connection->commit();

                    return;
                }

                $shippingQtyCollection = [];

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

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

                        if ('' !== $cell && str_contains($cell, 'cols')) {
                            for ($d = 1; $d < $num; ++$d) {
                                if (($data[$d] ?? '') === '') {
                                    continue;
                                }

                                $exploded = explode('-', (string) $data[$d]);
                                if (\count($exploded) <= 1) {
                                    continue;
                                }

                                $secondExplode = explode(' ', (string) ($exploded[1] ?? ''));

                                // "... pal"
                                if (($secondExplode[1] ?? null) === 'pal') {
                                    $shippingQtyCollection[$d - 1]['of'] = (int) mb_trim((string) ($shippingQtyCollection[$d - 2]['at'] ?? 0));
                                    $shippingQtyCollection[$d - 1]['at'] = 384;
                                } // "... cols"
                                elseif (
                                    ($secondExplode[1] ?? null) === 'cols'
                                    || (($secondExplode[2] ?? null) === 'cols')
                                ) {
                                    $of = (int) mb_trim((string) ($exploded[0] ?? 0));
                                    $at = (int) mb_trim((string) (explode(' cols', (string) ($exploded[1] ?? '0'))[0] ?? 0));

                                    if (1 === $d) {
                                        $shippingQtyCollection[$d - 1]['of'] = 0;
                                        $shippingQtyCollection[$d - 1]['at'] = $at;
                                    } else {
                                        $shippingQtyCollection[$d - 1]['of'] = $of - 1;
                                        $shippingQtyCollection[$d - 1]['at'] = $at;
                                    }
                                }
                            }
                        }

                        if ('' !== $cell && mb_strstr($cell, 'FR')) {
                            // On reparcours la ligne en ne prenant que les 4 valeurs de transport
                            for ($d = 1; $d < min($num, 6); ++$d) {
                                if (($data[$d] ?? '') === '') {
                                    continue;
                                }

                                $currentZone = explode('FR', (string) ($data[0] ?? ''))[1] ?? '';
                                if ('' === $currentZone) {
                                    continue;
                                }

                                $shipping = new ShippingAuto();
                                $shipping->setCountry('FR');
                                $shipping->setCounty($currentZone);
                                $shipping->setQtyOf($shippingQtyCollection[$d - 1]['of'] ?? 0);
                                $shipping->setQtyAt($shippingQtyCollection[$d - 1]['at'] ?? null);

                                $price = (float) str_replace(',', '.', (string) $data[$d]);
                                if ($price > 10) {
                                    $shipping->setPackagePrice((int) ($price * 100));
                                } else {
                                    $shipping->setBottlePrice((int) ($price * 100));
                                }

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

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

                $connection->commit();
            } catch (\Throwable $e) {
                if (isset($handle) && \is_resource($handle)) {
                    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', 'stef_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) {
                    if ($row > 0) {
                        if (mb_strlen((string) ($data[1] ?? '')) < 5) {
                            $data[1] = '0'.$data[1];
                        }
                        if (mb_strlen((string) ($data[3] ?? '')) < 2) {
                            $data[3] = '0'.$data[3];
                        }

                        $shippingSup = new ShippingAutoSup();
                        $shippingSup->setCountry('FR');
                        $shippingSup->setCounty((string) ($data[3] ?? ''));
                        $shippingSup->setPostal((string) ($data[1] ?? ''));

                        $city = mb_trim((string) ($data[2] ?? ''));

                        // $city = str_replace(" ST ", " SAINT ", trim($data[2]));
                        // $city = str_replace("ST ", "SAINT ", $city);
                        // $city = $this->checkCity->check($city, $data[3], $data[1]);
                        // if ($city) {
                        //     $shippingSup->setVerification(1);
                        // }

                        $shippingSup->setOldName(mb_trim((string) ($data[2] ?? '')));
                        $shippingSup->setCity($city);

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

                    ++$row;
                }

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

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

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