<?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;
use function GuzzleHttp\Psr7\str;

class Geodis2022Provider implements CarrierProviderInterface
{
    const TYPE = 'geodis_2022';

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

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

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

    /**
     * @var RequestStack
     */
    private $requestStack;

    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'];
        $oneSheet = true;
        if ($file) {
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($this->filesystem->getAdapter()->getPathPrefix().$config->getFile()->getPath());
            if($spreadsheet->getSheetCount() > 1){
                $spreadsheet->setActiveSheetIndexByName("TARIF MESSAGERIE");
                $oneSheet = false;
            }
            $writer      = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
            $writer->setSheetIndex($spreadsheet->getActiveSheetIndex());
            $writer->save($this->filesystem->getAdapter()->getPathPrefix()."geodis2022.csv");


            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."geodis2022.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 ($oneSheet) {
                            if ($data[$c] === 'Bouteilles') {
                                for ($d = 3; $d < $num; $d++) {
                                    if ($data[$d] != "") {
                                        if ($d == 3) {
                                            $shippingQtyCollection[$d]['of'] = 0;
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        } else {
                                            $shippingQtyCollection[$d]['of'] = $data[$d - 1];
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        }
                                    }
                                }
                            }
                            $department = explode(" ", $data[1])[0];
                            if (is_numeric($department)) {
                                if ($data[$c] != "" && $c > 1) {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    $county = $department;
                                    $shipping->setCounty($county);
                                    $data[$c] = floatval(str_replace(',','.',$data[$c]));
                                    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);
                                }
                            }
                        } else {
                            if ($data[$c] === 'Département de destination') {
                                for ($d = 3; $d < $num; $d++) {
                                    if ($data[$d] != "") {
                                        if ($d == 3) {
                                            $shippingQtyCollection[$d]['of'] = 0;
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        } else {
                                            $shippingQtyCollection[$d]['of'] = $data[$d - 1];
                                            $shippingQtyCollection[$d]['at'] = $data[$d];
                                        }
                                    }
                                }
                            }
                            if (is_numeric($data[2])) {
                                if ($data[$c] != "" && $c > 2) {
                                    $shipping = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    if (strlen($data[2]) < 2) {
                                        $county = "0".$data[2];
                                    } else {
                                        $county = $data[2];
                                    }
                                    $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()."geodis_sup.csv");

            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."geodis_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) {
                    if ($row > 0) {
                        if (strlen($data[1]) < 5) {
                            $data[1] = "0".$data[1];
                        }
                        if (strlen($data[3]) < 2) {
                            $data[3] = "0".$data[3];
                        }
                        $shippingSup = new ShippingAutoSup();
                        $shippingSup->setCountry('FR');
                        $shippingSup->setCounty($data[3]);
                        $shippingSup->setPostal($data[1]);
                        $city = trim($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(trim($data[2]));
                        $shippingSup->setCity($city);
                        $this->em->persist($shippingSup);

                    }

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

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