<?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 LTDProvider implements CarrierProviderInterface
{
    const TYPE = 'LTD';

    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;
    }

    /**
     * @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->setLoadSheetsOnly("TARIF A DETAIL PROVINCE");
        $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()."scellier.csv");
            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."scellier.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] == "Département") {
                            for ($c = 1; $c < $num; $c++) {
                                if ($data[$c] != "") {
                                    if (intval(explode(" ", $data[$c])[0]) != 0) {
                                        $of                              = intval(explode(" ", $data[$c])[0]) - 1;
                                        $at                              = intval(explode(" ", $data[$c])[2]);
                                        $shippingQtyCollection[$c]['of'] = $of;
                                        $shippingQtyCollection[$c]['at'] = $at;
                                    }
                                }
                            }
                        }
                        if (is_numeric(substr($data[0], 0, 2))) {
                            for ($c = 1; $c < $num-1; $c++) {
                                if ($data[$c] != "") {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    if (strstr($data[0], 'Hte Montagne') || strstr($data[0], 'Haute Montagne') || strstr($data[0], 'Haute Mmontagne') || strstr($data[0], 'localités specif')) {
                                        $county = substr($data[0], 0, 2);
                                        $shipping->setHM(1);
                                    } 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->save($this->filesystem->getAdapter()->getPathPrefix()."transvins_sup.csv");

            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."transvins_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++) {
                        if (is_numeric(substr($data[0], 0, 2))) {
                            if (strpos($data[2], '/')) {
                                $splitPostal = explode('/', $data[2]);
                                if (strlen($splitPostal[0]) < 5) {
                                    $splitPostal[0] = "0".$splitPostal[0];
                                }
                                if (strlen($splitPostal[1]) < 5) {
                                    $splitPostal[1] = "0".$splitPostal[1];
                                }
                                if (strpos($data[3], '/')) {
                                    $splitCity    = explode('/', $data[3]);
                                    $shippingSup1 = new ShippingAutoSup();
                                    $shippingSup1->setCountry('FR');
                                    $shippingSup1->setCounty(substr($data[0], 0, 2));
                                    $shippingSup1->setPostal(trim($splitPostal[0]));
                                    $city = trim($data[3]);
                                    /*$city = str_replace(" ST ", " SAINT ", trim($data[3]));
                                    $city = str_replace("ST ", "SAINT ", $city);
                                    $city = $this->checkCity->check($city, substr($data[0], 0, 2), trim($splitPostal[0]));
                                    if ($city) {
                                        $shippingSup1->setVerification(1);
                                    }*/
                                    $shippingSup1->setOldName($splitCity[0]);
                                    $shippingSup1->setCity($city);
                                    $this->em->persist($shippingSup1);

                                    $shippingSup2 = new ShippingAutoSup();
                                    $shippingSup2->setCountry('FR');
                                    $shippingSup2->setCounty(substr($data[0], 0, 2));
                                    $shippingSup2->setPostal(trim($splitPostal[1]));
                                    $city = trim($data[3]);
                                    /*$city = str_replace(" ST ", " SAINT ", trim($data[3]));
                                    $city = str_replace("ST ", "SAINT ", $city);
                                    $city = $this->checkCity->check($city, substr($data[0], 0, 2), trim($splitPostal[1]));
                                    if ($city) {
                                        $shippingSup2->setVerification(1);
                                    }*/
                                    $shippingSup2->setOldName($splitCity[1]);
                                    $shippingSup2->setCity($city);
                                    $this->em->persist($shippingSup2);
                                } else {
                                    $shippingSup1 = new ShippingAutoSup();
                                    $shippingSup1->setCountry('FR');
                                    $shippingSup1->setCounty(substr($data[0], 0, 2));
                                    $shippingSup1->setPostal(trim($splitPostal[0]));
                                    $city = trim($data[3]);
                                    /*$city = str_replace(" ST ", " SAINT ", trim($data[3]));
                                    $city = str_replace("ST ", "SAINT ", $city);
                                    $city = $this->checkCity->check($city, substr($data[0], 0, 2), trim($splitPostal[0]));
                                    if ($city) {
                                        $shippingSup1->setVerification(1);
                                    }*/
                                    $shippingSup1->setOldName(trim($data[3]));
                                    $shippingSup1->setCity($city);
                                    $this->em->persist($shippingSup1);

                                    $shippingSup2 = new ShippingAutoSup();
                                    $shippingSup2->setCountry('FR');
                                    $shippingSup2->setCounty(substr($data[0], 0, 2));
                                    $shippingSup2->setPostal(trim($splitPostal[1]));

                                    /*$city = str_replace(" ST ", " SAINT ", trim($data[3]));
                                    $city = str_replace("ST ", "SAINT ", $city);
                                    $city = $this->checkCity->check($city, substr($data[0], 0, 2), trim($splitPostal[1]));
                                    if ($city) {
                                        $shippingSup2->setVerification(1);
                                    }*/
                                    $shippingSup2->setOldName(trim($data[3]));
                                    $shippingSup2->setCity($city);
                                    $this->em->persist($shippingSup2);
                                }
                            } else {
                                if (strlen($data[2]) < 5) {
                                    $data[2] = "0".$data[2];
                                }
                                $shippingSup = new ShippingAutoSup();
                                $shippingSup->setCountry('FR');
                                $shippingSup->setCounty(substr($data[0], 0, 2));
                                $shippingSup->setPostal($data[2]);
                                $city = trim($data[3]);
                                /*$city = str_replace(" ST ", " SAINT ", trim($data[3]));
                                $city = str_replace("ST ", "SAINT ", $city);
                                $city = $this->checkCity->check($city, substr($data[0], 0, 2), $data[2]);
                                if ($city) {
                                    $shippingSup->setVerification(1);
                                }*/
                                $shippingSup->setOldName(trim($data[3]));
                                $shippingSup->setCity($city);
                                $this->em->persist($shippingSup);
                            }

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

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