<?php
/**
 * @author Colinet Julien
 */

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\FileFilesystem;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\CheckCity;
use CpCreation\VitiCore\Shop\Model\ShippingAuto;
use CpCreation\VitiCore\Shop\Model\ShippingAutoSup;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class OenotransProvider implements CarrierProviderInterface
{
    const TYPE = 'oenotrans';

    private $requestStack;

    /**
     * @var FileFilesystem
     */
    private $filesystem;

    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var CheckCity
     */
    private $checkCity;

    /**
     * @var array
     */
    private $pal;


    public function __construct(RequestStack $requestStack,
        FileFilesystem $filesystem,
        EntityManagerInterface $em,
        CheckCity $checkCity
    ) {
        $this->filesystem   = $filesystem;
        $this->em           = $em;
        $this->checkCity    = $checkCity;
        $this->requestStack = $requestStack;
        $this->pal          = [
            "1/2 PAL" => "151 à 228",
            "1 PAL"   => "229 à 480",
            "2 PAL"   => "481 à 960",
            "3 PAL"   => "961 à 1440",
        ];
    }

    /**
     * @param ShippingConfig $config
     * @throws \Doctrine\DBAL\DBALException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function setData(ShippingConfig $config)
    {
        $files   = $this->requestStack->getCurrentRequest()->files->get('shipping_config');
        $file    = $files['file']['file'];
        $fileSup = $files['fileSup']['file'];
        $reader  = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $reader->setReadDataOnly(true);
        if ($file) {
            $spreadsheet = $reader->load($this->filesystem->getAdapter()->getPathPrefix().$config->getFile()->getPath());
            $writer      = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
            $writer->save($this->filesystem->getAdapter()->getPathPrefix()."oenotrans.csv");
            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."oenotrans.csv", "r")) !== false) {

                $classMetaData = $this->em->getClassMetadata(ShippingAuto::class);
                $connection = $this->em->getConnection();
                $dbPlatform = $connection->getDatabasePlatform();
                $connection->beginTransaction();
                $connection->query('SET FOREIGN_KEY_CHECKS=0');
                $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
                $connection->executeUpdate($q);
                $connection->query('SET FOREIGN_KEY_CHECKS=1');

                $row                   = 0;
                $shippingQtyCollection = [];
                while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                    $num = count($data);
                    $row++;
                    for ($c = 0; $c < $num; $c++) {
                        if ($data[$c] === 'Localités') {
                            for ($c = 1; $c < $num; $c++) {
                                if ($data[$c] != "") {
                                    if (strstr($data[$c], 'à')) {
                                        $explode = explode('à', $data[$c]);
                                        $of      = intval(trim($explode[0]));
                                        if ($of > 0) {
                                            $of = $of - 1;
                                        }
                                        $shippingQtyCollection[$c]['of'] = $of;
                                        $shippingQtyCollection[$c]['at'] = intval(trim($explode[1]));

                                    } else {
                                        foreach ($this->pal as $key => $pal) {
                                            if ($key == $data[$c]) {
                                                $explode = explode('à', $pal);
                                                $of      = intval(trim($explode[0]));
                                                if ($of > 0) {
                                                    $of = $of - 1;
                                                }
                                                $shippingQtyCollection[$c]['of'] = $of;
                                                $shippingQtyCollection[$c]['at'] = intval(trim($explode[1]));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (is_numeric(substr($data[0], 0, 2))) {
                            for ($c = 1; $c < $num; $c++) {
                                if ($data[$c] != "") {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    if (strstr($data[0], 'VHM') || strstr($data[$c], 'I')) {
                                        $county = substr($data[0], 0, 2);
                                        $shipping->setHM(1);
                                    } elseif (strstr($data[$c], '2A/2B')) {
                                        $county = 20;
                                    } elseif (strlen($data[0]) < 2) {
                                        $county = "0".$data[0];
                                    } else {
                                        $county = $data[0];
                                    }
                                    $shipping->setCounty($county);
                                    if ($data[$c] > 10) {
                                        $shipping->setQtyOf($shippingQtyCollection[$c]['of']);
                                        $shipping->setQtyAt($shippingQtyCollection[$c]['at']);
                                        $shipping->setPackagePrice(intval(strval($data[$c] *100)));
                                    } else {
                                        $shipping->setQtyOf($shippingQtyCollection[$c]['of']);
                                        $shipping->setQtyAt($shippingQtyCollection[$c]['at']);
                                        $shipping->setBottlePrice(intval(strval($data[$c] *100)));
                                    }
                                    $this->em->persist($shipping);
                                }
                            }
                        }
                    }

                }
                $this->em->flush();
                fclose($handle);
                unset($handle);
                unset($data);
            }

        }
        if ($fileSup) {
            $spreadsheet = $reader->load($this->filesystem->getAdapter()->getPathPrefix().$config->getFileSup()->getPath());
            $writer      = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
            $writer->setSheetIndex(1);
            $writer->save($this->filesystem->getAdapter()->getPathPrefix()."oenotrans_sup.csv");
            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."oenotrans_sup.csv", "r")) !== false) {

                $classMetaData = $this->em->getClassMetadata(ShippingAutoSup::class);
                $connection = $this->em->getConnection();
                $dbPlatform = $connection->getDatabasePlatform();
                $connection->beginTransaction();
                $connection->query('SET FOREIGN_KEY_CHECKS=0');
                $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
                $connection->executeUpdate($q);
                $connection->query('SET FOREIGN_KEY_CHECKS=1');
                
                $row = 0;
                while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                    $num = count($data);
                    $row++;
                    for ($c = 0; $c < $num; $c++) {
                        $firstCityBegin  = 0;
                        $secondCityBegin = 3;
                        if (is_numeric($data[$firstCityBegin])) {
                            if ($data[$firstCityBegin] <10)
                            {
                                $data[$firstCityBegin] = "0".$data[$firstCityBegin];
                            }
                            $shippingSup = new ShippingAutoSup();
                            $shippingSup->setCountry('FR');
                            $shippingSup->setCounty($data[$firstCityBegin]);
                            $cityColumn = $firstCityBegin + 1;
                            $city = $data[$cityColumn];
                            /*$city = str_replace(" ST ", " SAINT ", $data[$cityColumn]);
                            $city = str_replace("ST ", "SAINT ", $city);
                            $city       = $this->checkCity->check($city, $data[$firstCityBegin]);
                            if ($city) {
                                $shippingSup->setVerification(1);
                            }*/
                            $shippingSup->setOldName($data[$cityColumn]);
                            $shippingSup->setCity($city);

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

                            if (is_numeric($data[$secondCityBegin])) {
                                if ($data[$secondCityBegin] <10)
                                {
                                    $data[$secondCityBegin] = "0".$data[$secondCityBegin];
                                }
                                $shippingSup = new ShippingAutoSup();
                                $shippingSup->setCountry('FR');
                                $shippingSup->setCounty($data[$secondCityBegin]);
                                $cityColumn = $secondCityBegin + 1;
                                $city = $data[$cityColumn];
                                /*$city = str_replace(" ST ", " SAINT ", $data[$cityColumn]);
                                $city = str_replace("ST ", "SAINT ", $city);
                                $city       = $this->checkCity->check($city, $data[$secondCityBegin]);
                                if ($city) {
                                    $shippingSup->setVerification(1);
                                }*/
                                $shippingSup->setOldName($data[$cityColumn]);
                                $shippingSup->setCity($city);

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

                        }
                        break;
                    }
                    unset($data);
                }
                $this->em->flush();
                fclose($handle);
                unset($handle);

            }
        }
    }

    /**
     * @return string
     */
    public function getCarrier(): string
    {
        return static::TYPE;
    }
}
