<?
/**
 * TKD Admin Controller Wrapper Class.
 *
 * @package		TKDAdmin Controller
 * @author		Muhammad Uzair Khan (Muhammad.Uzair@tradekey.com)
 * @version		1.0
 * @since		Version 1.0 2013
 * @comments	Please think of it as fun :P AND ENJOY
 */
class MY_Controller_Admin extends CI_Controller {
	private static $instance;

	/**
	 * Constructor
	 */
	protected $layout_data = array();
	protected $layout;

	public function __construct() {

		global $config;
		parent::__construct();
	}


	public function index($data = array())
	{
		$this->layout_data['additional_tools'] = array("switch","datatables","jquery-ui-dd");
		$this->layout_data['form_js_files'] = array("advanced-form-components.js","form-component.js");

		$model_name = "model_".$this->router->class;

		$this->load->model($model_name);
		$model_obj = $this->$model_name ;
		$params = $model_obj->pagination_params;
		$records = $model_obj->pagination_query($params);
		$pg_config['order_field'] = $model_obj->get_order_field_name();

		if( is_array($data) && is_array($records['data']) )
			$data = $data + $this->prepare_datatable_ajax($records['data'],$pg_config);
		elseif(is_array($records['data']))
			$data = $this->prepare_datatable_ajax($records['data'],$pg_config);

		$data['model'] = "$model_name";
		$this->load_view("showall" , $data );
	}

	public function add() {

		global $config;
		$class_name = $this->router->class;
		$model_array = $this->_extra_models_add;
		$model_name = 'model_'.$class_name ;
		$model_array[] = $model_name;
		$this->_validation_models_add[] = $model_name;
		
		$this->load->model($model_array);
		$data['form_fields'][$class_name] = $this->$model_name->get_fields();
		if($this->uri_data['id'])
		{

			$where['id'] = $this->uri_data['id'];
			$form_data[$class_name] = $this->$model_name->find_one($where);
			if(count($form_data[$class_name])==0)
			{
				redirect($this->admin_path."index/msgtype/Error/msg/404 - Record not found.", 'refresh');
				exit();
			}
		}
	
		$this->layout_data['additional_tools'] = array("tinymce","js_validator","multi_select","datepicker","switch","dropzone","fileupload");
		$this->layout_data['form_js_files'] = array("jquery.validate.min.js","form-validation-script.js","advanced-form-components.js","form-component.js");
		$user_data = $this->input->post(NULL, true);

		$data['form_data'] = $form_data;
		$data['user_input'] = $user_data['login'];
		$config = $this->config->config;
		
		if($_POST['submit'] && $this->bulk_validate($this->_validation_models_add))
		{
			
			$this->$model_name->set_attributes($_POST[$class_name]);
			$vTypeId = $this->$model_name->save();
			if($vTypeId)
			{
				redirect($this->admin_path."index/msgtype/success/msg/Record updated successfuly.", 'refresh');
			}
			else
			{
				redirect($this->admin_path."index/msgtype/error/msg/Could not save data.", 'refresh');
		 		exit();
			}
			
		}
		
		$this->load_view("_form", $data);

	}

	public function prepare_datatable_ajax($record,$pg_config=array()) {
		
		global $config;
		$class = $this->router->class ;
		$allowed_tags = array("pics_urls");
		$dont_truncate = array();

		if(is_array($record))
		foreach ($record as $row) {
			$table_data = array();
			$itemId =  $row['id'];
			foreach ($row as $field => $value) {

				if(!trim($field) || $field==$pg_config['order_field'])
					continue;
				$value = mysql_real_escape_string($value);
				
				if(!in_array($field, $allowed_tags))
					$value = strip_tags($value);
				
				if(!in_array($field, $dont_truncate))
					$value = truncate($value,256);
				
				$value = stripslashes($value);
			
				$thead[$field] = "{ \"sTitle\": \"" . ucfirst(str_replace("_", " ", $field)) . "\"}";
				if (in_array($field, array("is_discontinued", "status","is_featured"))) {
					$dicon = $value == 1 ? "checked=checked" : "";
					$value = '<div data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\" data-value=\"'.$value.'\" data-field=\"'.$field.'\" class=\"switch switch-square switch-' . $field . '\" tableclass=\"'.$class.'\" data-on-label=\"<i class=icon-ok></i>\" data-off-label=\"<i class=icon-remove></i>\"><input value=\"1\" type=\"checkbox\"' . $dicon . '/></div>';
				}
				$table_data[] .= '"' . ($value) . '"';
			}
			// DELETE Button
			if(!$pg_config['dont_show_delete'])
				$delete_button = '<button class=\"btn_delete_product btn_delete_product btn btn-danger btn-xs\" data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\"  ><i class=\"icon-trash \"></i></button>';
			// EDIT Button
			if(!$pg_config['dont_show_edit'])
				$edit_button = '<a href=\"'.$config['admin_base_url'].$class.'/add/id/'.$itemId.'/\" target=\"_blank\"><button class=\"btn-xs btn btn_edit_product btn-primary data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\" btn-xs\"><i class=\"icon-pencil\"></i></button></a>';
			// ORDER FIELD- HIDDEN
			if($pg_config['order_field'])
				$order_field = '<input type=\"hidden\" class=\"order_field_val\" value=\"'.$row[$pg_config['order_field']].'\" data-item-id=\"'.$itemId.'\">';
			// VIEW BUTTON
			if($pg_config['show_view'])
				$edit_button = '<a href=\"'.$config['admin_base_url'].$class.'/view/id/'.$itemId.'/\" target=\"_blank\"><button class=\"btn-xs btn btn_edit_product btn-primary data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\" btn-xs\"><i class=\"icon-picture\"></i></button></a>';
			$extra_buttons = '' ;
			if(array_filled($this->dt_extra_actions))
			{
				foreach ($this->dt_extra_actions as $btn) {
					$extra_buttons .= sprintf($btn,$itemId) ;
				}
			}
			$table_data[] = '"'.$edit_button . $delete_button.$extra_buttons.'"';
			$tdata[] = "[" . implode(",", $table_data) . "]";
		}
		$action_label = "action";
		$thead[] = "{ \"sTitle\": \"" . ucfirst($action_label) . "\"}";
		
		if(is_array($tdata))
			$data['products_data'] = implode(',', $tdata);
		
		if(is_array($thead))
			$data['products_column'] = "[" . implode(',', $thead) . "]";
		return $data;
	}

