<?php 
class Application_Model_User extends MyWeb_Model_Database
{

    protected $_storageName = 'User';

    protected $_formClasses = array(
        'insert' => 'userNew',
        'update' => 'userEdit',
        'search' => 'userSearch',
        'login' => 'userLogin',
        'logout' => 'userLogout'
        );

        
        
	public function fetchEntries($dataInput)
    {
    	// databázový adaptér
        $db = $this->getStorage()->getAdapter();
        $select = $this->getFetchEntrySelect($dataInput);
        // načítá údaje
        //echo "<p>".$select."</p>";
        $data = $db->fetchAll($select);
        return $data;
    }
    
    
    public function fetchEntry($id)
    {
        // databázový adaptér
        $db = $this->getStorage()->getAdapter();
        
        // vytvoří SELECT
        $select = $db->select();
        
        if (is_null($id)){
        	$select	->	from(array('U' => 'user'),
        						array('id_user','user_name','user_userName','user_registrationDateTime','user_passwd','State_id_state'))
        
        					->	join(array('S' => 'State'),
        						'U.State_id_state=S.id_state',
        						array('id_state','state_state','NameState_id_NameState','TableDatabase_id_tableDatabase'));
        }else {
        	
        	$select	->	from(array('U' => 'user'),
        				array('id_user','user_name','user_userName','date(user_registrationDateTime)','user_passwd','State_id_state'))
        
        					->	join(array('S' => 'State'),
        						'U.State_id_state=S.id_state',
        						array('id_state','state_state','NameState_id_NameState','TableDatabase_id_tableDatabase'))
        					->	join(array('N' => 'NameState'),
        						'S.NameState_id_NameState=N.id_NameState',
        						array('id_NameState','nameState_name'))
        					->	where('U.id_user = ?',$id);
        }
        
        // načítá údaje
        //echo "<p>".$select."</p>";
        $data['data'] = $db->fetchRow($select);
        return $data;
    }

    
	/**
     * vrati select pro fetchEntry
     * @see MyWeb_Model_Database::getFetchEntrySelect()
     */
    public function getFetchEntrySelect($data){
    	$select = $this->createFetchEntrySelect($data);
    	
    	if (!Zend_Auth::getInstance()->hasIdentity()){
    		$select->where('N.nameState_name <> ?','disabled');
        }else {
        	$acl = MyWeb_Acl::getInstance();
        	$request = Zend_Controller_Front::getInstance()->getRequest();
        	if (!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity()->role_role,strtolower($request->getControllerName()),'disabledData')){
        		$select->where('N.nameState_name <> ?','disabled');
        	}
        }
        
