<?php

namespace OfficeBrain\Bundle\ImageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;

class ImageController extends Controller
{
    /**
	 * @Route("{_local}/image/upload/{section}", name="officebrain_core_bundle_image_upload")	 
	 * @Template()
	 */
	
	public function ImageUploadAction(){
		//$uploadFilePath = $this->get('kernel')->getRootDir().'/../web'.$this->container->getParameter('_default_image_upload_path');
		$uploadFilePath = $this->container->getParameter('tmp_image_upload_path');
		$allwoedUpload = $this->container->getParameter('allowed_upload_size');
		$allwedMimeType = $this->container->getParameter('allowed_mime_type');
		$section = $this->getRequest()->get('section','');
		$translator = $this->get('translator');
		
		$imageManagerApi = $this->get('officebrain_image_api_manager');
		
		if(!IS_DIR($uploadFilePath)){
			mkdir($uploadFilePath,0777,true);
		}
		
		$maxSizeUploadFromIni = intval(ini_get('upload_max_filesize'));
		$maxSizeUpload = ($maxSizeUploadFromIni >$allwoedUpload) ? $allwoedUpload : $maxSizeUploadFromIni;
		
		$logoFile = $error ='';
		
		//TODO Change MSG To configuration file
		foreach($_FILES as $file){
			if($file['size']>$maxSizeUpload* 1024 * 1024){
				$error = $translator->trans('max_upload_size');
				$error = sprintf($error,$maxSizeUpload);
			}else if(!in_array($file['type'],$allwedMimeType)){
				$error = $translator->trans('allowed_file_type');
			}
			
			if(!$error){
				$logoFile = time()."_".preg_replace('/[^A-Za-z0-9\-\.]/', '', basename($file['name']));
				@move_uploaded_file($file['tmp_name'], $uploadFilePath.$logoFile);
			
				$response = $imageManagerApi->uploadImage($uploadFilePath.$logoFile,$section);
			}
		}
		
		if(!$error){
			$return = array (
						'form_status' => 'success',
						'img_name'=> $logoFile,
						'section'=> $section,
						/*'data' => $this->container->get('twig')->render("OfficeBrainCoreBundle:Admin:image_ie9.html.twig",
									array('image'=>$this->container->getParameter('_default_image_upload_path_for_avalanche_imagine').$logoFile,
									'field_id'=>$this->get('request')->get('field_id'))),*/
						'form_errors' => ''
				);
		} else {
			$return = array (
					'form_status' => 'error',
					'error_message' => $error);
		}
		
		/*$handleIe9 = $this->get('request')->get('browser_info','');
		
		if($handleIe9=="lower_msie"){
			$response = new Response();
			$return['data'] = htmlentities($return['data'],ENT_QUOTES);
			$response->setContent(json_encode($return));
			$response->headers->set('Content-Type', 'text/html');
			return $response;
		} else {
			return new JsonResponse ( $return);
		}*/
		
		return new JsonResponse ( $return);
	}
	
	/**
	 * @Route("{_local}/clientimage/upload/{section}", name="officebrain_core_bundle_image_upload_client")
	 * @Template()
	 */
	
