<?php
/**
 * @author wojbach
 * @author Janusz
 */
class Banner_Controller_Admin_IndexController extends Eppe_Backend_Controller_Action {
	
	private $_slider;
        private $_sliderTmp;
        private $_config;

        const THUMB_PREFIX = 'thumb_';
        const CANVAS_PREFIX = 'canvas_';
        const ORIGINALS_PREFIX = 'original_';

        public function init() {
                parent::init();
                $this->_slider = 'public' . Banner_Module_Module::getInstance()->getSiteImgPath();
                $this->_sliderTmp = 'public' . Banner_Module_Module::getInstance()->getAdminImgPath() . 'slides/';
                $this->_config = Banner_Module_Module::getInstance()->config;
                $namespaceNestedBlock = new Zend_Session_Namespace('nestedblock');
                $namespaceNestedBlock->active = 0;
        }

        /**
         * Główna akcja modułu slajdera, odpowiada za wyświetlenie listy slajdów oraz zapis oryginalnego slajdu z formularza. 
         */
        public function indexAction() {
                $this->clearTmpDirectory();
		

                $mSlide = new Banner_Model_Bannerslides();
                $mConfig = new Banner_Model_Bannerconfigs();

                $addForm = new Banner_Form_Admin_Add();
                $settingsForm = new Banner_Form_Admin_Settings();

                if ($this->_isPost() && $addForm->isValid($this->_getPost())) {
                        if ($addForm->slide->isUploaded()) {

                                //zapis nazwy pliku do zmiennej
                                $filename = $addForm->slide->getValue();

				$link = ($this->_config->link)? $addForm->getValue('url') : null;
				$slogan = ($this->_config->slogan)? $addForm->getValue('slogan') : null;
				$alt = ($this->_config->alt)? $addForm->getValue('alt') : null;
				
                                //stworzenie wersji roboczej
                                $id = $mSlide->createSlideRow($filename, $link, $slogan, $alt);

                                //ustalenie lokalizacji zapisywanych plików - jeden z nich to oryginał, drugi półtno, z którego będzie wycinany slajd
                                $originalSlidePath = $this->_sliderTmp . self::ORIGINALS_PREFIX . $id . '.' . Eppe_Tools::getFileExtension($addForm->slide->getValue());
                                $canvalSlidePath = $this->_sliderTmp . self::CANVAS_PREFIX . $id . '.' . Eppe_Tools::getFileExtension($addForm->slide->getValue());

                                //zapis plików
                                try {
                                        $this->saveFormFileElement($addForm->slide, $originalSlidePath, $this->_config->imageThumbs->original->width, $this->_config->imageThumbs->original->height);
                                        $this->saveFormFileElement($addForm->slide, $canvalSlidePath, $this->_config->imageThumbs->canvas->width, $this->_config->imageThumbs->canvas->height);
                                }
                                catch (Exception $e) {
                                        $this->_addMessage($e->getMessage(), 'error');
                                        $this->_helper->redirector->gotoSimple('index', 'admin_index', 'Banner');
                                }

                                //przekierowanie do akcji kadrowania slajdu
                                $this->_forward('crop', 'admin_index', 'Banner', array('id' => $id));
                        }
                        else {
                                $this->_addMessage('Wystąpił błąd poczas próby zapisania pliku na serwerze', 'error');
                        }
                }

                //wypełnienie 
		$settingsData = $mConfig->getAttributes();
		$settingsForm->populate($settingsData);

		$this->pushIndexJs();

                $this->view->activeItems = $mSlide->getActiveItems();
                $this->view->inactiveItems = $mSlide->getInactiveItems();

                $this->view->addForm = $addForm;
              $this->view->settingsForm = $settingsForm;
        }

        /**
         * Ajaxowa akcja zapisu zmian konfiguracyjnych bannera jak np. czas, po którym zmieni się slajd 
         */
        public function ajaxSettingsAction() {
                $this->_disableView();

                $settingsForm = new Banner_Form_Admin_Settings();
                $mConfig = new Banner_Model_Bannerconfigs();

                if ($settingsForm->isValid($post = $this->_getPost())) {
                        foreach ($post as $key => $value) {
				$bean = $mConfig->getAttribute($key);
				$bean->value = $value;
				R::store($bean);
                        }
                }
                echo Zend_Json::encode(array('result' => 'success', 'msg' => __('Zmiany zostały zapisane')));
                exit;
        }