    	return $select;
    }
    
    
    
    /**
     * Vytvori select pro fetch entries
     * 
     * @param unknown_type $data
     */
    public function createFetchEntrySelect($data)
    {
        // databázový adaptér
        $db = $this->getStorage()->getAdapter();
        
        // vytvoří SELECT
        $select = $db	->	select()
        				->	from(array('U' => 'user'),
        					array('id_user','user_name','user_userName','user_registrationDateTime','user_passwd','State_id_state'))
        				->	join(array('S' => 'State'),
        						'U.State_id_state=S.id_state',
        						array('id_state','state_state','NameState_id_NameState','TableDatabase_id_tableDatabase'))
        				->	join(array('N' => 'NameState'),
        						'S.NameState_id_NameState=N.id_NameState',
        						array('id_NameState','nameState_name'))
        				->	join(array('T' => 'TableDatabase'),
        						'S.TableDatabase_id_tableDatabase=T.id_tableDatabase',
        						array('id_tableDatabase','tableDatabase_table'))
        				->	join(array('RH' => 'userhasrole'),
        						'U.id_user=RH.User_id_user',
        						array('User_id_user', 'Role_id_role'))
        				->	join(array('R' => 'role'),
        						'R.id_role=RH.Role_id_role',
        						array('id_role','role_role','State_id_state'));
        				
        						
        $select	->	where('T.tableDatabase_table = ?',$this->_storageName);
        
        // načítá údaje
         if (is_null($data)){
        	//echo "<p>kompletni vypis</p>";
        }else {
        	if (array_key_exists('user_name', $data)){
        		if (!is_null($data['user_name']) && (strcmp($data['user_name'],"none") !== 0) && (strcmp($data['user_name'],"") !== 0)){
        			$select	->	where('U.user_name = ?',$data['user_name']); 
        		}
        	}
        
        	if (array_key_exists('user_userName', $data)){
        		if (!is_null($data['user_userName']) && (strcmp($data['user_userName'],"none") !== 0) && (strcmp($data['user_userName'],"") !== 0)){
        			$select	->	where('U.user_userName = ?',$data['user_userName']); 
        		}
        	}
        
        	if (array_key_exists('user_registrationDateTime', $data)){
        		if (!is_null($data['user_registrationDateTime']) && (strcmp($data['user_registrationDateTime'],"none") !== 0) && (strcmp($data['user_registrationDateTime'],"") !== 0)){
        			$select	->	where('date(U.user_registrationDateTime) = ?',$data['user_registrationDateTime']); 
        		}
        	}
        	
        	if (array_key_exists('State_id_stateValue', $data) && !empty($data['State_id_stateValue'])){
        		if ((array_key_exists('State_id_stateInputName', $data)) && (array_key_exists('State_id_stateInputValue', $data))){
        			if (!empty($data['State_id_stateInputName']) && (strcmp($data['State_id_stateInputName'],"none") !== 0) && (strcmp($data['State_id_stateInputName'],"State_id_state") !== 0)){
        				if (!empty($data['State_id_stateInputValue']) && (strcmp($data['State_id_stateInputValue'],"none") !== 0) || (strcmp($data['State_id_stateInputValue'],"0") !== 0)){
        					$select	->	where('U.State_id_state = ?',$data['State_id_stateInputValue']);
        				}
        			}
        		}
        		$select	->	where('N.nameState_name = ?',$data['State_id_stateValue']);
        	}
        	
        	if (array_key_exists('Role_id_roleValue', $data) && !empty($data['Role_id_roleValue'])){
        		if ((array_key_exists('Role_id_roleInputName', $data)) && (array_key_exists('Role_id_roleInputValue', $data))){
        			if (!empty($data['Role_id_roleInputName']) && (strcmp($data['Role_id_roleInputName'],"none") !== 0) && (strcmp($data['Role_id_roleInputName'],"Role_id_role") !== 0)){
        				if (!empty($data['Role_id_roleInputValue']) && (strcmp($data['Role_id_roleInputValue'],"none") !== 0) || (strcmp($data['Role_id_roleInputValue'],"0") !== 0)){
        					$select	->	where('R.id_role = ?',$data['Role_id_roleInputValue']);
        				}
        			}
        		}
        		$select	->	where('R.role_role = ?',$data['Role_id_roleValue']);
        	}
        
        }
        // načítá údaje
        //echo "<p>".$select."</p>";
        return $select;
    }
    
    
    
    /**
     * ulozani zaznamu do tabulky vazebni pro M:N
     * @see MyWeb_Model_Database::_postInsert()
     */
    protected function _postInsert($data)
    {
    	try {
    		
            $modelRole = $this->loadModel('UserHasRole');
            $primaryKeyMN = $modelRole->getStorage()->info('primary');
            $primaryKey = $this->getStorage()->info('primary');
            
            foreach ($primaryKeyMN as $key => $value){
            	if (!array_key_exists($value, $data)){
            		$data[$primaryKeyMN[$key]] = $data[current($primaryKey)];
            	}
            }
            
            $row = $modelRole->getStorage()->createRow($data);
            $id = $row->save();
        
    	} catch (Zend_Db_Exception $e) {
            // vyvolá vlastní výjimku
            require_once 'MyWeb/Model/Exception.php';
            throw new MyWeb_Model_Exception('Vložení nebylo úspěšné');
        }
    }


}
