<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/***************************************************************************
 *	PROJECT: ZokiSoft Smart Catalog
 *
 *	This program is a commercial software and any kind of using
 *	it must agree to ZokiSoft License Agreement.
 *
 *	This notice may not be removed from the code.
 *
 *	Copyright 2007-2008 ZokiSoft
 *	http://www.zokisoft.com/
 ***************************************************************************/

class Page extends Catalog_Controller
{

	/**
	 *	@desc constractor
	 */
	function Page()
	{

		parent::Catalog_Controller();

		$this->aHeaderVar['catalog_charset'] = $this->config->item('catalog_charset');

		$this->aSystemVar['template_viewer_root'] = $this->config->item('template_module_viewer');
		$this->aSystemVar['template_viewer_current'] = $this->config->item('template_viewer_page');

		$this->aHeaderVar['additional_css'] = '<link href="' . $this->config->item('design_css_url') . 'static.css" rel="stylesheet" type="text/css" />';

	}

    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function index()
	{
	    $this->create();
	}

    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function create( array $aPreFill = array() )
	{
		$aData = array();
        if( !$this->bAdmin )
			redirect();

		$this->aHeaderVar['additional_js'] = $this->_tiny_mce_settings();

		$aData['data']['form'] = array(
			'Id'		=> 0,
			'Lang'		=> $this->aSystemVar['cur_lang'],
			'Title'		=> '',
			'BaseName'	=> '',
			'Content'	=> '',
		);

		foreach ( $aData['data']['form'] as $key => $value )
		{
			if ( !empty($aPreFill[$key]) )
			{
				$aData['data']['form'][$key] = $aPreFill[$key];
			}
		}

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'create', $aData );
	}

    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function edit( $sBaseName )
	{

        if( !$this->bAdmin )
			redirect();

		$aData = array();

		$this->aHeaderVar['additional_js'] = $this->_tiny_mce_settings();

		$sLang = $this->aSystemVar['cur_lang'];

		$this->db->select('`zok_static_content`.*,`zok_static_lang`.`Lang`,`zok_static_lang`.`Title`,`zok_static_lang`.`Content`');
		$this->db->join('`zok_static_lang`','`zok_static_content`.`Id`=`zok_static_lang`.`PageId` AND `Lang`=\''.$sLang.'\'','left');
		$this->db->where('`BaseName`', $sBaseName);
		$oRes = $this->db->get('`zok_static_content`');
		$aRes = $oRes->row_array();

		if ( empty($aRes['Title']) )
		{
			$this->create(array('Id'=>@$aRes['Id'],'BaseName'=>$sBaseName,'Lang'=>$sLang));
			return true;
		}

		$aData['data']['form'] = $aRes;

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'create', $aData );
	    return true;
	}

    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function save()
	{
		if( !$this->bAdmin )
			redirect();

		$this->load->library('validation');

		$rules['PageId']		= 'trim|numeric';
		$rules['Title']			= "trim|required|xss_clean";
		$rules['Content']		= 'required';
		$rules['BaseName']		= 'trim|required|alpha_dash|xss_clean';


		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		if ($this->validation->run() == FALSE)
		{
			$this->create($_POST);
			return true;
		}

// =================================================================================================================
// update
			$iPageId = (int)$this->input->post('PageId');
			$sPageLang = $this->input->post('Lang');

			// define def lang
			foreach ($this->aSystemVar['lang_list'] as $aItem)
				if ( 1 == $aItem['Def'] )
				{
					$sDefLang = $aItem['BaseName'];
					break;
				}


			$aPage = array(
				'BaseName'	=> $this->Catalog_model->GetUniqBaseName($this->input->post('BaseName'), 'zok_static_content', $iPageId),
			);

			// =============================================================================================
			// delete and rebuild files if basename has been changed
			if( !empty($iPageId) )
			{
				$this->db->select('`zok_static_lang`.*,`BaseName`');
				$this->db->join('`zok_static_content`','`zok_static_content`.`Id`=`zok_static_lang`.`PageId`');
				$this->db->where("`PageId`={$iPageId}");
				$rRes = $this->db->get('`zok_static_lang`');

				foreach ( $rRes->result_array() as $aItem )
				{
					if ( $aPage['BaseName'] == $aItem['BaseName'] )
						break;

					if ( $sPageLang != $aItem['Lang'] )
					{
						// delete old file
						if ( $aItem['Lang'] != $sDefLang )
						{
							$aItem['BaseName'] .= '_'.$aItem['Lang'];
							$sNewName = $aPage['BaseName'].'_'.$aItem['Lang'];
						}
						else
							$sNewName = $aPage['BaseName'];

//echo ($this->config->item('base_dir').'views/_page/'.$aItem['BaseName'] . EXT);
						@unlink($this->config->item('base_dir').'views/_page/'.$aItem['BaseName'] . EXT);

						// create new one
						$aItem['BaseName'] = $sNewName;
//print_r($aItem);
						$this->_buildPage($aItem);
					}
				}
			}
			// =============================================================================================

			if( empty($iPageId) )
			{
				$this->db->insert('zok_static_content', $aPage);
				$iPageId = $this->db->insert_id();
			}
			else
			{
                $this->db->where('`Id`', $iPageId);
				$this->db->update('zok_static_content', $aPage);
			}

			$sBaseName = $aPage['BaseName'];

// =================================================================================================================
// =================================================================================================================
// update lang

			$this->db->select('`Id`');
			$this->db->where('`PageId`=\''.$iPageId.'\' AND `Lang`=\''.$sPageLang.'\'');
			$rRes = $this->db->get('`zok_static_lang`');

			$aPage = array();
			$aPage['Title'] = htmlspecialchars(wordwrap( $this->input->post('Title'), 35, ' ', true), ENT_QUOTES, $this->config->item('catalog_charset'));
			$aPage['Content'] = $this->input->post('Content');

			if ( 0 == $rRes->num_rows() )
			{
			// insert
				$aPage['PageId']=$iPageId;
				$aPage['Lang']=$sPageLang;

				$this->db->insert('`zok_static_lang`',$aPage);
			}
			else
			{
			// update
				$aId = $rRes->row_array();
				$this->db->where('`zok_static_lang`.`Id`=\''.$aId['Id'].'\'');
				$this->db->update('`zok_static_lang`', $aPage);
			}

// =================================================================================================================

			// define language
			if ( $sPageLang != $sDefLang )
			{
				$aPage['BaseName'] = $sBaseName.'_'.$sPageLang;
				$sPF = '/lang-'.$sPageLang;
			}
			else
			{
				$aPage['BaseName'] = $sBaseName;
				$sPF = '';
			}

			$this->_buildPage($aPage);

			redirect('info/'.$sBaseName.$sPF);

	}

    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function remove()
	{

	    return;
	}


	function _buildPage($aData)
	{
		$this->load->helper('file');

		$sFileContent = '<?php  if (!defined(\'BASEPATH\')) exit(\'No direct script access allowed\');?>' . "\n";
		$sFileContent .= '<? $this->load->view($this->aSystemVar[\'template_viewer_root\'] . \'_header\'); ?>' . "\n";
		$sFileContent .= '<h1>' . trim($aData['Title']) . '</h1>' . "\n";
		$sFileContent .= $aData['Content'] . "\n";
		$sFileContent .= '<? $this->load->view($this->aSystemVar[\'template_viewer_root\'] . \'_footer\'); ?>';

		write_file( $this->config->item('base_dir') . 'views/_page/' . $aData['BaseName'] . EXT, $sFileContent);

		return true;
	}

   	function _tiny_mce_settings()
	{
		$ret = '
	        <script type="text/javascript" src="' . base_url() . 'system/application/scripts/tiny_mce/tiny_mce.js"></script>
        	<script type="text/javascript">
                // O2k7 skin (silver)
				tinyMCE.init({
					// General options
					mode : "exact",
					elements : "page_content",
					theme : "advanced",
					skin : "o2k7",
					skin_variant : "silver",
					plugins : "safari,table,save,advimage,advlink,insertdatetime,preview,contextmenu,paste,visualchars,xhtmlxtras,inlinepopups",

					// Theme options
					theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
					theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
					theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
					theme_advanced_buttons4 : "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : false,


					// Example content CSS (should be your site CSS)
					content_css : "' . base_url() . 'views/_css/tiny_mce.css",
				});
			</script>
		';
	    return $ret;
	}
}

/* End of file page.php */
/* Location: ./system/application/controllers/page.php */