        /**
         * Akcja obsługująca wyświetlenie oraz działanie panelu kadrowania slajdu
         * @throws Exception 
         */
        public function cropAction() {
                if (NULL === $id = $this->_getParam('id'))
                        throw new Exception('No slide given!');

                $mSlide = new Banner_Model_Bannerslides();

		$row = R::findOne($mSlide::NAME, 'WHERE id = ?', array($id));
                if (!$row)
                        throw new Exception('Invalid slide ID!');
                
                $form = new Banner_Form_Admin_Crop();
                
                if ($this->_isPost() && $form->isValid($post = $this->_getPost()) && isset($post['src'])) {
                        
                        $image = PhpThumb_PhpThumbFactory::create(ROOT_PATH . $this->removeImgTrigger($post['src']));
                        $dimensions = $image->getCurrentDimensions();
                        /* save cropped */
                        $image->crop($form->getValue('x1'), $form->getValue('y1'), $this->_config->imageThumbs->slide->width, $this->_config->imageThumbs->slide->height);
                        $save = $image->save(ROOT_PATH . $this->_slider . $id . '.' . $image->getLowerFormat());

                        /* save sort thumb */
                        $image->resize($this->_config->imageThumbs->thumb->width);
                        $save_thumb = $image->save(ROOT_PATH . $this->_sliderTmp . self::THUMB_PREFIX . $id . '.' . $image->getLowerFormat());
                        
                        if (isset($id)) {
                                if (!$save->getErrorMessage() && !$save_thumb->getErrorMessage()) {
					$row->last_slice_x = $form->getValue('x1');
					$row->last_slice_y = $form->getValue('y1');
					$row->last_slice_width = $dimensions['width'];
					$row->last_slice_height = $dimensions['height'];
					$row->is_available = 1;
					R::store($row);
                                        
                                        $this->_addMessage('Element został zapisany.');
                                }
                                else {
                                        $this->_addMessage('Wystąpił błąd poczas próby zapisania pliku na serwerze', 'error');
                                }
                                $this->_helper->redirector->gotoSimple('index');
                        }
                }

                $this->pushCropJs($row);

                $this->view->thumb_width = $this->_config->imageThumbs->thumb->width;
                $this->view->thumb_height = $this->_config->imageThumbs->thumb->height;
                $this->view->image = $this->getCanvas($row);
                $this->view->form = $form;
        }

        public function modifyUrlAction() {
                if (NULL === $id = $this->_getParam('id'))
                        throw new Exception('Slide id is not defined');

                $dbTable = new Banner_Model_Bannerslides();
                if (NULL === $bean = $dbTable->getSlideUrl($id))
                        throw new Exception('Slide doesn\'t exist');

		$data = $bean->export();
		
                $form = new Banner_Form_Admin_Url();

                if ($this->getRequest()->isPost()) {
                        $post = $this->getRequest()->getPost();
                        if ($form->isValid($post)) {
                                try {
					$bean->url = (isset($post['url']))? $post['url'] : '';
					$bean->slogan = (isset($post['slogan']))? $post['slogan'] : '';
					$bean->alt = (isset($post['alt']))? $post['alt'] : '';
					$update = R::store($bean);

                                        if ($update) {
                                                $this->_addMessage('Zmiany zostały zapisane.');
                                        }
                                        else {
                                                $this->_addMessage('Zmiany nie zostały wprowadzone.', 'error');
                                        }
                                        $page = new Zend_Navigation_Page_Mvc(array('module' => 'Banner', 'controller' => 'admin_index', 'action' => 'index'));
                                        $this->_redirect($page->getHref());
                                }
                                catch (Exception $e) {
                                        echo 'Caught exception: ', $e->getMessage(), PHP_EOL;
                                }
                        }
                }
                $form->populate($data);
                $this->view->form = $form;
        }
        
