<?php

/**
 * $Id$
 * klient
 *
 */
class HomeSiteController extends MainController implements ControllerInterface {

	const PATH_BANER = '/upload/home';
	const COUNT_BOX = 6;
	const AVATAR_DEST_DIR = '/upload/home';
	const LOGO_DEST_DIR = '/upload/logo';
	const AVATAR_TEMP_DIR = '/upload/temp';
	const MAX_AVATAR_FILE_SIZE = 5; //Rozmiar w mb
	const CROPPER_BIG_PHOTO_MAX_WIDTH = 800;
	const CROPPER_BIG_PHOTO_MAX_HEIGHT = 800;
	const CROPPER_BIG_PHOTO_MAX_WIDTH_BANER = 1000;
	const CROPPER_BIG_PHOTO_MAX_HEIGHT_BANER = 1000;
	//const PHOTO_WIDTH = 288;
	//const PHOTO_HEIGHT = 127;

	const IMAGE_MINI_WIDTH = 450;
	const IMAGE_MINI_HEIGHT = 200;
	const IMAGE_MINI_WIDTH_BANER = 1024;
	const IMAGE_MINI_HEIGHT_BANER = 385;

	//const IMAGE_NORMAL_WIDTH = 627;
	//const IMAGE_NORMAL_HEIGHT = 219;
	/**
	 * 170px × 130px
	 * Domyslna metoda
	 *
	 */
	public function IndexAction($param) {
		//$this->SetAjaxRender();
		$dalData = StructureDAL::GetDalDataObj();
		$dalData->addCondition('publication', 1);
		$dalData->setSortBy('name');
		$arrayObjElement = StructureDAL::GetResult($dalData);
		//Utils::ArrayDisplay($arrayObjElement);
		//Utils::ArrayDisplay($param);
		$lang = SessionProxy::GetValue('lang');
		$countArray = range(0, 3);
		//Utils::ArrayDisplay($param);
		$dalData = MfHomeSiteDAL::GetDalDataObj();
		//$dalData->setCondition(array('lang' => $param['lang']));
		$dalData->setCondition(array('lang' =>$lang));
		$dalData->setLimit(4);

		$arrayObjHome = MfHomeSiteDAL::GetResult($dalData);

		//Utils::ArrayDisplay($countArray);
		$arrayToEdit = array();
		foreach ($countArray as $key => $element) {
			if (key_exists($key, $arrayObjHome)) {
				$arrayToEdit[] = $arrayObjHome[$key];
			} else {
				$arrayToEdit[] = MfHomeSiteDAL::GetEmptyObj();
			}
		}
		//Utils::ArrayDisplay($arrayToEdit);
		$this->smarty->assign('arrayObjElement', $arrayObjElement);
		$this->smarty->assign('arrayToEdit', $arrayToEdit);
		$this->smarty->assign('lang', $lang);
	}