	public function ClientImageUploadAction(){
		$uploadFilePath = $this->container->getParameter('client_upload_base_path');
		
		$allwoedUpload = $this->container->getParameter('allowed_upload_size');
		$allwedMimeType = $this->container->getParameter('allowed_mime_type');
		$section = $this->getRequest()->get('section','');
		$translator = $this->get('translator');
		$uploadFilePath = $uploadFilePath.$section."/";
		$imageManagerApi = $this->get('officebrain_image_api_manager');
		
		if(!IS_DIR($uploadFilePath)){
			mkdir($uploadFilePath,0777,true);
		}
	
		$maxSizeUploadFromIni = intval(ini_get('upload_max_filesize'));
		$maxSizeUpload = ($maxSizeUploadFromIni >$allwoedUpload) ? $allwoedUpload : $maxSizeUploadFromIni;
	
		$logoFile = $error ='';
	
		//TODO Change MSG To configuration file
		foreach($_FILES as $file){
			if($file['size']>$maxSizeUpload* 1024 * 1024){
				$error = $translator->trans('max_upload_size');
				$error = sprintf($error,$maxSizeUpload);
			}else if(!in_array($file['type'],$allwedMimeType)){
				$error = $translator->trans('allowed_file_type');
			}
				
			if(!$error){
				$logoFile = time()."_".preg_replace('/[^A-Za-z0-9\-\.]/', '', basename($file['name']));
				$isUploaded = @move_uploaded_file($file['tmp_name'], $uploadFilePath.$logoFile);
				if ( $section == 'category' && $isUploaded ){// if section is category then only need to save thumbnail image 
					$thumbnailPath = $uploadFilePath.'thumbnail/';
					if(!IS_DIR($thumbnailPath)){
						mkdir($thumbnailPath,0777,true);
					}
					$generateThumbCmd = 'convert "'.$uploadFilePath.$logoFile.'" -resize 500x500 "'.$thumbnailPath.$logoFile.'" ';
					exec($generateThumbCmd.' 2>&1', $errors);
					//echo "<pre>";print_r($errors);die;// to check errors
				}
			}
		}
	
		if(!$error){
			$return = array (
					'form_status' => 'success',
					'img_name'=> $logoFile,
					'section'=> $section,
					/*'data' => $this->container->get('twig')->render("OfficeBrainCoreBundle:Admin:image_ie9.html.twig",
					 array('image'=>$this->container->getParameter('_default_image_upload_path_for_avalanche_imagine').$logoFile,
					 		'field_id'=>$this->get('request')->get('field_id'))),*/
					'form_errors' => ''
			);
		} else {
			$return = array (
					'form_status' => 'error',
					'error_message' => $error);
		}
		return new JsonResponse ( $return);
	}
	
	
	/**
	 * Description : For Upload Document file to API
	 * @Route("{_local}/document/upload/{section}", name="officebrain_core_bundle_document_upload")
	 * @Template()
	 */
	
	public function documentUploadAction(){
		//$uploadFilePath = $this->get('kernel')->getRootDir().'/../web'.$this->container->getParameter('_default_image_upload_path');
		$uploadFilePath = $this->container->getParameter('tmp_document_upload_path');
		$allwoedUpload = $this->container->getParameter('allowed_document_upload_size');
		$allwedMimeType = $this->container->getParameter('allowed_document_mime_type');
		$section = $this->getRequest()->get('section','');
		$translator = $this->get('translator');
	
		$imageManagerApi = $this->get('officebrain_image_api_manager');
	
		if(!IS_DIR($uploadFilePath)){
			mkdir($uploadFilePath,0777,true);
		}
		$maxSizeUploadFromIni = intval(ini_get('upload_max_filesize'));
		$maxSizeUpload = ($maxSizeUploadFromIni >$allwoedUpload) ? $allwoedUpload : $maxSizeUploadFromIni;
	
		$logoFile = $error ='';
	
		//TODO Change MSG To configuration file
		foreach($_FILES as $file){
			if($file['size']>$maxSizeUpload* 1024 * 1024){
				$error = $translator->trans('max_upload_size');
				$error = sprintf($error,$maxSizeUpload);
			}else if(!in_array($file['type'],$allwedMimeType)){
				$error = $translator->trans('allowed_document_type');
			}
				
			if(!$error){
				$logoFile = time()."_".preg_replace('/[^A-Za-z0-9\-\.]/', '', basename($file['name']));
				@move_uploaded_file($file['tmp_name'], $uploadFilePath.$logoFile);
				
				//For Upload Document in API
				$response = $imageManagerApi->uploadImage($uploadFilePath.$logoFile,$section);
			}
		}
		if(!$error){
			$return = array (
					'form_status' => 'success',
					'doc_name'=> $logoFile,
					'section'=> $section,
					/*'data' => $this->container->get('twig')->render("OfficeBrainCoreBundle:Admin:image_ie9.html.twig",
					 array('image'=>$this->container->getParameter('_default_image_upload_path_for_avalanche_imagine').$logoFile,
					 		'field_id'=>$this->get('request')->get('field_id'))),*/
					'form_errors' => ''
			);
		} else {
			$return = array (
					'form_status' => 'error',
					'error_message' => $error);
		}
		return new JsonResponse ( $return);
	}
}
