<?php
namespace Ayaline\Bundle\EzCarteInteractiveBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CartographieController extends Controller
{

    public function mapAction()
    {
        //Map settings
        $mapSetting = array();
        $mapSetting['zoom'] = $this->container->getParameter('map_setting.zoom');
        $mapSetting['latitude'] = $this->container->getParameter('map_setting.latitude');
        $mapSetting['longitude'] = $this->container->getParameter('map_setting.longitude');
        $mapSetting['mapType'] = $this->container->getParameter('map_setting.type');
        $mapSetting['proximite'] = $this->container->getParameter('map_setting.mapproximite');
        $pictoGategories = $this->container->hasParameter("custom.picto.categories") ? $this->container->getParameter("custom.picto.categories") : array();
        //SIT sections
        $sections = array();
        $sit_sections = $this->container->getParameter('sit_section');
        $sit_categories = $this->container->getParameter('sit_categories');
        $sit_criteres = $this->container->getParameter('criteres');
        $listCritere = array();
        $listModalite = array();
        for ($i = 0; $i < count($sit_criteres); $i++) {
            foreach ($sit_criteres[$i] as $key => $critere) {
                $listCritere[$key] = $critere;
            }
        }
        $sit_modalites = $this->container->getParameter('modalites');
        for ($j = 0; $j < count($sit_modalites); $j++) {
            foreach ($sit_modalites[$j] as $keyM => $modalite) {
                $listModalite[$keyM] = $modalite;
            }

        }

        $path = $this->get('kernel')->getRootDir() . '/../web';

        foreach ($sit_sections as $sectionItem) {
            $section['titre'] = $sectionItem['titre'];
            $iconCss = "";
            $iconImg = "";
            $icone = $sectionItem['icone'];
            if ($icone != "" && file_exists($path . "/bundles/ayalineezcarteinteractive/images/menu/" . $icone)) {
                $iconCss .= "background: url('/bundles/ayalineezcarteinteractive/images/menu/$icone') no-repeat 0 50%;";

                $iconImg = "bundles/ayalineezcarteinteractive/images/menu/$icone";
            }
            $children = array();

            foreach ($sectionItem['section_children'] as $child) {
                $criteres = array();
                $listCriteres = array();

                $puceCateg = "/bundles/ayalineezcarteinteractive/images/pictos/menu/categ_undefined.png";
                if (array_key_exists($child, $sit_categories)) {
                    if ($this->container->hasParameter("custom.picto.categories") && isset($pictoGategories[$child])) {
                        $puceCateg = $pictoGategories[$child];
                    }
                    elseif (file_exists($path . "/bundles/ayalineezcarteinteractive/images/pictos/menu/categ_" . $child . ".png")) {
                        $puceCateg = "/bundles/ayalineezcarteinteractive/images/pictos/menu/categ_" . $child . ".png";
                    }
                }


                if (array_key_exists($child, $listCritere)) {
                    $criteres = $listCritere[$child];

                    foreach ($criteres as $items) {
                        foreach ($items as $keyI => $item) {
                            if (!array_key_exists($keyI, $listCriteres)) {
                                $listCriteres[$keyI] = array('nom' => $item['nom'], 'modalites' => array());
                            }

                            $listsModalites = array();
                            if (array_key_exists($keyI, $listModalite)) {
                                $listsModalites = $listModalite[$keyI];

                            }
                            $listCriteres[$keyI]['modalites'] = $listsModalites;
                        }

                    }
                }
                array_push(
                    $children,
                    array(
                        'id' => $child,
                        'titreCategorie' => $sit_categories[$child],
                        'puceCategorie' => $puceCateg,
                        'criteres' => $listCriteres
                    )
                );
            }
            $section['children'] = $children;
            $section['iconeCss'] = $iconCss;
            $section['iconeImg'] = $iconImg;
            array_push($sections, $section);
        }
        //récupération du panier
        //$Panier = $this->getMap();

        return $this->render(
            "AyalineEzCarteInteractiveBundle:full:cartographie_full.html.twig",
            array(
                'mapSettings' => $mapSetting,
                'sitSettings' => $sections,
            )
        );

    }

