<?php
/**
* @version	$Id: stylesheets_item.php 13569 2010-05-18 15:25:01Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class StylesheetsItem extends kDBItem
	{

		function Compile()
		{
			$selector_item =& $this->Application->recallObject('selectors.item', 'selectors', Array('live_table'=>true, 'skip_autoload' => true) );
			$parent_field = $this->Application->getUnitOption($selector_item->Prefix, 'ForeignKey');

			$sql_template = 'SELECT '.$selector_item->IDField.' FROM '.$selector_item->TableName.' WHERE '.$parent_field.' = %s ORDER BY SelectorName ASC';

			$selectors_ids = $this->Conn->GetCol( sprintf($sql_template, $this->GetID() ) );
			$ret = '/* This file is generated automatically. Don\'t edit it manually ! */'."\n\n";

			foreach($selectors_ids as $selector_id)
			{
				$selector_item->Load($selector_id);
				$ret .= $selector_item->CompileStyle()."\n";
			}

			$ret .= $this->GetDBField('AdvancedCSS');

			$compile_ts = adodb_mktime();
			$css_path = WRITEABLE . '/stylesheets/';

			$file_helper =& $this->Application->recallObject('FileHelper');
			/* @var $file_helper FileHelper */

			$file_helper->CheckFolder($css_path);

			$css_file = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$compile_ts.'.css';

			$fp = fopen($css_file,'w');
			if($fp)
			{
				$prev_css = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$this->GetDBField('LastCompiled').'.css';
				if( file_exists($prev_css) ) unlink($prev_css);

				fwrite($fp, $ret);
				fclose($fp);

				$sql = 'UPDATE '.$this->TableName.' SET LastCompiled = '.$compile_ts.' WHERE '.$this->IDField.' = '.$this->GetID();
				$this->Conn->Query($sql);
			}
		}

	}