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

    /**
     * @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'];

        $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()."stef.csv");
            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."stef.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++;
                }
            }
            unset($handle);
            unset($data);
            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."stef.csv", "r")) !== false) {
                $row = 0;
                // $data correspond a une ligne
                while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                    $num = count($data);
                    $row++;
                    // Chaque valeur de ligne
                    for ($c = 0; $c < $num; $c++) {
                        if (str_contains($data[$c], "cols")) {
                            for ($d = 1; $d < $num; $d++) {
                                if ($data[$d] != "") {
                                    $exploded = explode("-", $data[$d]);
                                    if (count($exploded) > 1) {
                                        $secondExplode = explode(' ', $exploded[1]);
                                        if ($secondExplode[1] == 'pal') {
                                            $shippingQtyCollection[$d - 1]['of'] = trim(intval($shippingQtyCollection[$d - 2]['at']));
                                            $shippingQtyCollection[$d - 1]['at'] = trim(384);
                                        }
                                        elseif ($secondExplode[1] == 'cols' || (isset($secondExplode[2]) && $secondExplode[2] == 'cols')) {
                                            $of = trim(intval($exploded[0]));
                                            $at = trim(intval(explode(" cols", $exploded[1])[0]));
                                            //dump($secondExplode);
                                            if ($d == 1) {
                                                $shippingQtyCollection[$d - 1]['of'] = 0;
                                                $shippingQtyCollection[$d - 1]['at'] = trim(intval($at));
                                            } else {
                                                $shippingQtyCollection[$d - 1]['of'] = trim(intval($of - 1));
                                                $shippingQtyCollection[$d - 1]['at'] = trim(intval($at));
                                            }
                                        }

                                    }
                                }
                            }
                        }
                        if (strstr($data[$c], '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] != "") {
                                    $currentZone = explode("FR", $data[0])[1];
                                    $shipping    = new ShippingAuto();
                                    $shipping->setCountry('FR');
                                    $shipping->setCounty($currentZone);
                                    $shipping->setQtyOf($shippingQtyCollection[$d - 1]['of']);
                                    $shipping->setQtyAt($shippingQtyCollection[$d - 1]['at']);
                                    $price = floatval(str_replace(",", ".", $data[$d]));
                                    if ($price > 10) {
                                        $shipping->setPackagePrice(intval(strval($price * 100)));
                                    } else {
                                        $shipping->setBottlePrice(intval(strval($price * 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()."stef_sup.csv");

            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."stef_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;
    }
}
