<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * GCB helper class.
 *
 *
 * @package    GCB
 * @author     Gurkan Caner Birer
 * @version		0.6.3
 * @copyright  (c) 2007-2009 GCB
 */
class gcb_Core {

/****************** FORM HELPERS**************/

	/**
	 * Generates an opening HTML form tag.
	 *
	 * @param   string  form action attribute
	 * @return  string
	 */
	public static function open_form($action = NULL, $id="form")
	{
		return form::open($action).'<table id="'.$id.'">';
	}
	
	/**
	 * Generates an closing HTML form tag.
	 *
	 * @param   string  form action attribute
	 * @return  string
	 */
	public static function close_form($action = NULL)
	{
		return form::close().'</table>';
	}
	
	public static function row_input($name, $label="", $value=NULL)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];			
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		$return .= '<td>'.form::input($name, $value, 'class="textbox"');
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		$return .='</td>';
		
		$return .= "</tr>";
		return $return;
	}
	
	public static function input($name, $label="", $value=NULL)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];			
		$return = "";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= form::label($name, $label);
		$return .= form::input($name, $value, 'class="textbox"');
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		return $return;
	}
	public static function row_password($name, $label="", $value=NULL)
	{
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		$return .= '<td>'.form::password($name, $value, 'class="textbox"');
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		
		$return .='</td>';
		$return .= "</tr>";
		return $return;
	}
	public static function password($name, $label="", $value=NULL)
	{
		$return = "";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= form::label($name, $label);
		$return .= form::password($name, $value, 'class="textbox"');
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		
		return $return;
	}
	
	public static function checkbox($name, $label="", $value=NULL, $checked=FALSE)
	{
		if(isset($_POST[$name]))
		{
			$value = $_POST[$name];
			if($value)
				$checked = TRUE;
		}
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		$return .= '<td>'.form::checkbox($name, $value, $checked).'</td>';
		$return .= "</tr>";
		return $return;
	}
	
	public static function textarea($name, $label=NULL, $value=NULL, $editor=FALSE)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];	
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		$return .= '<td>';
		if($editor)
		{
			/*
			//$return .='<script type="text/javascript" src="'.url::base().'js/ckeditor/ckeditor.js"></script>';
			$return .= form::textarea($name, $value);
			$return .='<script type="text/javascript"> var oFCKeditor = new FCKeditor( "'.$name.'"  ) ;';
			$return .= 'oFCKeditor.BasePath	= '.url::base().'js/fckeditor/fckeditor.js;' ;
			$return .= 'oFCKeditor.ReplaceTextarea();</script>';
			*/
			$return .= Editor::factory("fck_article")
				->set_fieldname($name)
				->set_value($value)
				->render(FALSE, TRUE);
		}
		else
			$return .= form::textarea($name, $value);
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		$return .='</td>';
		$return .= "</tr>";
		return $return;
	}
	
	public static function submit($value="")
	{
		if(!$value)
			$value = "submit";
		$value = gcb::lang($value);
		return '<tr><td></td><td align="right">'.form::submit('submit', $value).'</td></tr>';
	}
	
	public static function cities($name="city", $value=NULL,$multi=false,$whole_turkey="")
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];
		$return = "<tr>";
		$cities = array($whole_turkey => $whole_turkey,'Adana' => 'Adana','Adıyaman' => 'Adıyaman','Afyon' => 'Afyon','Aksaray' => 'Aksaray','Amasya' => 'Amasya','Ankara' => 'Ankara','Antalya' => 'Antalya','Ardahan' => 'Ardahan','Artvin' => 'Artvin','Aydın' => 'Aydın','Ağrı' => 'Ağrı','Balıkesir' => 'Balıkesir','Bartın' => 'Bartın','Batman' => 'Batman','Bayburt' => 'Bayburt','Bilecik' => 'Bilecik','Bingöl' => 'Bingöl','Bitlis' => 'Bitlis','Bolu' => 'Bolu','Burdur' => 'Burdur','Bursa' => 'Bursa','Çanakkale' => 'Çanakkale','Çankırı' => 'Çankırı','Çorum' => 'Çorum','Denizli' => 'Denizli','Diyarbakır' => 'Diyarbakır','Düzce' => 'Düzce','Edirne' => 'Edirne','Elazığ' => 'Elazığ','Erzincan' => 'Erzincan','Erzurum' => 'Erzurum','Eskişehir' => 'Eskişehir','Gaziantep' => 'Gaziantep','Giresun' => 'Giresun','Gümüşhane' => 'Gümüşhane','Hakkari' => 'Hakkari','Hatay' => 'Hatay','Isparta' => 'Isparta','Iğdır' => 'Iğdır','İstanbul' => 'İstanbul','İzmir' => 'İzmir','K.Maraş' => 'K.Maraş','Karabük' => 'Karabük','Karaman' => 'Karaman','Kars' => 'Kars','Kastamonu' => 'Kastamonu','Kayseri' => 'Kayseri','Kilis' => 'Kilis','Kocaeli' => 'Kocaeli','Konya' => 'Konya','Kütahya' => 'Kütahya','Kırklareli' => 'Kırklareli','Kırıkkale' => 'Kırıkkale','Kırşehir' => 'Kırşehir','Malatya' => 'Malatya','Manisa' => 'Manisa','Mardin' => 'Mardin','Mersin' => 'Mersin','Muğla' => 'Muğla','Muş' => 'Muş','Nevşehir' => 'Nevşehir','Niğde' => 'Niğde','Ordu' => 'Ordu','Osmaniye' => 'Osmaniye','Rize' => 'Rize','Sakarya' => 'Sakarya','Samsun' => 'Samsun','Siirt' => 'Siirt','Sinop' => 'Sinop','Sivas' => 'Sivas','Şanlıurfa' => 'Şanlıurfa','Şırnak' => 'Şırnak','Tekirdağ' => 'Tekirdağ','Tokat' => 'Tokat','Trabzon' => 'Trabzon','Tunceli' => 'Tunceli','Uşak' => 'Uşak','Van' => 'Van','Yalova' => 'Yalova','Yozgat' => 'Yozgat','Zonguldak' => 'Zonguldak');
		$label = gcb::lang($name).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		if($multi)
			$return .= '<td>'.form::dropdown(array("name" =>$name."[]",
												   "multiple"=>"multiple"), $cities, $value);
		else
			$return .= '<td>'.form::dropdown($name, $cities, $value);
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		$return .='</td>';
		$return .= "</tr>";
		return $return;
	}
	
	public static function dropdown($name, $array, $label=NULL, $value=NULL)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];	
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= '<td>'.form::label($name, $label).'</td>';
		$return .= '<td>'.form::dropdown($name, $array, $value);
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		$return .='</td>';
		$return .= "</tr>";
		return $return;
	}
	public static function multi_list($name, $array, $label=NULL, $selected=NULL)
	{
		$return ="";
		if(isset($_POST[$name]) and !$selected)
			$selected = array_keys($_POST[$name]);
		if(!$label)
		{
			$label = $name;
		}
		if($label != "none")
		{
			$label = gcb::lang($label).':';
			$return = form::label($name, $label);
		}
		
		$return .= form::dropdown(array('name' => $name."[]", 'multiple' => 'multiple'), $array, $selected);
		return $return;
	}
	public static function label($name, $label="", $value=NULL)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];			
		$return = "";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= form::label($name, $label);
		$return .= '<span>'.$value."</span>";
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		return $return;
	}
	
	public static function row_label($name, $label="", $value=NULL)
	{
		if(isset($_POST[$name]) and !$value)
			$value = $_POST[$name];			
		$return = "<tr>";
		if(!$label)
		{
			$label = $name;
		}
		$label = gcb::lang($label).':';
		$return .= "<td>".form::label($name, $label)."</td>";
		$return .= '<td>'.$value;
		if(isset($_POST["errors"][$name]))
			$return .= '<span id="error">'.gcb::lang($_POST["errors"][$name],"error").'</span>';
		else
		{
			$errors = Session::instance()->get('errors');
			if(isset($errors[$name]))
				$return .= '<span id="error">'.gcb::lang($errors[$name],"error").'</span>';
		}
		$return .="</td></tr>";
		return $return;
	}
	/****************** LANGUAGE HELPERS**************/
	public static function lang($text, $file='label')
	{
		if(strpos($text," "))
			return $text;
		$key = $file.'.'.$text;
		$value = Kohana::lang($key);
		if($value == $key)
			$value =  ucwords(inflector::humanize($text));
		return $value;
	}
	
	/****************** GENERAL HELPERS**************/
	public static function show($text=NULL, $id="")
	{
		if(isset($text))
		{
			if($id)
				echo '<div id="'.$id.'">';
			if(is_array($text))
			{
				foreach($text as $item)
				{
					echo $item."<br />";
				}
			}
			else
				echo $text;
			if($id)
				echo '</div>';
		}
	}
	
	public static function err($arr=null)
	{
		if(isset($arr))
		{
			echo '<div id="error">';
			while ($value = current($arr))
			{
				echo "<b>".gcb::lang(key($arr)).":</b> ".gcb::lang($value, "error")."<br />";
				next($arr);
			}
			echo '</div>';
		}
	}
	public static function now()
	{
		return date("Y-m-d H:i:s");
	}
	
	/****************** ORM HELPERS**************/
	public static function fill(& $orm_object, $array="")
	{
		if(!$array)
			$array = $_POST;
		if(!$array)
			return;
		foreach($array as $key => $value)
		{
			if (isset($orm_object->table_columns[$key]))
			{
				$orm_object->$key = $value;
			}
		}
	}
	
	public static function post_fill(& $orm_object)
	{
		$table_columns = $orm_object->table_columns;
		foreach($table_columns as $column_name => $value)
		{
			$_POST[$column_name] = $orm_object->$column_name;
		}
	}
	
	public static function paged(&$orm, $view)
	{
		$page_list = new View($view);
		
		$page_num = Kohana::instance()->input->get('page', 1);
		$per_page = Kohana::config("site.per_page");
		$offset   = ($page_num - 1) * $per_page;
		$pages = $orm->limit($per_page, $offset)
			->find_all();
		$pagination = Pagination::factory(array
		(
			'style' => 'digg',
			'items_per_page' => $per_page,
			'query_string' => 'page',
			'total_items' => $orm->count_last_query(),
		));
		if($pagination->total_pages > 1)
			$page_list->pagination = $pagination;
		else
			$page_list->pagination ="";
		$items_name = inflector::plural($orm->object_name);
		$page_list->$items_name = $pages;
		return $page_list;
	}
	
	public static function option($key, $value=NULL)
	{
		$option = ORM::factory("option",$key);
		if($value)
		{
			$option->value = $value;
			$option->save();
		}
		else
		{
			return $option->value;
		}
	}
	/****************** STRING HELPERS**************/
	public static function to_slug($string)
	{
		$string = utf8::transliterate_to_ascii(utf8::strtolower($string));
		return url::title(str_replace("ı","i",$string));
	}
	/****************** IMAGE HELPERS**************/
	public static function product_image($image, $text=NULL,$alt="")
	{
		$uploads_dir =  Kohana::config("site.product_image_upload_dir_name");
		$fileext = ".".substr(strrchr($image, "."), 1);
		$name = substr($image, 0,-strlen($fileext))."-small".$fileext;
		
		if(!$text)
		{
			$text = html::image($uploads_dir.$name,$alt);
		}
		return html::anchor($uploads_dir.$image,
							$text,
							array('class'=>'show-image',
								  "title"=>$alt));
	}
	public static function product_file_name($image)
	{
		$ret = array();
		$abs_uploads_dir =  Kohana::config("site.product_image_upload_dir");
		$fulldest = "$abs_uploads_dir/$image";
		
		$fileext = ".".substr(strrchr($image, "."), 1);
		$name = gcb::to_slug(substr($image, 0,-strlen($fileext)));
		$image = $name;
		for ($i=1; file_exists($fulldest); $i++)
		{
		  $image = $name.'['.$i.']';
		  $fulldest = "$abs_uploads_dir/$image".$fileext;
		}
		
		$ret[] = $image.$fileext;
		$ret[] = $image."-small".$fileext;
		return $ret;
		
	}
}