        public function ajaxDeleteSlideAction() {
                $this->_disableView();

                $mSlide = new Banner_Model_Bannerslides();

                if (NULL === $id = $this->_getParam('id')) {
                        echo Zend_Json::encode(array('result' => 'error', 'msg' => 'Nie podano żadnego elementu.'));
                        exit;
                }
                
                if (NULL === $bean = $mSlide->getSlideUrl($id)) {
                        echo Zend_Json::encode(array('result' => 'error', 'msg' => 'Element nie istnieje.'.$id));
                        exit;
                }
                
		R::trash($bean);
		
                if (NULL == $mSlide->getSlideUrl($id))
                        echo Zend_Json::encode(array('result' => 'success', 'msg' => 'Wybrany element został usuniety'));
                else
                        echo Zend_Json::encode(array('result' => 'error', 'msg' => 'Wybrany element nie został odnaleziony'));
        }

        /**
         * Ajaxowa akcja obsługująca sortowanie slajdów
         */
        public function ajaxOrderImagesAction() {
                if ($this->getRequest()->isPost()) {
                        $type = $this->_getParam('type');
                        if ($type != 1 AND $type != 0)
                                exit;

                        $post = $this->getRequest()->getPost();
                        $dbTable = new Banner_Model_Bannerslides();

			if(isset($post['listItem'])){
				foreach ($post['listItem'] as $order => $id) {
					$bean = R::findOne($dbTable::NAME, 'WHERE id = ?', array($id));
					$bean->active = $type;
					$bean->order = $order;
					R::store($bean);
					$updatedRows[$id] = $bean->id;
				}
				if(count($updatedRows) > 0){
					echo Zend_Json::encode(array('result' => 'success', 'msg' => 'Kolejność została zapisana'));
				}else{
					echo Zend_Json::encode(array('result' => 'error', 'msg' => 'Zmiany nie zostały zapisane'));
				}
			}else{
				echo Zend_Json::encode(array('result' => 'error', 'msg' => 'Zostały zapisane'));
			}
				
                        
                }
                exit;
        }

        /**
         * Ajaxowa akcja obsługująca powiększanie i pomniejszanie obrazka 
         */
        public function ajaxModifyImgAction() {
                if ($this->getRequest()->isPost()) {

                        $post = $this->getRequest()->getPost();

                        $post['src'] = $this->removeImgTrigger($post['src']);

                        $current_thumb = PhpThumb_PhpThumbFactory::create(ROOT_PATH . $post['src']);
                        $dimensions = $current_thumb->getCurrentDimensions();

                        switch ($post['act']) {
                                case 'zoom_in':
                                        /* oryginalny obrazek */
                                        $canvas = $thumb = PhpThumb_PhpThumbFactory::create(ROOT_PATH . $post['canvas_src']);
                                        $originalDimensions = $canvas->getCurrentDimensions();
                                        
                                        if ($dimensions['width'] * 1.1 < $originalDimensions['width'] AND $dimensions['height'] * 1.1 < $originalDimensions['height']) {
                                                $thumb->resize($dimensions['width'], $dimensions['height']);
                                                $thumb->resizePercent(110);
                                        }
                                        else {
                                                $thumb->resize($this->_config->imageThumbs->canvas->width, $this->_config->imageThumbs->canvas->height);
                                                $warning = $this->view->translate('Nie można już powiększyć zdjęcia');
                                        }
                                        $filename = '/' . $this->_sliderTmp . 'tmp/' . $post['uniqid'] . '.' . strtolower($thumb->getLowerFormat());
                                        $thumb->save(ROOT_PATH . $filename);
                                        break;

                                case 'zoom_out':
                                        /* oryginalny obrazek */
                                        $thumb = PhpThumb_PhpThumbFactory::create(ROOT_PATH . $post['canvas_src']);

                                        if ($dimensions['width'] * 0.9 > $this->_config->imageThumbs->slide->width AND $dimensions['height'] * 0.9 > $this->_config->imageThumbs->slide->height) {
                                                $thumb->resize($dimensions['width'] * 0.9, $dimensions['height'] * 0.9);
                                        }
                                        else {
                                                $thumb->resize($dimensions['width'], $dimensions['height']);
                                                $warning = $this->view->translate('Nie można już pomniejszyć zdjęcia');
                                        }
                                        $filename = '/' . $this->_sliderTmp . 'tmp/' . $post['uniqid'] . '.' . strtolower($thumb->getLowerFormat());
                                        $thumb->save(ROOT_PATH . $filename);
                                        break;
                        }

                        $response = array('result' => isset($warning) ? 'warning' : 'success',
                                'src' => '/' . $this->_sliderTmp . 'tmp/' . $post['uniqid'] . '.' . strtolower($thumb->getLowerFormat() . '?c=' . uniqid()),
                                'message' => @$warning);

                        echo Zend_Json::encode($response);
                        exit;
                }
        }

