<?php
    namespace AppBundle\Service;

    use Symfony\Component\Filesystem\Filesystem;
    use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
    use AppBundle\Entity\Connection;
    use AppBundle\Entity\Application;

            //spedytor: 'kontener.pl'
            //armator: 'MAG',
            //port zaladunku:
            //port ladunku
            //frachtMorski: 2500.00,
            //oplataDokumentacyjna: 232.0,
            //thc: 293,0
            //waluta: 'USD',
            //typKontenera: '40DV',
            //regula_handlu: 'FOB',
            //wazneOd: {data wygenerowania pliku, np. 2016-05-01},
            //wazneDo: 2016-06-30

    class JsonService{
        protected $doctrine;

        public function __construct($doctrine) {
            $this->doctrine = $doctrine;
        }

        public function generateJson(){
            $fs = new Filesystem();
            $em = $this->doctrine;

            //pobranie potrzebnych danych
            $connections = $em->getRepository('AppBundle:Connection')->findAllData();
            $settings = $em->getRepository('AppBundle:Setting')->findAllData();
            $documentary = number_format($settings['documentary'], 2, ',', '');
            $thc = number_format($settings['thc'], 2, ',', '');
            $customs = number_format($settings['customs'], 2, ',', '');
            $data = array();

            //aktualna data
            $today_date = date('Ymd');

            foreach($connections as $key => $value){
                $loadPort = $this->portName($value['l']);
                $unloadPort = $this->portName($value['u']);
                $container = 1;
                $cost = number_format($value['c'], 2, ',', '');
                $valid_to = $value['vt'];
                $created_at = $value['ca'];
                $updated_at = $value['ua'];
                $valid_from = ($updated_at != null) ? $updated_at->format('Y-m-d') : $created_at->format('Y-m-d');

                if($loadPort != false && $loadPort != false && $container != false){
                    $data[$key] = array(
                        'spedytor' => 'drobnicamorska.pl',
                        'armator' => 'MAG',
                        'portZaladunku' => $loadPort,
                        'portWyladunku' => $unloadPort,
                        'frachtMorski' => $cost,
                        'oplataDokumentacyjna' => $documentary,
                        'oplataCelna' => $customs,
                        'thc' => $thc,
                        'waluta' => 'USD',
                        'regula_handlu' => 'FOB',
                        'wazneOd' => $valid_from,
                        'wazneDo' => $valid_to->format('Y-m-d')
                    );
                };
            };

            //konwersja do utf-8 dla jsona
            foreach($data as $key => $value){

                foreach($value as $key_v => $value_v){
                    $enc = mb_detect_encoding($value_v);
                    if($enc != 'UTF-8'){
                        $data[$key][$key_v] = iconv($enc.'//TRANSLIT//IGNORE', 'UTF-8', $value_v);
                    };
                };
            };

            $xml = '';
            $xml = '<?xml version="1.0" standalone="yes"?>';
            $xml .= '<polaczenia>';
            foreach($data as $key => $value){
                $xml .= '<polaczenie>';
                $xml .= '<spedytor>'.$value['spedytor'].'</spedytor>';
                $xml .= '<armator>'.$value['armator'].'</armator>';
                $xml .= '<portZaladunku>'.$value['portZaladunku'].'</portZaladunku>';
                $xml .= '<portWyladunku>'.$value['portWyladunku'].'</portWyladunku>';
                $xml .= '<frachtMorski>'.$value['frachtMorski'].'</frachtMorski>';
                $xml .= '<oplataDokumentacyjna>'.$value['oplataDokumentacyjna'].'</oplataDokumentacyjna>';
                $xml .= '<oplataCelna>'.$value['oplataCelna'].'</oplataCelna>';
                $xml .= '<thc>'.$value['thc'].'</thc>';
                $xml .= '<waluta>'.$value['waluta'].'</waluta>';
                $xml .= '<regula_handlu>'.$value['regula_handlu'].'</regula_handlu>';
                $xml .= '<wazneOd>'.$value['wazneOd'].'</wazneOd>';
                $xml .= '<wazneDo>'.$value['wazneDo'].'</wazneDo>';
                $xml .= '</polaczenie>';
            }

            $xml .= '</polaczenia>';
            //konwert do jsona
//            $data = json_encode($data, 256);

            $data = $this->raw_json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);

            //tworzenie folderu
            try {
                if (!$fs->exists('../../fracht')) {
                   $fs->mkdir('../../fracht', 0755);
                }
            } catch (IOExceptionInterface $e) {
                echo "An error occurred while creating your directory at " . $e->getPath();
            }
            try {
                if (!$fs->exists('../../xml')) {
                   $fs->mkdir('../../xml', 0755);
                }
            } catch (IOExceptionInterface $e) {
                echo "An error occurred while creating your directory at " . $e->getPath();
            }
            //tworzenie pliku
            $name = $today_date.'.json';
            if ($fs->exists('../../fracht/'.$name )) {
               $fs->remove('../../fracht/'.$name );
            }
            $fs->dumpFile('../../fracht/'.$name , $data);

            $name2 = $today_date.'.xml';
            if ($fs->exists('../../xml/'.$name2)) {
               $fs->remove('../../xml/'.$name2 );
            }
            $fs->dumpFile('../../xml/'.$name2 , $xml);
        }

        //nazwa portu po id
        private function portName($sid = 0){
            $em = $this->doctrine;
            $port = $em->getRepository('AppBundle:Setting')->portAllMyData();

            foreach($port as $key => $value){

                if($value['id'] == $sid){
                    return $value['name'];
                };
            };

            return false;
        }

        private function raw_json_encode($input, $flags = 0) {
            $fails = implode('|', array_filter(array(
                '\\\\',
                $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
                $flags & JSON_HEX_AMP ? 'u0026' : '',
                $flags & JSON_HEX_APOS ? 'u0027' : '',
                $flags & JSON_HEX_QUOT ? 'u0022' : '',
            )));
            $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
            $callback = function ($m) {
                return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
            };
            return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
        }

    }
?>
