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

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

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

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

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

    /**
     * @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/4 PAL*" => "0 à 114",
            "1/2 PAL*" => "114 à 228",
            "1 PAL"    => "228 à 480",
            "2 PAL"    => "480 à 960",
            "3 PAL"    => "960 à 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()."genin.csv");

            if (($handle = fopen($this->filesystem->getAdapter()->getPathPrefix()."genin.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élai') {
                            for ($c = 1; $c < $num; $c++) {
                                if ($data[$c] != "") {
                                    foreach ($this->pal as $key => $pal) {
                                        if ($key == $data[$c]) {
                                            $explode = explode('à', $pal);
                                            $of      = intval(trim($explode[0]));
                                            $shippingQtyCollection[$data[$c]]['of'] = $of;
                                            $shippingQtyCollection[$data[$c]]['at'] = intval(trim($explode[1]));
                                            $numMax                                 = $c;

                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (is_numeric(intval(substr($data[0], 0, 2))) && intval($data[0]) != 0 && intval($data[0]) != 51100) {
                        if ($data[0] != "") {
                            $departments = array_chunk($data, 7);
                            foreach ($departments as $department) {
                                if($department[0] != ""){
                                    foreach ($this->pal as $key => $pal) {
                                        $shipping = new ShippingAuto();
                                        $shipping->setCountry('FR');
                                        $county = substr($department[0], 0, 2);
                                        $shipping->setCounty($county);
                                        $shipping->setQtyOf($shippingQtyCollection[$key]['of']);
                                        $shipping->setQtyAt($shippingQtyCollection[$key]['at']);
                                        $shipping->setPackagePrice(floatval($department[array_search($key, array_keys($this->pal)) + 2]) * 100);
                                        $this->em->persist($shipping);
                                    }
                                }
                            }
                        }
                    }
                }
                $this->em->flush();
                fclose($handle);
                unset($handle);
                unset($data);
            }
        }
    }

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