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

    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;

        $oneSheet = true;

        // ==========
        // FICHIER PRINCIPAL
        // ==========
        if ($file) {
            $reader = new Xlsx();
            $reader->setReadDataOnly(true);

            // ✅ Flysystem v2/v3 : chemin absolu via ton wrapper multi-filesystems
            $xlsxPath = $this->filesystem->absolutePath('file', $config->getFile()->getPath());
            $spreadsheet = $reader->load($xlsxPath);

            if ($spreadsheet->getSheetCount() > 1) {
                $spreadsheet->setActiveSheetIndexByName('TARIF MESSAGERIE');
                $oneSheet = false;
            }

            $writer = new Csv($spreadsheet);
            $writer->setSheetIndex($spreadsheet->getActiveSheetIndex());

            $csvPath = $this->filesystem->absolutePath('file', 'geodis2022.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());

                $row = 0;
                $shippingQtyCollection = [];

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

                    for ($c = 0; $c < $num; ++$c) {
                        if ($oneSheet) {
                            if (($data[$c] ?? null) === 'Bouteilles') {
                                for ($d = 3; $d < $num; ++$d) {
                                    if (($data[$d] ?? '') !== '') {
                                        if (3 === $d) {
                                            $shippingQtyCollection[$d]['of'] = 0;
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        } else {
                                            $shippingQtyCollection[$d]['of'] = $data[$d - 1];
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        }
                                    }
                                }
                            }

                            $department = explode(' ', (string) ($data[1] ?? ''))[0] ?? '';
                            if (is_numeric($department)) {
                                if (($data[$c] ?? '') !== '' && $c > 1) {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    $shipping->setCounty($department);

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

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

                                    if ($data[$c] > 10) {
                                        $shipping->setPackagePrice((int) ((float) $data[$c] * 100));
                                    } else {
                                        $shipping->setBottlePrice((int) ((float) $data[$c] * 100));
                                    }

                                    $this->em->persist($shipping);
                                }
                            }
                        } else {
                            if (($data[$c] ?? null) === 'Département de destination') {
                                for ($d = 3; $d < $num; ++$d) {
                                    if (($data[$d] ?? '') !== '') {
                                        if (3 === $d) {
                                            $shippingQtyCollection[$d]['of'] = 0;
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        } else {
                                            $shippingQtyCollection[$d]['of'] = $data[$d - 1];
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        }
                                    }
                                }
                            }

                            if (isset($data[2]) && is_numeric($data[2])) {
                                if (($data[$c] ?? '') !== '' && $c > 2) {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');

                                    $dept = (string) $data[2];
                                    $county = (mb_strlen($dept) < 2) ? ('0'.$dept) : $dept;
                                    $shipping->setCounty($county);

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

                                    $value = (float) str_replace(',', '.', (string) $data[$c]);
                                    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) {
            $reader = new Xlsx();
            $reader->setReadDataOnly(true);

            $xlsxSupPath = $this->filesystem->absolutePath('file', $config->getFileSup()->getPath());
            $spreadsheetSup = $reader->load($xlsxSupPath);

            $writerSup = new Csv($spreadsheetSup);
            $csvSupPath = $this->filesystem->absolutePath('file', 'geodis_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;
    }
}
