<?php

namespace OfficeBrain\Bundle\CategoryBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;


class CategoryController extends Controller
{
	public function __construct()
	{
		$this->request = null;
		$this->entityManager = null;
		$this->session = null;
		$this->projectSetting = null;
		$this->statsh_cache_wrapper=RedisCacheService::create();
	}
	public function __destruct()
	{
		unset($this->request);
		unset($this->entityManager);
		unset($this->session);
		unset($this->projectSetting);
		unset($this->statsh_cache_wrappe);
	}
	
	public function init()
	{
		$this->request = $this->getRequest();
		$this->entityManager = $this->getDoctrine()->getManager();
		$this->session = $this->request->getSession();
		$this->translator = $this->get('translator');
		$this->projectSetting = $this->request->get('project_setting');
		$this->apiManager= $this->get("officebrain_category_api_manager");
	}
	
	
	/**
	 * @Route("/{_locale}/category/list",
	 * 	name="officebrain_category_bundle__list",options={"expose"=true}
	 * )
	 * @Template("OfficeBrainCategoryBundle::homePageCategoryListing.html.twig")
	 */
	public function homePageCategoryListingAction()
	{
		$this->request = $this->getRequest();
		$this->entityManager = $this->getDoctrine()->getManager();
		$this->session = $this->request->getSession();
		$this->translator = $this->get('translator');
		$this->projectSetting = $this->request->get('project_setting');
		$this->apiManager= $this->get("officebrain_category_api_manager");
		
		//$this->init();
		
		
		$param = $this->request->get('_route_params');
		$locale=$this->request->getLocale();
		list($default_language) = explode("_",$this->container->getParameter('locale'));
		
		// -----------------------------------------------------------------------
		$cacheSiteKey = array('CATEGORYLIST',$locale,$this->projectSetting['instance_id'],$this->container->getParameter('kernel.environment'));
		$this->moduleCachePrefix='__HomePageCategoryList__:';
		$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
		$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
		if($cacheData){
			return $cacheData;
		}
		
		$categoryData = $this->apiManager->getList((array)$default_language);
		$categoryDataResult = $this->apiManager->fetchAllCategories($categoryData);
		//print_r($categoryDataResult); die;
		$categoryList = $this->apiManager->buildCategoryListView($categoryDataResult["product_categories"]);
		$sort_position = array_column($categoryList, 'sort_position');
		array_multisort($sort_position, SORT_ASC, $categoryList);
		$res = array("category_list" => $categoryList);
		//print_r($res); die;
		$response = $this->render('OfficeBrainCategoryBundle::homePageCategoryListing.html.twig',$res );
		if(!empty($cacheKey))
		{
			RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
		}
		
		return $res;
	}

	/**
	 * @Route("/{_locale}/call-sync-category-listing",
	 * 	name="officebrain_category_bundle_callSyncListing",options={"expose"=true}
	 * )
	 * 
	 */
	public function callSyncListingAction()
	{
		ignore_user_abort(true);
		set_time_limit(0); 

		// Start output buffer so we can flush early
		if (ob_get_level() == 0) {
			ob_start();
		}

		echo "Sync job triggered";

		// Send headers for immediate response
		header("Content-Type: text/plain");
		header("Connection: close");
		header("Content-Length: " . ob_get_length());

		ob_end_flush();
		flush();

		// Finish request immediately (works with PHP-FPM)
		if (function_exists('fastcgi_finish_request')) {
			fastcgi_finish_request();
		}

		/* -------------------------------------------------
		   Everything below runs in background
		--------------------------------------------------*/
    
		$this->apiManager= $this->get("officebrain_category_api_manager");
		
		$category = $this->apiManager->getAllSynCategoryForChangeStatus('Progress');
		if($category==NULL){
			$callApi = $this->apiManager->getAllSynCategoryForChangeStatus('Pending');
			if($callApi!=NULL){
				$pmsId = $callApi->getPmsId();
				$categoryStatus=$callApi->getCategoryStatus();
				$name=$callApi->getName();
				$id=$callApi->getId();
				$action = 'delete';
				if($categoryStatus=="Active"){
					$action='add';
				}
				
				$obj = $this->apiManager->addCategoryStatusSchedular($pmsId,$categoryStatus,$name,'Progress',$id);

				$totalItems = ($obj->getProductCount()!=0) ? $obj->getProductCount() : 1;
				$avgTimePerItem = 2.5; // seconds
				$etaSeconds = $totalItems * $avgTimePerItem;
				$minutes = floor(($etaSeconds % 3600) / 60);
				$newDateTime = date('Y-m-d H:i:s', strtotime("+$minutes minutes"));
				$this->apiManager->setEstimateTime($obj,$newDateTime);

				echo $command = '/usr/bin/php ' . $this->get('kernel')->getRootDir() . '/console office_brain:solr:sync:product-category-active-inactive  --instanceId=1  --culture="en_us" --categoryId='.$pmsId.' --action='.$action.' --schedularId='.$id.' > /dev/null 2>&1 &';

				
				shell_exec($command);

				
			}
		}
		echo "End"; die;
	}
}