	/**
	 * Dodawanie/edycja klient/banera
	 *
	 */
	public function EditAction($param) {
		$countArray = range(0, 3);
		$post = Request::GetAllPost();
		foreach ($countArray as $key => $element) {
			$objHomeElement = MfHomeSiteDAL::GetById($post['elementId'][$key]);
			//$objHomeElement = new MfHomeSite();
			$objHomeElement->SetName($post['elementName'][$key]);
			$objHomeElement->SetSourceUrl($post['elementUrl'][$key]);
//			$objHomeElement->SetDescription($post['elementText'][$key]);
			//$objHomeElement->SetIdSource($post['idElement'][$key]);


			if ($_FILES['elementImg_' . $key]['tmp_name']) {

// 				$photoSize = getimagesize($_FILES['elementImg_'.$key]['tmp_name']);
// 				$photoProp = $photoSize[0] / $photoSize[1];
// 				$photoWidth = $photoSize[0];
// 				$photoHeight = $photoSize[1];
// 				if ($photoWidth > self::CROPPER_BIG_PHOTO_MAX_WIDTH) {
// 					$photoHeight = self::CROPPER_BIG_PHOTO_MAX_WIDTH / $photoProp;
// 					$photoWidth = self::CROPPER_BIG_PHOTO_MAX_WIDTH;
// 				}
// 				if ($photoHeight > self::CROPPER_BIG_PHOTO_MAX_HEIGHT) {
// 					$photoWidth = self::CROPPER_BIG_PHOTO_MAX_HEIGHT * $photoProp;
// 					$photoHeight = self::CROPPER_BIG_PHOTO_MAX_HEIGHT;
// 				}
// 				$photoFile = PhotoDAL::SimplePhotoUpload($_FILES['elementImg_'.$key], self::AVATAR_TEMP_DIR . DIRECTORY_SEPARATOR , $photoWidth, $photoHeight, 100);



				$destName = md5('photo' . microtime());
				if (file_exists(PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg'))
					unlink(PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg');

				move_uploaded_file($_FILES['elementImg_' . $key]['tmp_name'], PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg');

// 				$propW = $photoWidth/self::IMAGE_MINI_WIDTH;
// 				$propH = $photoHeight/self::IMAGE_MINI_HEIGHT;
// 				if ($propW > $propH) {
// 					$prop = $propH;
// 				} else {
// 					$prop = $propW;
// 				}
// 				$photoMini = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/home', 0, 0, self::IMAGE_MINI_WIDTH*$prop, self::IMAGE_MINI_HEIGHT*$prop, self::IMAGE_MINI_WIDTH, self::IMAGE_MINI_HEIGHT);
				$objHomeElement->SetPhoto($destName . '.jpg');
			}



			MfHomeSiteDAL::Save($objHomeElement);
			//Utils::ArrayDisplay($objHomeElement);
		}

		$this->AddRedirectInfo('Zapisano', 'ok', Router::GenerateUrl('editHomeSite', array('_value' => 'HomeSite')), 0);
		//Utils::ArrayDisplay($_POST);
		//Utils::ArrayDisplay($_FILES);
	}

	public function LinksAction($param) {
		//Utils::ArrayDisplay($param);
		$lang = SessionProxy::GetValue('lang');
		$countArray = range(0, 5);
		//Utils::ArrayDisplay($param);
		$dalData = MfHomeSiteLinkDAL::GetDalDataObj();
		//$dalData->setCondition(array('lang' => $param['lang']));
		//$dalData->setCondition(array('lang' =>$lang));
		$dalData->setLimit(6);

		$arrayObjHome = MfHomeSiteLinkDAL::GetResult($dalData);

		//Utils::ArrayDisplay($countArray);
		$arrayToEdit = array();
		foreach ($countArray as $key => $element) {
			if (key_exists($key, $arrayObjHome)) {
				$arrayToEdit[] = $arrayObjHome[$key];
			} else {
				$arrayToEdit[] = MfHomeSiteLinkDAL::GetEmptyObj();
			}
		}
		//Utils::ArrayDisplay($arrayToEdit);
		$this->smarty->assign('arrayToEdit', $arrayToEdit);
		$this->smarty->assign('lang', $lang);
	}

	/**
	 * Dodawanie/edycja klient/banera
	 *
	 */
	public function EditLinkAction($param) {
		$countArray = range(0, 5);
		$post = Request::GetAllPost();
		foreach ($countArray as $key => $element) {
			$objHomeElement = MfHomeSiteLinkDAL::GetById($post['elementId'][$key]);
			//$objHomeElement = new MfHomeSite();
			$objHomeElement->SetName($post['elementName'][$key]);
			$objHomeElement->SetSourceUrl($post['elementUrl'][$key]);
			//$objHomeElement->SetDescription($post['elementText'][$key]);
			MfHomeSiteLinkDAL::Save($objHomeElement);
			//Utils::ArrayDisplay($objHomeElement);
		}
		$this->AddRedirect(Router::GenerateUrl('editHomeSite', array('HomeSite' => 'links')), 0);
		//Utils::ArrayDisplay($_POST);
		//Utils::ArrayDisplay($_FILES);
	}

	public function BanerAction($param) {
		//Utils::ArrayDisplay($param);
		$lang = SessionProxy::GetValue('lang');
		$countArray = range(0, 9);
		//Utils::ArrayDisplay($param);
		$dalData = MfHomeSiteBanerDAL::GetDalDataObj();
		//$dalData->setCondition(array('lang' => $param['lang']));
		$dalData->setCondition(array('lang' =>$lang));
		$dalData->setLimit(10);
		$dalData->setSortBy('sort');

		$arrayObjHome = MfHomeSiteBanerDAL::GetResult($dalData);

		//Utils::ArrayDisplay($countArray);
		$arrayToEdit = array();
		foreach ($countArray as $key => $element) {
			if (key_exists($key, $arrayObjHome)) {
				$arrayToEdit[] = $arrayObjHome[$key];
			} else {
				$arrayToEdit[] = MfHomeSiteBanerDAL::GetEmptyObj();
			}
		}
		//Utils::ArrayDisplay($arrayToEdit);
		$this->smarty->assign('arrayToEdit', $arrayToEdit);
		$this->smarty->assign('lang', $lang);
	}

	/**
	 * Dodawanie/edycja klient/banera
	 *
	 */
	public function EditBanerAction($param) {
		$countArray = range(0, 9);
		$post = Request::GetAllPost();
		foreach ($countArray as $key => $element) {
			$objHomeElement = MfHomeSiteBanerDAL::GetById($post['elementId'][$key]);
			//$objHomeElement = new MfHomeSite();
			$objHomeElement->SetName($post['elementName'][$key]);
			$objHomeElement->SetSourceUrl($post['elementUrl'][$key]);
			$objHomeElement->SetSort($post['elementSort'][$key]);
			$objHomeElement->SetDescription($post['elementText'][$key]);


			if ($_FILES['elementImg_' . $key]['tmp_name']) {

				$photoSize = getimagesize($_FILES['elementImg_' . $key]['tmp_name']);
				$photoProp = $photoSize[0] / $photoSize[1];

				$photoWidth = $photoSize[0];
				$photoHeight = $photoSize[1];

				if ($photoWidth > self::CROPPER_BIG_PHOTO_MAX_WIDTH_BANER) {
					$photoHeight = self::CROPPER_BIG_PHOTO_MAX_WIDTH_BANER / $photoProp;
					$photoWidth = self::CROPPER_BIG_PHOTO_MAX_WIDTH_BANER;
				}

				if ($photoHeight > self::CROPPER_BIG_PHOTO_MAX_HEIGHT_BANER) {
					$photoWidth = self::CROPPER_BIG_PHOTO_MAX_HEIGHT_BANER * $photoProp;
					$photoHeight = self::CROPPER_BIG_PHOTO_MAX_HEIGHT_BANER;
				}

				//$photoFile = PhotoDAL::SimplePhotoUpload($_FILES['elementImg_'.$key], self::AVATAR_TEMP_DIR . DIRECTORY_SEPARATOR , $photoWidth, $photoHeight, 100);



				$destName = md5('photo' . microtime());
				//Utils::ArrayDisplay($_FILES['elementImg_'.$key]['tmp_name']);
				//Utils::ArrayDisplay(PATH_STATIC_CONTENT.'upload/home/'.$destName.'.jpg');

				include_once (Config::Get('PATH_CORE') . '/lib/WideImage/WideImage.php');
				
				
				if (file_exists(PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg'))
					unlink(PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg');
				
				$img = WideImage::loadFromUpload('elementImg_' . $key);
				$img->resizeDown('1920', null)->saveToFile(PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg', 90);

				//move_uploaded_file($_FILES['elementImg_' . $key]['tmp_name'], PATH_STATIC_CONTENT . 'upload/home/' . $destName . '.jpg');


				$propW = $photoWidth / self::IMAGE_MINI_WIDTH_BANER;
				$propH = $photoHeight / self::IMAGE_MINI_HEIGHT_BANER;

				if ($propW > $propH) {
					$prop = $propH;
				} else {
					$prop = $propW;
				}
				//$photoMini = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/home', 0, 0, self::IMAGE_MINI_WIDTH_BANER*$prop, self::IMAGE_MINI_HEIGHT_BANER*$prop, self::IMAGE_MINI_WIDTH_BANER, self::IMAGE_MINI_HEIGHT_BANER);
				$objHomeElement->SetPhoto($destName . '.jpg');
			}

			if (isset($post['elementClear'][$key])) {
				$objHomeElement->SetName('');
				$objHomeElement->SetSourceUrl('');
				$objHomeElement->SetPhoto('');
				$objHomeElement->SetSort(100);
			}
			MfHomeSiteBanerDAL::Save($objHomeElement);
			//Utils::ArrayDisplay($objHomeElement);
		}

		$this->AddRedirect(Router::GenerateUrl('editHomeSite', array('HomeSite' => 'Baner')), 0);
		//Utils::ArrayDisplay($_POST);
		//Utils::ArrayDisplay($_FILES);
	}

	public function LogoAction($param) {
		if (!isset($param['type'])) {
			$param['type'] = 1;
		}

		$this->smarty->assign('type', $param['type']);

		$dalData = MfLogaDAL::GetDalDataObj();
		$dalData->addCondition('type', $param['type']);
		$arrayObj = MfLogaDAL::GetResult($dalData);
		$this->smarty->assign('arrayObj', $arrayObj);
	}

	public function AddLogoAction($param) {
		if (!isset($param['type'])) {
			$param['type'] = 1;
		}

		$obj = MfLogaDAL::GetEmptyObj();

		if (Request::GetPost('doLogoEdit')) {
			//Utils::ArrayDisplay(Request::GetAllPost());

			$out = array();
			$validator = new Validator(Request::GetAllPost());
			$data = Request::GetAllPost();

			$validator->IsEmpty('name', 'Pole nazwa musi zostać wypełnione.');
			if (!$_FILES['logo']['tmp_name']) {
				$validator->AddError('logo', 'Dodaj plik');
			}


			$out = $validator->GetErrorList();

			$active = Request::Get('active');
			$active ? $active = 1 : $active = '0';
			$obj->setPublication($active);
			$obj->setName($data['name']);
			$obj->setUrl($data['url']);
			$obj->setSort($data['sort']);
			$obj->setType($param['type']);
			$obj->setDateAdd(Utils::GetNowDate());




			//Utils::ArrayDisplay($out);
			if (empty($out)) {

				$destNameOrg = $_FILES["logo"]["name"];
				include(Config::Get('PATH_CORE') . '/lib/WideImage/WideImage.php');
				move_uploaded_file($_FILES["logo"]["tmp_name"], PATH_STATIC_CONTENT . self::LOGO_DEST_DIR . '/' . $param['type'] . '/' . $destNameOrg);
//				$img = WideImage::loadFromUpload('logo');
//				$img->saveToFile(PATH_STATIC_CONTENT.self::LOGO_DEST_DIR.'/'.$destNameOrg);
//				$img->resizeDown('100%', 75)->saveToFile(PATH_STATIC_CONTENT.self::LOGO_DEST_DIR.'/'.$destNameOrg, 90);
				$obj->setPhoto($destNameOrg);
				$idLoga = MfLogaDAL::Save($obj);

				$this->AddRedirectInfo('Zapisano', 'ok', Router::GenerateUrl('editLoga', array('HomeSite' => 'Logo', 'type' => $param['type'])));
			} else {

				$this->smarty->assign('obj', $obj);
				$this->smarty->assign('info', 'Pola obowiązkowe muszą zostać wypełnione.');
				$this->smarty->assign('type', 'error');

				foreach ($out as $item) {
					$error[$item['field']] = $item['msg'];
				}
				$this->smarty->assign('error', $error);
			}
		}
		$this->smarty->assign('obj', $obj);
		$this->smarty->assign('type', $param['type']);
	}

	public function EditLogoAction($param) {
		if (!isset($param['type'])) {
			$param['type'] = 1;
		}

		$dalData = MfLogaDAL::GetDalDataObj();
		$obj = MfLogaDAL::GetById($param['id']);

		if (Request::GetPost('doLogoEdit')) {
			//Utils::ArrayDisplay(Request::GetAllPost());

			$out = array();
			$validator = new Validator(Request::GetAllPost());
			$data = Request::GetAllPost();

			$validator->IsEmpty('name', 'Pole nazwa musi zostać wypełnione.');



			$out = $validator->GetErrorList();

			$active = Request::Get('active');
			$active ? $active = 1 : $active = '0';
			$obj->setPublication($active);
			$obj->setName($data['name']);
			$obj->setUrl($data['url']);
			$obj->setSort($data['sort']);
			$obj->setType($param['type']);
			$obj->setDateAdd(Utils::GetNowDate());




			//Utils::ArrayDisplay($out);
			if (empty($out)) {
				if ($_FILES['logo']['tmp_name']) {
					$destNameOrg = $_FILES["logo"]["name"];
					move_uploaded_file($_FILES["logo"]["tmp_name"], PATH_STATIC_CONTENT . self::LOGO_DEST_DIR . '/' . $param['type'] . '/' . $destNameOrg);

//					include(Config::Get('PATH_CORE').'/lib/WideImage/WideImage.php');
//					$img = WideImage::loadFromUpload('logo');
//					$img->resizeDown('100%', 75)->saveToFile(PATH_STATIC_CONTENT.self::LOGO_DEST_DIR.'/'.$destNameOrg, 90);
					$obj->setPhoto($destNameOrg);
				}
				$idLoga = MfLogaDAL::Save($obj);

				$this->AddRedirectInfo('Zapisano', 'ok', Router::GenerateUrl('editLoga', array('HomeSite' => 'Logo', 'type' => $param['type'])));
			} else {

				$this->smarty->assign('obj', $obj);
				$this->smarty->assign('info', 'Pola obowiązkowe muszą zostać wypełnione.');
				$this->smarty->assign('type', 'error');

				foreach ($out as $item) {
					$error[$item['field']] = $item['msg'];
				}
				$this->smarty->assign('error', $error);
			}
		}
		$this->smarty->assign('obj', $obj);
	}

	public function DeleteLogoAction($param) {
		$this->SetNoRender();
		if (!isset($param['type'])) {
			$param['type'] = 1;
		}

		$dalData = MfLogaDAL::GetDalDataObj();
		$obj = MfLogaDAL::GetById($param['id']);
		if ($obj->getId() > 0) {
			$dalData->setObj($obj);
			$param['type'] = $obj->getType();
			//Utils::ArrayDisplay(PATH_STATIC_CONTENT . self::LOGO_DEST_DIR . '/' . $param['type'] . '/' . $obj->getPhoto());
			if (file_exists(PATH_STATIC_CONTENT . self::LOGO_DEST_DIR . '/' . $param['type'] . '/' . $obj->getPhoto())) {
				unlink(PATH_STATIC_CONTENT . self::LOGO_DEST_DIR . '/' . $param['type'] . '/' . $obj->getPhoto());
			}
			MfLogaDAL::Delete($dalData);
		} else {
			$this->AddRedirectInfo('Brak elementu', 'error', Router::GenerateUrl('editLoga', array('HomeSite' => 'Logo', 'type' => $param['type'])));
		}
		$this->AddRedirectInfo('Usunięto', 'ok', Router::GenerateUrl('editLoga', array('HomeSite' => 'Logo', 'type' => $param['type'])));
	}

	public function BoxAction($param) {

//Utils::ArrayDisplay($param);
//Utils::ArrayDisplay($_FILES);
		if (Request::GetPost('doBoxEdit')) {
			//Utils::ArrayDisplay(Request::GetAllPost());

			if ($_FILES['box']['tmp_name']) {


				move_uploaded_file($_FILES['box']['tmp_name'], PATH_STATIC_CONTENT . "/upload/baner.jpg");

				$this->AddRedirectInfo('Zapisano', 'ok', Router::GenerateUrl('editBox', array('HomeSite' => 'Box')));
			} else {
				//Utils::ArrayDisplay('err');
				$this->AddRedirectInfo('Dodaj plik', 'info', Router::GenerateUrl('editBox', array('HomeSite' => 'Box')));
			}
		}
	}

	public function ArticleBoxAction($param) {
		$dalData = MfArticleBoxDAL::GetDalDataObj();
		$arrayObj = MfArticleBoxDAL::GetResult($dalData);
		$this->smarty->assign('arrayObj', $arrayObj);
	}

	public function EditArticleAction($param) {
		$arrayIdLang = array('pl' => 1, 'en' => 2);
		$lang = SessionProxy::GetValue('lang');
		
		if (isset($arrayIdLang[$lang])) {
			$id = $arrayIdLang[$lang];
			$obj = MfArticleBoxDAL::GetById($id);
			//Utils::ArrayDisplay($obj);
			if ($obj->getId() != $id) {
				$dalData = MfArticleBoxDAL::GetDalDataObj();
				$obj->setId($id);
				$obj->setLang($lang);
				$dalData->setObj($obj);
				MfArticleBoxDAL::Insert($dalData);
			} 
			$this->smarty->assign('obj', $obj);

			if (Request::IsPost()) {
				$data = Request::GetAllPost();
				$publication = Request::Get('publication');
					$publication ? $publication = 1 : $publication = '0';
				$obj->setDescription($data['description']);
				$obj->setShortnote($data['shortnote']);
				$obj->setPublication($publication);
				$obj->setLang($lang);
				//$obj->setDatePublication($data['datePublication']);
				$obj->setName($data['name']);


				$dalData = MfArticleBoxDAL::GetDalDataObj();
				$dalData->setObj($obj);
				MfArticleBoxDAL::Save($obj);
				$this->AddRedirectInfo('Zapisano', 'ok', Router::GenerateUrl('', array('HomeSite'=>'EditArticle')));
			}
		} else {
			$obj = MfArticleBoxDAL::GetEmptyObj();
		}
		$this->smarty->assign('obj', $obj);
	}

	/**
	 * Metoda wspolna
	 *
	 */
	public function preDispatch($param) {
		$this->Run($param);
		//$admin = AuthDAL::GetAdmin();
		$this->RunShared('Auth', array());
		
		
		$this->smarty->assign('titleAdmin', 'Formularz');
		$struct = array(
		//'User' => array('User' => 'Index'),
        'Rejestracja' => array('Calc' => 'Reg'),
//		'Parametry' => array('Calc' => 'Index', 'type' => 1),
		//'Parametry mieszkanie' => array('Calc' => 'Index', 'type' => 2),
		'Treści' => array('HomeSite' => 'EditArticle')
		);

		$this->smarty->assign('structure', $this->renderStruct($struct));
	}

	private function renderStruct($struct) {
		$return = '';

		foreach ($struct AS $k => $row) {
			$return .= '<li><a href="' . Router::GenerateUrl('dictpig', $row) . '">' . $k . '</a></li>';
		}

		$html = '<ul>';
		$html .= $return;
		$html .= '</ul>';


		return $html;
	}

	public function postDispatch($param) {
		
	}

}

?>