	public function paginate()
	{
		$params = array();
		$model = $_GET['model'];
		
		$this->load->model($model);
		$model_obj = $this->$model;

		$params = $this->$model->pagination_params;

		if($_GET['dt_fields'])
			$params['fields'] = $_GET['dt_fields'] ? mysql_real_escape_string($_GET['dt_fields']) : "*";

		if($_GET['iSortCol_0']!==null)
		{
			$sort_type = ($_GET['sSortDir_0'] == "asc") ? "ASC" : "DESC";
			$params['order'] = (intval($_GET['iSortCol_0'])+1) ." ".$sort_type;
		}
		
		$model_obj->_per_page = $model_obj->_per_page ? $model_obj->_per_page : intval($_GET['iDisplayLength']);
		
		$records = $model_obj->pagination_query($params);
		$pg_config = $_GET['pg_config'];
		if(is_array($records['data']))
			$data = $this->prepare_datatable_ajax($records['data'],$pg_config);

		echo '{
				"sEcho": '.$_GET['sEcho'].',
				"iTotalRecords": "'.$records['count'].'",
				"iDisplayLength": '.$model_obj->_per_page.',
				"iTotalDisplayRecords": "'.$records['count'].'",
				"aaData": [
					'.$data['products_data'].'
				]
			}';
	}

	public function prepare_datatable($record) {
		global $config;
		$class = $this->router->class ;
		$allowed_tags = array("pics_urls");
		if(is_array($record))
		foreach ($record as $row) {
			$table_data = array();
			$itemId =  $row['id'];
			foreach ($row as $field => $value) {
			
				$value = mysql_escape_string($value);
				if(!in_array($field, $allowed_tags))
					$value = strip_tags(($value));
				
				$thead[$field] = "{ \"sTitle\": \"" . ucfirst(str_replace("_", " ", $field)) . "\"}";
				if (in_array($field, array("is_discontinued", "status","is_featured"))) {
					$dicon = $value == 1 ? "checked=checked" : "";
					$value = '<div data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\" data-value=\"'.$value.'\" data-field=\"'.$field.'\" class=\"switch switch-square switch-' . $field . '\" tableclass=\"'.$class.'\" data-on-label=\"<i class=icon-ok></i>\" data-off-label=\"<i class=icon-remove></i>\"><input value=\"1\" type=\"checkbox\"' . $dicon . '/></div>';
				}
				$table_data[] .= '"' . ($value) . '"';
			}
			$table_data[] = '"'.'<a href=\"'.$config['admin_base_url'].$class.'/add/id/'.$itemId.'/\" target=\"_blank\"><button class=\"btn btn-primary btn-xs\"><i class=\"icon-pencil\"></i></button></a>'.
							 '<button class=\"btn_delete_product btn_delete_product btn btn-danger btn-xs\" data-model=\"'.$class.'\" data-pk=\"'.$itemId.'\"  ><i class=\"icon-trash \"></i></button>'.'"';
			$tdata[] = "[" . implode(",", $table_data) . "]";
		}
		$action_label = "action";
		$thead[] = "{ \"sTitle\": \"" . ucfirst($action_label) . "\"}";
		
		if(is_array($tdata))
			$data['products_data'] = implode(',', $tdata);
		
		if(is_array($thead))
			$data['products_column'] = "[" . implode(',', $thead) . "]";
		return $data;
	}

	public function update() {
		if(is_array($_POST['params']) && count($_POST['params'])){
			$model = $_POST['params']['model'];
			$pk = $_POST['params']['pk'];
			$val = $_POST['params']['val']==0?1:0;
			$field = $_POST['params']['field'];

			$data[$field] = $val;
			
			if($this->router->class==$model){
				$this->db->where('id', $pk);
				$update = $this->db->update($model,$data); 
				if($update==true)echo 1;
				else echo 0;
			}	
		}
		
	}
	


}
?>