    public function importAction($idc, $modalites)
    {
        //variables utiles
        $path = $this->get('kernel')->getRootDir();
        $paramModa = "";
        $listeModa = "";
        $xmlResultat = false;

        //paramètres de configuration
        $sit_categories = $this->container->getParameter('sit_categories');
        $idCritGeoloc = $this->container->getParameter('idcritere');
        $idModaliteLat = $this->container->getParameter('idmodaliteLatitude');
        $idModaliteLng = $this->container->getParameter('idmodaliteLongitude');
        $urlCache = $this->container->getParameter('URLCache');
        $dureeCache = $this->container->getParameter('DureeCache');
        $urlParams = $this->container->getParameter('URLParams');
        $urlRootSit = $this->container->getParameter('rootCartoSitUrl');
        $operateursCriteres = $this->container->getParameter('operateurCritere');
        $listOperateurs = array();
        $pictoGategories = $this->container->hasParameter("custom.picto.categories") ? $this->container->getParameter("custom.picto.categories") : array();

        foreach ($operateursCriteres as $operateurs) {
            foreach ($operateurs as $keyO => $operateur) {

                if (!array_key_exists($keyO, $listOperateurs)) {
                    $listOperateurs[$keyO] = $operateur;
                }
            }
        }
        //paramètres de l'url
        #catégorie
        $categ_id = explode("_", $idc);
        $categ_id = $categ_id[1];
        $categTitle = $sit_categories[$categ_id];
        $categTitle = implode("\\'", explode("'", $categTitle));

        #les modalités
//

        //Si les modalités sont choisies
        if ($modalites != "") {
            $tempoListeCriteres = explode("|", $modalites);
            foreach ($tempoListeCriteres as $critere) {
                $tempoListeModa = explode("-", $critere);
                $tempoCritere = $tempoListeModa[0];
                $tempoCritere = explode("_", $tempoCritere);
                $tempoCritere = $tempoCritere[1];
                $tempoSigne = "|";
                if ($listOperateurs[$tempoCritere] == ',') {
                    $tempoSigne = ",";
                }
                $listeModa = "";
                foreach ($tempoListeModa as $cle => $moda) {
                    if ($cle != 0) {
                        $tempoModa = explode("_", $moda);
                        $tempoModa = $tempoModa[1];
                        if ($listeModa == "") {
                            $listeModa .= $tempoModa;
                        } else {
                            $listeModa .= $tempoSigne . $tempoModa;
                        }
                    }
                }

                if ($listeModa != "") {
                    if ($paramModa == "") {
                        $paramModa .= $listeModa;
                    } else {
                        $paramModa .= '|' . $listeModa;
                    }
                }
            }
        }
        if ($paramModa != "") {
            $paramModa = "&mr2=" . urlencode($paramModa);
        }

        if ($this->fichierXMLCacheExpire($urlCache, "cachexmlcateg" . $categ_id . "cachexmlmoda" . md5($paramModa), $dureeCache)) {
            $contenuXML = simplexml_load_file($urlRootSit . "Recherche" . "&idc=" . $categ_id . $urlParams . $paramModa);
            $this->setFichierXMLCache($contenuXML->asXML(), $urlCache, "cachexmlcateg" . $categ_id . "cachexmlmoda" . md5($paramModa), $dureeCache);
            $xmlResultat = simplexml_load_file($path . "/" . $urlCache . "/" . "cachexmlcateg" . $categ_id . "cachexmlmoda" . md5($paramModa) . ".xml");
        } else {

            $xmlResultat = simplexml_load_file($path . "/" . $urlCache . "/" . "cachexmlcateg" . $categ_id . "cachexmlmoda" . md5($paramModa) . ".xml");
        }
        echo "<script>cartoMarkers['categ_$categ_id'] = [] ;</script>";

        if ($xmlResultat) {
            echo "<script>var markersProduitsCateg$categ_id= [] ;</script>";

            $i = 0;
            $varJS = "";
            foreach ($xmlResultat->details->detail as $detail) {
                /* tester si les valeur Latitude et Longitude sont correctes */
                $testGeoLat = $detail->xpath("./criteres/critere[@id=$idCritGeoloc]/modalites/modalite[@id=$idModaliteLat]/valModalite");
                $testGeoLng = $detail->xpath("./criteres/critere[@id=$idCritGeoloc]/modalites/modalite[@id=$idModaliteLng]/valModalite");
                if (count($testGeoLat) > 0 && count($testGeoLng) > 0 && is_numeric((string)$testGeoLat[0]) && is_numeric((string)$testGeoLng[0])) {
                    $idProduit = (string)$detail[@id];

                    $intitule = $detail->intitule;

                    $intitule = (string)$intitule[0];
                    $intitule = implode("\\'", explode("'", $intitule));
                    $geoLat = $detail->xpath("./criteres/critere[@id=$idCritGeoloc]/modalites/modalite[@id=$idModaliteLat]/valModalite");
                    $geoLat = (string)$geoLat[0];
                    $geoLng = $detail->xpath("./criteres/critere[@id=$idCritGeoloc]/modalites/modalite[@id=$idModaliteLng]/valModalite");
                    $geoLng = (string)$geoLng[0];
                    $detailVille = $detail->xpath("./ville/intituleVille");
                    $detailVille = (string)$detailVille[0];
                    $detailVille = implode("\\'", explode("'", $detailVille));
                    $detailAdr1 = $detail->xpath("./adresses/adresse/ligne1");
                    $detailAdr1 = (string)$detailAdr1[0];
                    $detailAdr1 = implode("\\'", explode("'", $detailAdr1));
                    $detailAdr2 = $detail->xpath("./adresses/adresse/ligne2");
                    $detailAdr2 = (string)$detailAdr2[0];
                    $detailAdr2 = implode("\\'", explode("'", $detailAdr2));
                    $detailAdr3 = $detail->xpath("./adresses/adresse/ligne3");
                    $detailAdr3 = (string)$detailAdr3[0];
                    $detailAdr3 = implode("\\'", explode("'", $detailAdr3));
                    $detailCP = $detail->xpath("./adresses/adresse/cp");
                    $detailCP = (string)$detailCP[0];
                    $detailTel = $detail->xpath("./adresses/adresse/tel1");
                    $detailTel = (string)$detailTel[0];
                    $detailFax = $detail->xpath("./adresses/adresse/fax");
                    $detailFax = (string)$detailFax[0];
                    $detailEmail = $detail->xpath("./adresses/adresse/email");
                    $detailEmail = (string)$detailEmail[0];
                    $detailEmail = implode("\\'", explode("'", $detailEmail));
                    $detailWeb = $detail->xpath("./adresses/adresse/web");
                    $detailWeb = (string)$detailWeb[0];
                    $detailWeb = implode("\\'", explode("'", $detailWeb));

                    $detailNewPhotos = array();
                    foreach ($detail->xpath("./newPhotos/newPhoto") as $newPhoto) {
                        $tempStr = (string)$newPhoto;
                        $tempStr = implode("\'", explode("'", $tempStr));
                        $detailNewPhotos[] = $tempStr;
                    }

                    $cheminPuceCateg = "/bundles/ayalineezcarteinteractive/images/pictos/map/categ_undefined.png";

                    if ($this->container->hasParameter("custom.picto.categories") && isset($pictoGategories[$categ_id])) {
                        $cheminPuceCateg = $pictoGategories[$categ_id];
                    }
                    elseif (file_exists($path . "/../web/bundles/ayalineezcarteinteractive/images/pictos/map/categ_" . $categ_id . ".png")) {
                        $cheminPuceCateg = "/bundles/ayalineezcarteinteractive/images/pictos/map/categ_" . $categ_id . ".png";
                    }

                    $varJS .= "
                      markersProduitsCateg" . $categ_id . "[$i] = new google.maps.Marker({
                      position: new google.maps.LatLng($geoLat,$geoLng),
                      map: map_container,
                      title:'" . $intitule . "',
                      icon: new google.maps.MarkerImage('" . $cheminPuceCateg . "'),
                      shadow: new google.maps.MarkerImage('/bundles/ayalineezcarteinteractive/images/pictos/map/marker_shadow.png',
                                                          new google.maps.Size(44, 33),
                                                          new google.maps.Point(0,0),
                                                          new google.maps.Point(0, 33)
                                                          )
                      });
                      ";
                    $geoAddr = $detailAdr1 . $detailAdr2 . $detailAdr3 . $detailCP . $detailVille;
                    $geoAddr = implode("\\'", explode("'", $geoAddr));
                    $geoAddr = implode("\\'", explode("'", $geoAddr));
                    $blocDetail = "<a href=\"#\" class=\"detail-street-view\" onClick=\"setSreetViewAt(\'$geoLat\',\'$geoLng\',\'$geoAddr\');return false;\" title=\"street view\"></a>";
                    $blocDetail .= "<a href=\"#\" class=\"detail-close-street-view cache\" onClick=\"hideStreetView();return false;\" title=\"Fermer street view\"></a>";

                    $blocDetail .= "<p class=\"intitule\"><a href=\"/Fiche/Detail/$idProduit\" target=\"_blank\">$intitule</a></p>";
                    $blocDetail .= "<p class=\"adresse\">$detailAdr1 $detailAdr2 $detailAdr3<br/>$detailCP $detailVille</p>";
                    $blocDetail .= "<p class=\"tel-fax\">Téléphone : $detailTel<br/>Fax : $detailFax</p>";
                    $blocDetail .= "<p class=\"web-mail\"><a>Site Internet : $detailWeb</a><br/><a>Contacter par mail: $detailEmail</a></p>";
                    $blocDetail .= "<div class=\"new-photos\">";

                    foreach ($detailNewPhotos as $key => $newPhoto) {
                        if ($key < 8) {
                            $blocDetail .= "<img src=\"$newPhoto\" class=\"new-photo\" />";
                            if ((((int)$key + 1) % 4) == 0 && $key != 0) {
                                $blocDetail .= "<div class=\"clear-both\"></div>";
                            }
                        }
                    }
                    $blocDetail .= "<div class=\"clear-both\"></div>";
                    $blocDetail .= "</div>";

                    $blocValise = "<div class=\"element-valise\">";
                    $blocValise .= "<a onClick=\"removeFromValise(\'$idProduit\');return false;\" href=\"#\" title=\"Retirer de ma valise\" id=\"removeValise-$idProduit\" class=\"remove-valise\"></a>";
                    $blocValise .= "<strong class=\"valise-elt-titre\">$intitule</strong>";
                    $blocValiseImg = "";

                    if (isset($detailNewPhotos[0])) {
                        $blocValiseImg = "<img class=\"valise-elt-image\" src=\"$detailNewPhotos[0]\"/>";
                    }
                    $blocValise .= "<p class=\"valise-adresse\">$blocValiseImg $detailAdr1 $detailAdr2 $detailAdr3<br/>$detailCP $detailVille</p>";
                    $blocValise .= "<div class=\"clear-both\"></div></div>";
                    $varJS .= "
                    google.maps.event.addListener(markersProduitsCateg" . $categ_id . "[$i], 'click', function() {
                       detailMarker={'idProd':'$idProduit','marker':markersProduitsCateg" . $categ_id . "[$i],'blocValise':'$blocValise'};
                        $('#detail-produit').fadeOut('fast',function(){
                            $('#detail-produit .content').html('$blocDetail');
                            $('#detail-produit .control .puce-categorie').html('Détails : $categTitle');
                            $('#detail-produit').fadeIn('slow');

                            if(valiseHasElement(detailMarker['idProd'])){
                               $('#detail-produit .retirer-valise').removeClass('cache');
                               $('#detail-produit .ajout-valise').addClass('cache');
                            }else{
                                $('#detail-produit .ajout-valise').removeClass('cache');
                                $('#detail-produit .retirer-valise').addClass('cache');
                            }
                        });
                    });
                    ";
                    $varJS .= "cartoMarkers['categ_$categ_id']=markersProduitsCateg" . $categ_id . ";";
                    $i++;
                }
            }
            return new Response("<script>" . $varJS . " markerCluster.addMarkers(cartoMarkers['categ_$categ_id']);</script>");
        }

    }