        /**
         *
         * @param Zend_Form_Element_File $formFileElement 
         * @param string $destination Miejsce zapisania obrazka
         * @return bool 
         */
        private function saveFormFileElement($formFileElement, $destination, $width, $height) {
                $thumb = PhpThumb_PhpThumbFactory::create($formFileElement->getFileName(), array('correctPermissions' => true));
                $thumb->resize($width, $height);

                return $thumb->save(ROOT_PATH . $destination);
        }

        /**
         * Dołożenie bibliotek js do akcji index 
         */
        private function pushIndexJs() {
                $this->view->headScript()->appendFile(Banner_Module_Module::getInstance()->getAdminJSPath() . 'index.js');
        }

        /**
         * Dokładanie bibliotek jCrop oraz kilku zmiennych potrzebnych do ogsługi cięcia
         * @param RedBean_OODBBean $row 
         */
        private function pushCropJs(RedBean_OODBBean $row) {
                $this->view->headLink()->appendStylesheet(Banner_Module_Module::getInstance()->getAdminCSSPath() . 'jcrop/jquery.Jcrop.css');

                $this->view->headScript()->appendFile(Banner_Module_Module::getInstance()->getAdminJSPath() . 'jquery.Jcrop.min.js')
                        ->appendFile(Banner_Module_Module::getInstance()->getAdminJSPath() . 'crop.js')
                        ->appendScript('imgPath = "' . Banner_Module_Module::getInstance()->getAdminImgPath() . '";
                                                        thumbWidth = ' . $this->_config->imageThumbs->slide->width . ';
                                                        thumbHeight = ' . $this->_config->imageThumbs->slide->height . ';
                                                        uniqid = "' . uniqid() . '";
                                                        canvasSrc = "' . $this->_sliderTmp . self::CANVAS_PREFIX . $row->id . '.' . $row->extension . '";
                                                        lastSliceX = ' . $row->last_slice_x . ';
                                                        lastSliceY = ' . $row->last_slice_y . ';');
        }

        /**
         *      Czyszczenie katalogu z tymczasowymi obrazami, które są tworzone podczas powiększania lub pomniejszania zdjęcia 
         */
        private function clearTmpDirectory() {
		chdir(substr(Banner_Module_Module::getInstance()->getAdminImgPath(), 1) . 'slides/tmp');
		$files = glob('*.*');
                foreach ($files as $file)
                        unlink($file);
        }

        /**
         * Jeśli obrazek był już cięty, to utworzony zostanie tymczasowy obrazek, odpowiadający wielkością temu z ostatniego cięcia, zwrócona zostaje ścieżka do niego
         * @param RedBean_OODBBean $row
         * @return string lokalizacja tymczasowego obrazka 
         */
        private function getCanvas(RedBean_OODBBean  $row) {
                $file = '/' . $this->_sliderTmp . self::CANVAS_PREFIX . $row->id . '.' . $row->extension;
                if (!$row->last_slice_width) {
                        return $file;
                }
                else {
                        $image = PhpThumb_PhpThumbFactory::create(ROOT_PATH . $file);
                        $newFilepath = '/' . $this->_sliderTmp . 'tmp/' . uniqid() . '.' . $row->extension;
                        $image->resize($row->last_slice_width, $row->last_slice_height);
                        $image->save(ROOT_PATH . $newFilepath);
                        return $newFilepath;
                }
        }

        /**
         * Ta funkcja usuwa paramert c, który zapobiega cacheowaniu obrazka przez przeglądarki
         * @param string $filename
         * @return string 
         */
        public function removeImgTrigger($filename) {
                if (strpos($filename, '?')) {
                        return substr($filename, 0, strpos($filename, '?'));
                }
                else {
                        return $filename;
                }
        }

}