<?php
defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

class KipModelRules extends JModel
{
	var $_table = null;
	var $_pagination = null;
	var $_filters = array(
		  'order'=> array('name'=>'filter_order', 'def'=>'i.client_id, u1.username', 'type'=>'string')
		, 'order_Dir'=> array('name'=>'filter_order_Dir', 'def'=>'', 'type'=>'word')
		, 'state'=> array('name'=>'filter_state', 'def'=>'', 'type'=>'word')
		, 'search'=> array('name'=>'filter_search', 'def'=>'', 'type'=>'string')
		, 'client_id'=> array('name'=>'filter_client_id', 'def'=>-1, 'type'=>'int')
	);
	
	function &getTable(){
		if ($this->_table == null)
		{
			$this->_table =& JTable::getInstance( 'rules','table');
		}
		return $this->_table;
	}

	function setFilter($name, $value=''){
		global $mainframe, $option;
		if(isset($this->_filters[$name])){
			$this->_filters[$name]['value'] = $value ? $value : $this->_filters[$name]['def'];
			$mainframe->setUserState( $option.'.'.$this->_name.'.'.$this->_filters[$name]['name'],$this->_filters[$name]['value']);  
		}
	}	
	
	function &getFilters(){
		global $mainframe, $option;
		if(!isset($this->_limit)){
			foreach($this->_filters as $k=>$v){
				$this->_filters[$k]['value']=$mainframe->getUserStateFromRequest( $option.'.'.$this->_name.'.'.$v['name'], $v['name'], $v['def'], $v['type']);
			}
			$this->_limit		= $mainframe->getUserStateFromRequest( $option.'.'.$this->_name.'.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
			$this->_limitstart	= $mainframe->getUserStateFromRequest( $option.'.'.$this->_name.'.limitstart', 'limitstart', 0, 'int' );
		}
		return $this->_filters;
	}
	
	function &getItems(){
		global $mainframe;

		if (isset($this->_items)) {
			return $this->_items;
		}
		$this->getFilters();
		
		$where = array();
		
		if ( $this->_filters['state']['value'] ){
			switch( $this->_filters['state']['value']){
				case 'P' :
					$where[] = 'i.published = 1';
				break;
				case 'U' :
					$where[] = 'i.published = 0';
				break;
			}
		}

		$filter_order1=$this->_filters['order']['value'];
		if(strpos($filter_order1, ','))
			$filter_order1 = str_replace(',',' '.$this->_filters['order_Dir']['value'].' ,',$filter_order1);
			
		$orderby = ' ORDER BY '. $filter_order1 .' '. $this->_filters['order_Dir']['value'];

		if ($this->_filters['search']['value']) {
			$where[] =	'(LOWER( i.description ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $this->_filters['search']['value'], true ).'%', false )
			. ' OR LOWER( i.iprange_txt ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $this->_filters['search']['value'], true ).'%', false )
			. ' OR LOWER( u1.username ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $this->_filters['search']['value'], true ).'%', false ).')'				
			;
		}

		if ($this->_filters['client_id']['value'] > -1) {
			$where[] =	'i.client_id = '.$this->_filters['client_id']['value'];
		}
		
		
		$this->_db->setQuery( 'SELECT COUNT(*)'
		. ' FROM #__kip_filters AS i'
		. (count($where) ? ' WHERE '.implode(' AND ',$where) : '')
		);
		$this->_total = $this->_db->loadResult();

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $this->_total, $this->_limitstart, $this->_limit );
		$this->_limitstart = $this->_pagination->limitstart; 
		$this->_limit = $this->_pagination->limit;
		
		$this->_db->setQuery('SELECT i.*, u.name AS editor, (CASE WHEN i.modified > i.created THEN i.modified ELSE i.created END) AS lastupdate, u1.username'
		. ' FROM #__kip_filters AS i'
		. ' LEFT JOIN #__users AS u ON u.id = i.checked_out'
		. ' LEFT JOIN #__users AS u1 ON u1.id = i.userid'
		. (count($where) ? ' WHERE '.implode(' AND ',$where) : '')
		. $orderby
		, $this->_limitstart, $this->_limit );
		//echo $this->_db->getQuery();
		$this->_items = $this->_db->loadObjectList();
		
		return $this->_items;
	}

	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}

	function setItemState( $items, $state )
	{
		if(is_array($items)){
			$row =& $this->getTable();
			foreach ($items as $id){
				$row->load( $id );
				$row->published = $state;
				if (!$row->store()) {
					$this->setError($row->getError());
					return false;
				}
			}
		}

		return true;
	}

	function remove($items){
		$row =& $this->getTable();
		foreach ($items as $id){
			$row->load( $id );
            if(!$row->delete( $id )){
            	$this->setError($row->getError());
            	return false;
            }
		}
		return count($items);
	}

	function checkout($uid = null){
		global $mainframe, $option;
		if (is_null($uid)) {
			$user	=& JFactory::getUser();
			$uid	= $user->get('id');
		}
		$item	=& $this->getItem();
		if($item->id){
			if ( JTable::isCheckedOut($uid, $item->checked_out )){
				$msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The item'), $item->title);
				$mainframe->redirect('index.php?option='.$option.'&view='.$this->getName(), $msg);
			}
			
			if(!$item->checkout($uid, $item->id)) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		return true;
	}

	function checkin($uid = null){
		$id = JRequest::getVar( 'id', 0, '', 'int' );
		$item = & $this->getTable();
		$item->checkin( $id );
		return true;
	}
		
	function store(){
		$this->_db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post	= JRequest::get('post',array());

		if (!$row->bind( $post)) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		
		if (!$row->check()){
			$this->setError($row->getError());
			//echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		
		if (!$row->store()){
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		$row->checkin();

		return true;
	}
	
	function &getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$item =& $this->getTable();

		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		if ($cid[0]) {
			$item->load($cid[0]);
		}
		return $item;
	}
	
}
