<?php

namespace OfficeBrain\Bundle\CmsBundle\Manager\Extended;

use OfficeBrain\Bundle\CmsBundle\Manager\AbstractManager\SitemapAbstract;

/**
 * @author Employee Id: 4136
 * OB eCommerce Product - Sitemap
 * Extended class for HTML Sitemap methods
 */
class SitemapExtended extends SitemapAbstract
{
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to set member variables default value
     *
     * @param 1: $entityManager
     * @param 2: $request
     * @param 3: $routerManager
     * @param 4: $categoryApiManager
     * @param 5: $cmsPageManager
     * @param 6: $language
     * @param 7: $basePath
     *
     * @return: NULL
     *
     * @throws Exception: Null
     */
    public function __construct($entityManager, $request, $routerManager, $categoryApiManager, $cmsPageManager, $language, $basePath)
    {
        parent::__construct($entityManager, $request, $routerManager, $categoryApiManager, $cmsPageManager, $language, $basePath);
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to unset member variables
     *
     * @param : None
     *
     * @return NULL
     *
     * @throws Exception: Null
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function fetches all the system routes and passes the required routes to the controller
     *
     * @param : None
     *
     * @return : total number of routes and system routes
     *
     * @throws Exception : Null
     **/
    public function getSystemRoutes()
    {
        $collection = $this->allRoutes->getRouteCollection();
        $allRoutes = $collection->all();
        $systemRoutes = array();
        $routeCount = 0;

        /*foreach ($allRoutes as $route => $params) {
            $routeInfo = $this->siteMapRouteRepository->getRoutesInfo($route);
            if (!empty($routeInfo)) {
                $systemRoutes[$routeInfo[0]->getGroupName()][$route] = $routeInfo[0];
                ++$routeCount;
            }
        }*/

        $categoryList = $this->getCategorySubCategoryList();
        if (!empty($categoryList)) {
            foreach ($categoryList as $local => $categories) {
                foreach ($categories as $categories_key => $categories_value) {
                    $systemRoutes['product_category']['office_brain_search_bundle_browse_category'][$local][$categories_key] = $categories_value;
                    ++$routeCount;
                    
                    if(isset($categories_value['child']) && !empty($categories_value['child'])) {
                    	foreach ($categories_value['child'] as $categories_child_key => $categories_child_value) {
                    		$systemRoutes['product_category']['office_brain_search_bundle_browse_category'][$local][$categories_child_key] = $categories_child_value;
                    		++$routeCount;
                    		
                    		if(isset($categories_child_value['child']) && !empty($categories_child_value['child'])) {
                    			foreach ($categories_child_value['child'] as $categories_sub_child_key => $categories_sub_child_value) {
                    				$systemRoutes['product_category']['office_brain_search_bundle_browse_category'][$local][$categories_sub_child_key] = $categories_sub_child_value;
                    				++$routeCount;
                    				
                    				if(isset($categories_sub_child_value['child']) && !empty($categories_sub_child_value['child'])) {
                    					foreach ($categories_sub_child_value['child'] as $categories_third_child_key => $categories_third_child_value) {
                    						$systemRoutes['product_category']['office_brain_search_bundle_browse_category'][$local][$categories_third_child_key] = $categories_third_child_value;
                    						++$routeCount;
                    					}
                    				}
                    			}
                    		}
                    	}
                    }
                }
            }
        }

        $cmsPages = $this->getPageRoutes();
        foreach ($cmsPages as $index => $value) {
            foreach ($value->getLanguageMapping() as $language) {
                $systemRoutes['information'][$index]['slug'] = $value->getSlug();
                $systemRoutes['information'][$index]['title'] = $language->getPageTitle();
            }
            ++$routeCount;
        }

        unset($collection);
        unset($allRoutes);
        unset($categoryList);
        unset($cmsPages);

        return array('route_count' => $routeCount, 'system_routes' => $systemRoutes);
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function fetches all the pages created by cms
     *
     * @param : None
     *
     * @return : returns all the pages details created by cms
     *
     * @throws Exception : Null
     **/
    public function getPageRoutes()
    {
        return $this->cmsPageManager->getCmsActivePageList();
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function fetches all the category and sub categories list
     *
     * @param : None
     *
     * @return category and sub category list array
     *
     * @throws Exception : Null
     **/
    public function getCategorySubCategoryList()
    {
        return $this->categoryApiManager->getList(array($this->cultureCode));
    }

     /**
      * @author Employee Id: 4464
      *
      * Description : This function create actual physical file of the sitemap
      *
      * @param : $routeDetail
      *
      * @return Null
      *
      * @throws Exception : Null
      **/
     public function generateSitemapFile($routeDetail, $site_url='https://www.idmepromotions.com')
     {
         $totalRoutes = $routeDetail['route_count'];
         $allRoutes = $routeDetail['system_routes'];
         $sitemapFile = '/sitemap.xml';
         $data = '';
         $urlLimit = 50000;

         if ($totalRoutes <= $urlLimit) {
             $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
             $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
            //print_r($routeDetail['system_routes']); die;
             foreach ($routeDetail['system_routes'] as $group => $routes) {
                 if ($group != 'information') {
                     foreach ($routes as $route => $info) {
                         if ($route != 'office_brain_search_bundle_browse_category') {
                             echo $data .= '<url>
                                <loc>'.$site_url.$this->allRoutes->generate($route).'</loc>
                                <lastmod>'.date('c').'</lastmod>
                            </url>';
                         } elseif ($route == 'office_brain_search_bundle_browse_category') {
                             foreach ($info as $local => $categories) {
                                 foreach ($categories as $catId => $catValue) {
                                    if((!isset($catValue['child'])) && $catValue['parent_id']==0){
                                       echo  $data .= '<url>
                                        <loc>'.$site_url.$this->allRoutes->generate('office_brain_search_bundle_browse_category_search', array('_locale' => $local, 'category_slug' => $catValue['slug'])).'</loc>
                                        <lastmod>'.date('c').'</lastmod>
                                       </url>';
                                    }else{
                                         if((isset($catValue['child'])) && $catValue['parent_id']==0){
                                            echo $data .= '<url>
                                                <loc>'.$site_url.$this->allRoutes->generate('office_brain_search_bundle_browse_sub_category', array('_locale' => $local, 'category_slug' => $catValue['slug'])).'</loc>
                                                <lastmod>'.date('c').'</lastmod>
                                            </url>';
                                            foreach ($catValue['child'] as $chcatId => $childValue) {
                                                if(isset($childValue['child'])){
                                                 echo  $data .= '<url>
                                                    <loc>'.$site_url.$this->allRoutes->generate('office_brain_search_bundle_browse_sub_category', array('_locale' => $local, 'category_slug' => $catValue['slug'])).'</loc>
                                                    <lastmod>'.date('c').'</lastmod>
                                                </url>';
                                                    foreach ($childValue['child'] as $subchcatId => $subchildValue) {
                                                    echo   $data .= '<url>
                                                    <loc>'.$site_url.$this->allRoutes->generate('office_brain_search_bundle_browse_category_search', array('_locale' => $local, 'category_slug' => $subchildValue['slug'])).'</loc>
                                                    <lastmod>'.date('c').'</lastmod>
                                                   </url>';
                                                    }
                                                }else{
                                                 echo  $data .= '<url>
                                                    <loc>'.$site_url.$this->allRoutes->generate('office_brain_search_bundle_browse_category_search', array('_locale' => $local, 'category_slug' => $childValue['slug'])).'</loc>
                                                    <lastmod>'.date('c').'</lastmod>
                                                   </url>';
                                                }
                                            }
                                        }  
                                    }
                                 }
                             }
                         }
                     }
                 } elseif ($group == 'information') {
                     foreach ($routes as $page) {
                         echo $data .= '<url>
                            <loc>'.$site_url.$this->allRoutes->generate('office_brain_cmsbundle_cmspage_page', array('slug' => $page['slug'])).'</loc>
                            <lastmod>'.date('c').'</lastmod>
                        </url>';
                     }
                 }
             }
             $data .= '</urlset>';

             $this->generateFile($this->basePath.$sitemapFile, $data);
         } else {
             $routeCreated = 0;
             $fileList = array();
             $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
             $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
             $i = 1;

             if (!empty($routeDetail['system_routes'])) {
                 foreach ($routeDetail['system_routes'] as $group => $routes) {
                     if ($group != 'information') {
                         foreach ($routes as $route => $info) {
                             if ($route != 'office_brain_search_bundle_browse_category') {
                                 if ($routeCreated == $urlLimit) {
                                     $fileList[] = $this->endCreateFile($this->basePath, $data, $i);
                                     $data = '';
                                     $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
                                     $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
                                     ++$i;
                                     $totalRoutes = $totalRoutes - $urlLimit;
                                     $routeCreated = 0;
                                 }

                                echo $data .= '<url>
                                        <loc>'.$site_url.$this->allRoutes->generate($route).'</loc>
                                        <lastmod>'.date('c').'</lastmod>
                                    </url>';
                                 ++$routeCreated;

                                 if ($totalRoutes == $routeCreated) {
                                     $data .= '</urlset>';
                                     $fileList[] = $this->generateSubFile($this->basePath, $data, $i);
                                     ++$i;
                                 }
                             } elseif ($route == 'office_brain_search_bundle_browse_category') {
                                 foreach ($info as $local => $categories) {
                                     foreach ($categories as $catId => $catValue) {
                                         if ($routeCreated == $urlLimit) {
                                             $fileList[] = $this->endCreateFile($this->basePath, $data, $i);
                                             $data = '';
                                             $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
                                             $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
                                             ++$i;
                                             $totalRoutes = $totalRoutes - $urlLimit;
                                             $routeCreated = 0;
                                         }

                                        echo $data .= '<url>
                                                <loc>'.$site_url.$this->allRoutes->generate($route, array('_locale' => $local, 'category_slug' => $catValue['slug'])).'</loc>
                                                <lastmod>'.date('c').'</lastmod>
                                            </url>';
                                         ++$routeCreated;

                                         if ($totalRoutes == $routeCreated) {
                                             $data .= '</urlset>';
                                             $fileList[] = $this->generateSubFile($this->basePath, $data, $i);
                                             ++$i;
                                         }
                                     }
                                 }
                             }
                         }
                     } elseif ($group == 'information') {
                         foreach ($routes as $page) {
                             if ($routeCreated == $urlLimit) {
                                 $fileList[] = $this->endCreateFile($this->basePath, $data, $i);
                                 $data = '';
                                 $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
                                 $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
                                 ++$i;
                                 $totalRoutes = $totalRoutes - $urlLimit;
                                 $routeCreated = 0;
                             }

                           echo  $data .= '<url>
                                    <loc>'.$site_url.$this->allRoutes->generate('office_brain_cmsbundle_cmspage_page', array('slug' => $page['slug'])).'</loc>
                                    <lastmod>'.date('c').'</lastmod>
                                </url>';
                             ++$routeCreated;

                             if ($totalRoutes == $routeCreated) {
                                 $data .= '</urlset>';
                                 $fileList[] = $this->generateSubFile($this->basePath, $data, $i);
                                 ++$i;
                             }
                         }
                     }
                 }
                 $data = '';
                 $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
                 $data .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
                 foreach ($fileList as $fileName) {
                     $data .= '<sitemap>
                        <loc>'.$this->basePath.$fileName.'</loc>
                        <lastmod>'.date('c').'</lastmod>
                    </sitemap>';
                 }
                 $data .= '</sitemapindex>';
                 $this->generateFile($this->basePath.$sitemapFile, $data);
             }
             unset($routeCreated);
             unset($fileList);
             unset($i);
         }
         unset($totalRoutes);
         unset($routeDetail);
         unset($allRoutes);
         unset($sitemapFile);
         unset($data);
         unset($urlLimit);
     }

     /**
      * @author Employee Id: 4464
      *
      * Description : This function create sub xml files
      *
      * @param 1: $this->basePath
      * @param 2: $data
      * @param 3: $count
      *
      * @return Name of the file (with the path) which is created
      *
      * @throws Exception : Null
      **/
     public function generateSubFile($basePath, $data, $count)
     {
         $fileName = $basePath.'sitemap'.$count.'.xml';
         $handle = fopen($fileName, 'w') or die('Cannot open file:  '.$fileName);
         fwrite($handle, $data);
         unset($basePath);
         unset($data);
         unset($count);
         unset($handle);

         return $fileName;
     }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function create actual physical file of the sitemap
     *
     * @param 1: $fileName
     * @param 2: $data
     *
     * @return Null
     *
     * @throws Exception : Null
     **/
    public function generateFile($fileName, $data)
    {
        $handle = fopen($fileName, 'w') or die('Cannot open file:  '.$fileName);
        fwrite($handle, $data);
        unset($handle);
        unset($fileName);
        unset($data);
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to end current file and create a new file
     *
     * @param 1: $this->basePath
     * @param 2: $data
     * @param 3: $counter
     *
     * @return Name of the file (with the path) which is created
     *
     * @throws Exception : Null
     **/
    public function endCreateFile($basePath, $data, $counter)
    {
        $data .= '</urlset>';
        $fileName = $this->generateSubFile($basePath, $data, $counter);
        $data = '';
        $data .= '<?xml version="1.0" encoding="UTF-8" ?>';
        $data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">';
        unset($data);
        unset($basePath);
        unset($counter);

        return $fileName;
    }

    /**
     * @author Employee Id: 4464
     *
     * Description : Set the public routes into the database
     *
     * @param $instanceId
     *
     * @return : sitemap routes Object
     *
     * @throws Exception: Null
     */
    public function setRoutesInfo($instanceId = null)
    {
        if (empty($instanceId)) {
            $instanceId = $this->instanceId;
        }

        return $this->siteMapRouteRepository->setRoutesInfo($instanceId);
    }
}
