<?php
/**
 * This is a 301 redirects
 *@author Pavel Savchuk
 */

class Backend_RedirectController extends RCMS_Core_BaseController {

	protected $_websitePath;

	protected $_websiteUrl;

	public function init() {
		parent::init();
		$this->_websitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
		$this->_websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$this->checkLogin();
		$this->_model = new Default_Model_RedirectModel();
		$this->_cache->clean('all');
	}
	/**
	 * @method init data for manage 301 redirects form
	 *
	 *@return void
	 */
	public function initDataForRedirectForm() {
		$draftCategoryId = $this->_model->selectDraftCategoryId();
		
		$redirectForm =  new RCMS_Form_RedirectForm();
		//$actionsArray = array("With selected"=>"With selected","Delete"=>"Delete");
		$pagesArray = $this->_model->selectPagesUrl();
		foreach ($pagesArray as $key => $url){
			if($draftCategoryId) {
				$parentCategoryId = $this->_model->getParentCategory($key);
				if($parentCategoryId == $draftCategoryId) {
					unset($pagesArray[$key]);
					continue;
				}
			}
		}

		foreach ($pagesArray as &$page){
			if(urldecode($page)!=$page){
				$page = urldecode($page);
			}
		}


		$redirectForm->getElement('pages')->setMultiOptions($pagesArray);
		//$redirectForm->getElement('rediractions')->setMultiOptions($actionsArray);

		$redirectForm->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/redirect.phtml'))
		));
		return $redirectForm;
	}

	/**
	 * @method divides string on parts of the determined length
	 *@param string $string
	 *@param integer $length
	 *@return string
	 */
	public function divideStringOnParts($string, $length=50) {
		/*$result ="";
		$partsCount = (int)(strlen($string)/$length);
		for($i=0;$i<$partsCount+1;$i++) {
			$result .= substr($string,($i*$length),$i+$length)."<br>";
			//$result .= substr($string,($i*$length),$i+$length)." ";
		}
		$end = sizeof($result)-6;
		$result = substr($result, 0,$end);
		return $result;*/
		return $string;

	}

/**
    * @method manages redirect
	 *@return void
	 */
	public function manageredirectAction() {

		//configurate settings variables from config file
		$this->_helper->getHelper('layout')->disableLayout();
		$redirectForm = $this->initDataForRedirectForm();
		$redirectsObjectsArray = $this->_model->getAllRedirects();
		
		foreach ($redirectsObjectsArray as &$redirectObj) {
			$redirectObj->url = $this->getCorrectUrl($redirectObj->url);
			$redirectObj->new_url = $this->getCorrectUrl($redirectObj->new_url);
			$redirectObj->original_old_url = $this->getCorrectUrl($redirectObj->original_old_url);
			}


		foreach ($redirectsObjectsArray as &$redirectObj) {
			if(isset($redirectObj->original_old_url) &&  trim($redirectObj->original_old_url) != '') {
				/* $tmp = explode(".", $redirectObj->original_old_url);
				 $size = sizeof($tmp);

				 if(isset($tmp[$size-1]) && $tmp[$size-1]!="html")
				 {
					$redirectObj->original_old_url = $redirectObj->original_old_url.".html";
				 }*/
				$redirectObj->original_old_url = $this->divideStringOnParts($redirectObj->original_old_url);
			}
			else {
				$orOldUri = $redirectObj->url;
				$tmp = explode(".", $orOldUri);
				if(!isset($tmp[1])) {
					$orOldUri = $orOldUri.".html";
				}
				$orOldUri = $this->getWebSiteUrl().$orOldUri;
				$this->_model->updateOriginalOldUrl($redirectObj->id_page,$orOldUri);
				$redirectObj->original_old_url = $this->divideStringOnParts($orOldUri);
			}

				$tmp  =  strstr($redirectObj->new_url, "http://");
				if($tmp!=false){
					$redirectObj->new_url  = $this->divideStringOnParts($redirectObj->new_url);
				}else{
					$redirectObj->new_url  = $this->divideStringOnParts($this->_websiteUrl.$redirectObj->new_url.'.html');
				}
				//$redirectObj->new_url = $this->divideStringOnParts($this->_websiteUrl.$redirectObj->new_url.'.html');
			

		}
		//assing form to template
		$this->view->redirectsObjectsArray = $redirectsObjectsArray;
		$this->view->websiteUrl = $this->_websiteUrl;
		$this->view->form  =  $redirectForm;
		//if request is POST and everything is valid
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


public function getCorrectUrl($url)
{
	if(urldecode($url)!=$url)
			{
				$url = urldecode(urldecode($url));
			}
	return $url;

}

	/**
     * @method process errors for 301 redirect form
     * @param array $array
	 *@return void
	 */
	public function processErrors($array) {
		$messages = array();
		$htmlUl = "";
		foreach ($array as $key => $value) {
			switch ($key) {
				case 'adminEmail':
					if(isset($value['regexNotMatch']))
						$messages[]="Admin Email field can only contain letters,digits, '@', '.' and '-' .";
					break;

				case 'imgSmall':
					if(isset($value['regexNotMatch']))
						$messages[]="Image Small size field can only contain digits.";
					break;

				case 'imgMedium':
					$messages[]="Image Medium size field can only contain digits.";
					break;

				case 'imgLarge':
					if(isset($value['regexNotMatch']))
						$messages[]="Image Large size field can only contain digits.";
					break;

				case 'smtpHost':
					if(isset($value['regexNotMatch']))
						$messages[]="Smtp Host field can only contain letters,digits, '.' and '-' .";
					break;

				case 'smtpLogin':
					if(isset($value['regexNotMatch']))
						$messages[]="Smtp Login field can only contain letters,digits, '.' and '-' .";
					break;

				case 'imgMaxWidth':
					if(isset($value['regexNotMatch']))
						$messages[]="Image Max Width field can only contain digits.";
					break;

				case 'videoWidth':
					if(isset($value['regexNotMatch']))
						$messages[]="Video Width size field can only contain digits.";
					break;

				case 'videoHeight':
					if(isset($value['regexNotMatch']))
						$messages[]="Video Height size field can only contain digits.";
					break;
			}
		}

		if(!empty($messages)) {
			$htmlUl = "<ul>";
			foreach ($messages as $message) {
				$htmlUl .= "<li>".$message."</li>";
			}
			$htmlUl .= "<ul>";
			return $htmlUl;
		}
		return null;
	}
}