    protected function setFichierXMLCache($contenuXML, $cheminRepCahce, $nomFichier, $dureeCache)
    {

        $path = $this->get('kernel')->getRootDir();
        try {
            $cheminRepCahce = $path . "/" . $cheminRepCahce;
            $cheminFichierCache = $cheminRepCahce . "/" . $nomFichier . ".xml";
            if (!file_exists($cheminRepCahce)) {
                mkdir($cheminRepCahce, 0777, true);
            }
            if (!file_exists($cheminFichierCache)) {
                file_put_contents($cheminFichierCache, $contenuXML);
            } elseif ((filemtime($cheminFichierCache) + $dureeCache) < mktime(date("H"), date("i"), date("s"), date("n"), date("j"), date("Y"))) {
                file_put_contents($cheminFichierCache, $contenuXML);
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    protected function fichierXMLCacheExpire($cheminRepCahce, $nomFichier, $dureeCache)
    {
        $path = $this->get('kernel')->getRootDir();
        try {
            $cheminRepCahce = $path . "/" . $cheminRepCahce;
            $cheminFichierCache = $cheminRepCahce . "/" . $nomFichier . ".xml";
            if (!file_exists($cheminRepCahce)) {
                return true; //cache expiré
            }
            if (!file_exists($cheminFichierCache)) {
                return true; //cache expiré
            } elseif ((filemtime($cheminFichierCache) + $dureeCache) < time()) {
                return true; //cache expiré
            }
            return false; //cache non expiré
        } catch (Exception $e) {
            return true; //cache expiré
        }
    }

}
