<?php

class DocumentsController extends Zend_Controller_Action {

	public function init() {
		$information = new Zend_Session_Namespace('information');	
		if( Lib_Permission::CheckPermission('documents') != true ){
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$admin = new Zend_Session_Namespace('admin');
		if( $admin->admin_auth != true ){
			$this->_helper->redirector('index','login');
		}			
	}	
	
	
	public function indexAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrdocuments = new Zend_Session_Namespace('filtrdocuments');
		$db = Zend_Registry::get('db');
		
		if( !isset($filtrdocuments->documents_sort) ){
			$filtrdocuments->documents_sort = 'asc';
		}

		if( !isset($filtrdocuments->documents_sortfield) ){
			$filtrdocuments->documents_sortfield = 'documents.documents_data';
		}
		
		/* konfiguracja sortowania */
		
		$sort = array(
			'asc' => @LANG_sortdoc_asc, 
			'desc' => @LANG_sortdoc_desc
		);
		$this->view->sortdoc = $sort;
		
		$sortfield = array(
			'documents.documents_data' => @LANG_documents_list_data, 
			'client.client_name' => @LANG_documents_list_clientname, 
			'documents.documents_nr' => @LANG_documents_list_docnr, 
			'project.project_name' => @LANG_project_list_name, 
			'company.company_name' => @LANG_company_list_name, 
			'documents.documents_name' => @LANG_documents_list_name, 
			'documents.documents_checkdate' => @LANG_documents_list_checkdate
		);
		$this->view->sortdocfield = $sortfield;
		
		$datafield = array(
			'documents.documents_data' => @LANG_documents_list_data, 
			'documents.documents_checkdate' => @LANG_documents_list_checkdate, 
			'documents.documents_ins' => @LANG_documents_list_ins, 
			'documents.documents_cp' => @LANG_documents_cp
		);
		$this->view->sortdatafield = $datafield;
		
		/* konfiguracja sortowania - koniec */
		
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
			
		$this->view->admin_id = $admin->admin_id;
		
		if( $information->openDocumentsError ){
			$this->view->openDocumentsError = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addDocumentsSuccess ){
			$this->view->addDocumentsSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->removeSuccess ){
			$this->view->removeSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}	
		
		if( $information->addFiltrCompanySuccess ){
			$this->view->addFiltrCompanySuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrCompanyRemove ){
			$this->view->addFiltrCompanyRemove = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrSortSuccess ){
			$this->view->addFiltrSortSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrFiltrDataSuccess ){
			$this->view->addFiltrFiltrDataSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrStatusSuccess ){
			$this->view->addFiltrStatusSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrStatusRemove ){
			$this->view->addFiltrStatusRemove = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		
		
		
		
		
		
		
		
		if( isset($v['filtrLimit']) ){
			$filtrdocuments->limit = $v['filtrLimit'];
			$this->_helper->redirector('index','documents');	
		}
		
		
		if( isset($vPost['gotHidden']) ){
			$filtrdocuments->filtrGot = ($filtrdocuments->filtrGot+1)%2;
			$this->_helper->redirector('index','documents');	
		}
		
		if( isset($filtrdocuments->filtrGot) ){
			$this->view->filtrGot =  $filtrdocuments->filtrGot;
		}else{
			$filtrdocuments->filtrGot = 0;
			$this->view->filtrGot =  $filtrdocuments->filtrGot;
		}
		
		
		
		if( isset($vPost['filtrProjectSort']) OR isset($vPost['filtrProjectSortName']) ){
			$filtrdocuments->documents_sort = $vPost['filtrProjectSort'];
			$filtrdocuments->documents_sortfield = $vPost['filtrProjectSortName'];
			$information->addFiltrSortSuccess = true;
			$this->_helper->redirector('index','documents');	
		}
		
		
		if( isset($vPost['filtrAdmin']) ){
			if( $vPost['filtrAdmin'] != 'all' ){
				$filtrdocuments->admin_id = $vPost['filtrAdmin'];
				$information->addFiltrCompanySuccess = true;
			}else{
				unset($filtrdocuments->admin_id);
				$information->addFiltrCompanyRemove = true;
			}
			$this->_helper->redirector('index','documents');	
		}
		
		$searchAdmin = null;
		if( $filtrdocuments->admin_id ){
			$this->view->filtr_admin_id =  $filtrdocuments->admin_id;
			$searchAdmin = 'documents.admin_id='.$filtrdocuments->admin_id;
		}
		
		
		if( $vPost['filtrCompanyRemove'] == 1 ){
			unset($filtrdocuments->project_id);
			unset($filtrdocuments->company_id);
		
			$information->addFiltrCompanySuccess = true;
			$this->_helper->redirector('index','documents');
		}
		
		if( count($vPost['filtrCompany']) > 0 ){
			unset($filtrdocuments->project_id);
			unset($filtrdocuments->company_id);
			foreach( $vPost['filtrCompany'] as $filtrCompanyKey => $filtrCompanyVal ){
				$filtrdocuments->company_id[$filtrCompanyVal] = $filtrCompanyVal;
			}
			$information->addFiltrCompanySuccess = true;
		/*	}else{
				unset($filtrdocuments->company_id);
				$information->addFiltrCompanyRemove = true;
			}*/
			$this->_helper->redirector('index','documents');	
		}elseif( $vPost['filtrCompanySearch'] == 1 ){
			unset($filtrdocuments->project_id);
			unset($filtrdocuments->company_id);
		
			$information->addFiltrCompanySuccess = true;
			$this->_helper->redirector('index','documents');
		}
		
		$search = null;
		if( count($filtrdocuments->company_id) > 0  ){
				$this->view->filtr_company_id =  $filtrdocuments->company_id;
				$search = '';
				foreach( $filtrdocuments->company_id as $filtrCompanyKey => $filtrCompanyVal ){
					if( $search == '' ) $search = 'company.company_id='.$filtrCompanyVal;
					else $search =  $search.' OR company.company_id='.$filtrCompanyVal;
				}
				if( $search != '' ) $search = '('.$search.')';
				$searchCom = str_replace('company.','',$search);
		}
		
		
		if( isset($vPost['filtrProject']) ){
			if( $vPost['filtrProject'] != 'all' ){
				$filtrdocuments->project_id = $vPost['filtrProject'];
				$information->addFiltrCompanySuccess = true;
			}else{
				unset($filtrdocuments->project_id);
				$information->addFiltrCompanyRemove = true;
			}
			$this->_helper->redirector('index','documents');	
		}
		
		$searchProjectId = null;
		if( $filtrdocuments->project_id ){
			$this->view->filtr_project_id =  $filtrdocuments->project_id;		
		//	$filtrdocuments->company_id = Lib_Project::CompanyId($filtrdocuments->project_id);
		//	$this->view->filtr_company_id = $filtrdocuments->company_id;
			$searchProjectId = 'documents.project_id='.$filtrdocuments->project_id;
		}
		
	
		
		
		
		if( isset($vPost['filtrStatus']) ){
			if( $vPost['filtrStatus'] != 'all' ){
				$filtrdocuments->status[$vPost['filtrStatusField']] = $vPost['filtrStatus'];
				$information->addFiltrStatusSuccess = true;
			}else{
				unset($filtrdocuments->status[$vPost['filtrStatusField']]);
				$information->addFiltrStatusRemove = true;
			}
			$this->_helper->redirector('index','documents');	
		}
		
		$searchDocumentStatus = NULL;
		if( $filtrdocuments->status ){
			$i = 0;
			foreach( $filtrdocuments->status as $key => $val ){
				$this->view->$key = $val;
				$i++;
				$val2 = $val-1;
				
				if( $key == 'documents_prepared' ){
					if( $i == 1 ){
						$searchDocumentStatus = '( client.client_activ_prepared_documents = 1 AND documents.'.$key.'='.$val2.' )';
					}else{
						$searchDocumentStatus = $searchDocumentStatus.' AND ( client.client_activ_prepared_documents = 1 AND documents.'.$key.'='.$val2.' )';
					}
				}else{
					if( $i == 1 ){
						$searchDocumentStatus = 'documents.'.$key.'='.$val2;
					}else{
						$searchDocumentStatus = $searchDocumentStatus.' AND documents.'.$key.'='.$val2;
					}				
				}
				
			}					
		}
		
		
		// filtr nazwa dokumentu - poczatek
		if( isset($vPost['removeDocumentName']) ){
			unset($filtrdocuments->documents_name);
			$this->_helper->redirector('index','documents');	
		}
		if( isset($vPost['filtrDocumentName']) ){
			$filtrdocuments->documents_name = $vPost['filtrDocumentName'];
			$information->addFiltrDocumentNameSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->documents_name ){
			$this->view->filtr_documents_name =  $filtrdocuments->documents_name;
			$searchDocumentName = "documents_name LIKE '%".$filtrdocuments->documents_name."%'";
		}
		if( !isset($searchDocumentName) ){
			$searchDocumentName = null;
		}
		// filtr nazwa dokumentu - poczatek
		// ==========================================================
		
		
		// filtr nr rejestracyjny - poczatek
		if( isset($vPost['removeCarNr']) ){
			unset($filtrdocuments->documents_car_id);
			$this->_helper->redirector('index','documents');	
		}
		if( isset($vPost['filtrCarNr']) ){
			$filtrdocuments->documents_car_id = $vPost['filtrCarNr'];
			$information->addFiltrCarNrSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->documents_car_id ){
			$this->view->documents_car_id =  $filtrdocuments->documents_car_id;
			$searchCarNr = "car_id = ".$filtrdocuments->documents_car_id."";
		}
		if( !isset($searchCarNr) ){
			$searchCarNr = null;
		}
		// filtr nr rejestracyjny - poczatek
		// ==========================================================
		
		
		// filtr nazwa klienta - poczatek
		if( isset($vPost['removeClientName']) ){
			unset($filtrdocuments->documents_client);
			$this->_helper->redirector('index','documents');	
		}
		if( isset($vPost['filtrClientName']) ){
			$filtrdocuments->documents_client = $vPost['filtrClientName'];
			$information->addFiltrClientNameSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->documents_client ){
			$this->view->filtr_documents_client =  $filtrdocuments->documents_client;
			$searchClientName = "client_name LIKE '".str_replace("*","%",$filtrdocuments->documents_client)."'";
		}
		if( !isset($searchClientName) ){
			$searchClientName = null;
		}
		// filtr nazwa klienta - poczatek
		// ==========================================================
		
		
		// filtr nazwa projektu - poczatek
		if( isset($vPost['removeProjectName']) ){
			unset($filtrdocuments->filtr_documents_project);
			$this->_helper->redirector('index','documents');	
		}
		if( isset($vPost['filtrProjectName']) ){
			$filtrdocuments->filtr_documents_project = $vPost['filtrProjectName'];
			$information->addFiltrProjectNameSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->filtr_documents_project ){
			$this->view->filtr_documents_project =  $filtrdocuments->filtr_documents_project;
			$searchProjectName = "project_name LIKE '".str_replace("*","%",$filtrdocuments->filtr_documents_project)."'";
		}
		if( !isset($searchProjectName) ){
			$searchProjectName = null;
		}
		// filtr nazwa projektu - poczatek
		// ==========================================================
		
		// filtr numer dokumentu - poczatek
		if( isset($vPost['removeDocNr']) ){
			unset($filtrdocuments->documents_nr);
			$this->_helper->redirector('index','documents');	
		}
		if( isset($vPost['filtrDocNr']) ){
			$filtrdocuments->documents_nr = $vPost['filtrDocNr'];
			$information->addFiltrDocNrSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->documents_nr ){
			$this->view->filtr_documents_numer =  $filtrdocuments->documents_nr;
			$searchDocNr = "documents_nr LIKE '".str_replace("*","%",$filtrdocuments->documents_nr)."'";
		}
		if( !isset($searchDocNr) ){
			$searchDocNr = null;
		}
		
		// filtr numer dokumentu koniec
		// ==========================================================
		
		
		$searchFiltrData = '';
		if( isset($vPost['removeDate']) ){		
			unset($filtrdocuments->filtr_documents_filtr_data_field);
			unset($filtrdocuments->filtr_documents_filtr_data_1);
			unset($filtrdocuments->filtr_documents_filtr_data_2);
			$information->addFiltrFiltrDataSuccess = true;
			$this->_helper->redirector('index','documents');
		}
		if( isset($vPost['filtr_documents_filtr_data_field']) ){
		//	var_dump($vPost['filtr_documents_filtr_data_field']);
		//	var_dump($vPost['filtr_documents_filtr_data_1']);
		//	var_dump($vPost['filtr_documents_filtr_data_2']);
			$filtrdocuments->filtr_documents_filtr_data_field = $vPost['filtr_documents_filtr_data_field'];
			$filtrdocuments->filtr_documents_filtr_data_1 = $vPost['filtr_documents_filtr_data_1'];
			$filtrdocuments->filtr_documents_filtr_data_2 = $vPost['filtr_documents_filtr_data_2'];
			$information->addFiltrFiltrDataSuccess = true;
			$this->_helper->redirector('index','documents');	
		}		
		if( $filtrdocuments->filtr_documents_filtr_data_field ){
			$this->view->filtr_documents_filtr_data_field = $filtrdocuments->filtr_documents_filtr_data_field;
			$this->view->filtr_documents_filtr_data_1 = $filtrdocuments->filtr_documents_filtr_data_1;
			$this->view->filtr_documents_filtr_data_2 = $filtrdocuments->filtr_documents_filtr_data_2;
			
			if( $filtrdocuments->filtr_documents_filtr_data_field == 'all' ){
			
			
				foreach($datafield as $key => $val){
			
					if( $searchFiltrData == '' ) $sep = '';
					else $sep = ' OR ';
					
					if( $filtrdocuments->filtr_documents_filtr_data_1 AND !$filtrdocuments->filtr_documents_filtr_data_2 ) $searchFiltrData = $searchFiltrData.$sep.$key." >= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_1,"d-m-Y","Y-m-d")."'";			
					if( !$filtrdocuments->filtr_documents_filtr_data_1 AND $filtrdocuments->filtr_documents_filtr_data_2 ) $searchFiltrData = $searchFiltrData.$sep.$key." <= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_2,"d-m-Y","Y-m-d")."'";			
					if( $filtrdocuments->filtr_documents_filtr_data_1 AND $filtrdocuments->filtr_documents_filtr_data_2 ) $searchFiltrData = $searchFiltrData.$sep." (".$key." >= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_1,"d-m-Y","Y-m-d")."' AND ".$key." <= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_2,"d-m-Y","Y-m-d")."') ";
				
				}
			
			
			}else{
			
				if( $filtrdocuments->filtr_documents_filtr_data_1 ) $searchFiltrData = $filtrdocuments->filtr_documents_filtr_data_field." >= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_1,"d-m-Y","Y-m-d")."'";			
				if( $filtrdocuments->filtr_documents_filtr_data_2 ) $searchFiltrData = $filtrdocuments->filtr_documents_filtr_data_field." <= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_2,"d-m-Y","Y-m-d")."'";			
				if( $filtrdocuments->filtr_documents_filtr_data_1 AND $filtrdocuments->filtr_documents_filtr_data_2 ) $searchFiltrData = "(".$filtrdocuments->filtr_documents_filtr_data_field." >= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_1,"d-m-Y","Y-m-d")."' AND ".$filtrdocuments->filtr_documents_filtr_data_field." <= '".Lib_Date::convertDate($filtrdocuments->filtr_documents_filtr_data_2,"d-m-Y","Y-m-d")."')";
			
			}
			
		}
		//echo$searchFiltrData;
		
		$searchFiltrDataGot = '';
		if( $filtrdocuments->filtrGot != 1 ){
			$searchFiltrDataGot = 'project.project_status = 0';		
		}
		
		if( !$filtrdocuments->limit ){
			$filtrdocuments->limit = 10;
		}
		
		if( !isset($search) ){
			$search = null;
		}

		
		$this->view->filtrLimit =  $filtrdocuments->limit;
		$limit = $filtrdocuments->limit;
		$limitpage = 10;

		$page = $this->_request->getParams();
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
		
		$p = ($page-1)*$limit;			

		$select = $db->select();
		$select->from('documents',array('COUNT(documents.documents_id) as count', 'documents.documents_id'))
			->join('project', 'documents.project_id = project.project_id')
			->join('company', 'company.company_id = project.company_id')
			->join('client', 'client.client_id = documents.client_id')
			->joinLeft('documents_car', 'documents_car.documents_id = documents.documents_id', array('car_id'))
		;
		
		$select->where(Lib_Permission::setPermissionCompanySQL());
		$select->where(Lib_Permission::setPermissionProjectSQL());
		if( $search != null ) $select->where($search);
		if( $searchProjectId != null ) $select->where($searchProjectId);
		if( $searchDocumentName != null ) $select->where($searchDocumentName);
		if( $searchClientName != null ) $select->where($searchClientName);
		if( $searchProjectName != null ) $select->where($searchProjectName);
		if( $searchDocNr != null ) $select->where($searchDocNr);
		if( $searchDocumentStatus != null ) $select->where($searchDocumentStatus);
		if( $searchFiltrData != '' ) $select->where($searchFiltrData);
		if( $searchFiltrDataGot != '' ) $select->where($searchFiltrDataGot);
		if( $searchAdmin != null ) $select->where($searchAdmin);
		if( $searchCarNr != null ) $select->where($searchCarNr);
		$select->order(array($filtrdocuments->documents_sortfield.' '.$filtrdocuments->documents_sort));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];
		
//,array("documents_currency_id" =>"documents.currency_id")

		$select = $db->select();
		$select->from('documents',array('*', 'documents.currency_id AS documents_currency_id'))
			->join('project', 'documents.project_id = project.project_id')
			->join('company', 'company.company_id = project.company_id')
			->join('client', 'client.client_id = documents.client_id')
			->joinLeft('documents_car', 'documents_car.documents_id = documents.documents_id', array('car_id'))
		;
		
		$select->where(Lib_Permission::setPermissionCompanySQL());
		$select->where(Lib_Permission::setPermissionProjectSQL());
		if( $search != null ) $select->where($search);
		if( $searchProjectId != null ) $select->where($searchProjectId);
		if( $searchDocumentName != null ) $select->where($searchDocumentName);
		if( $searchClientName != null ) $select->where($searchClientName);
		if( $searchProjectName != null ) $select->where($searchProjectName);
		if( $searchDocNr != null ) $select->where($searchDocNr);
		if( $searchDocumentStatus != null ) $select->where($searchDocumentStatus);
		if( $searchFiltrData != '' ) $select->where($searchFiltrData);
		if( $searchFiltrDataGot != '' ) $select->where($searchFiltrDataGot);
		if( $searchAdmin != null ) $select->where($searchAdmin);
		if( $searchCarNr != null ) $select->where($searchCarNr);
		$select->order(array($filtrdocuments->documents_sortfield.' '.$filtrdocuments->documents_sort))->limit($limit,$p);  
	//	var_dump($select);die();
		
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$this->view->dataTable = $data;		
	//	echo $select;
		
		$Lib_Page = new Lib_Page();
		$Lib_Page->setLimit( $limit );
		$Lib_Page->setLimitPage( $limitpage );
		$Lib_Page->setMax( $dataCount );
		$Lib_Page->setActualId( $page );
		$Lib_Page->setController('documents');
		$Lib_Page->setAction('index');
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;	
		
		$Company = new Company();
		$data = $Company->fetchAll(Lib_Permission::setPermissionCompanySQL(), " company_name ASC "); 		
		if( count($data) > 0 ) $this->view->dataTableCompany = $data;
		
		$Project = new Project();
		$searchProject = Lib_Permission::setPermissionProjectSQL();
		if( count($filtrdocuments->company_id) > 0 ) $searchProject = $searchProject.' AND '.$searchCom;
		
		if( $filtrdocuments->filtrGot != 1 ){
			$searchProject = $searchProject.' AND project_status = 0';		
		}
		
		$data = $Project->fetchAll($searchProject, " project_name ASC "); 		
		if( count($data) > 0 ) $this->view->dataTableProject = $data;
		
		
		
		
			
		$Admin = new Admin();		
		$data = $Admin->fetchAll(null , array('admin_secondname ASC','admin_firstname ASC')); 		
		$this->view->dataTableAdmin = $data;	
		
		
		
		$this->view->documents_sort =  $filtrdocuments->documents_sort;
		$this->view->documents_sortfield =  $filtrdocuments->documents_sortfield;
		$this->view->last_open_document =  $filtrdocuments->last_open_document;
		
		
		$dataCarDB = $db->query("SELECT * FROM `car` ORDER BY car_nr ASC")->fetchAll();
		$this->view->dataTableCar = $dataCarDB;	

		
		$Currency = new Currency();	
		$dataCurrency = $Currency->fetchAll(); 

		$dataCurrencyArray = array();
		foreach( $dataCurrency as $key => $val ){
			$dataCurrencyArray[$val['currency_id']] = $val['currency_short'];
		}
		
		$this->view->dataTableCurrency = $dataCurrencyArray;	
	}

	
	
	public function checkdocumentnrAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrproject = new Zend_Session_Namespace('filtrproject');
		
		$Documents = new Documents();		
		
		$v = $this->_request->getPost();
		
		$select = $Documents->select();
		$select->where('documents_nr = ?', $v['documents_nr']);	
		$row = $Documents->fetchRow($select);
		
		if( isset($row) ){
			echo @LANG_documents_nr_exist;
		}
		
        $this->_helper->viewRenderer->setNoRender();
	}

	
	
	public function documentsfiltrresetAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrdocuments = new Zend_Session_Namespace('filtrdocuments');

		$fLimit = $filtrdocuments->limit;
		
		Zend_Session::namespaceUnset('information');
		Zend_Session::namespaceUnset('filtrdocuments');
		
		$filtrdocuments->limit = $fLimit;
		$filtrdocuments->filtrGot = 1;
		
		$this->_helper->redirector('index','documents');	
			
        $this->_helper->viewRenderer->setNoRender();
	}
	
	
	public function addAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrproject = new Zend_Session_Namespace('filtrproject');
		
		$Project = new Project();
		$Company = new Company();	
		$Client = new Client();	
		$Documents = new Documents();		
		$DocumentsArchive = new DocumentsArchive();	
		$Currency = new Currency();	
		
		$v = $this->_request->getPost();
		
		if( isset($v['admin_adddocuments']) ){
			if( Lib_Permission::getPermissionProject( $v['project_id'] ) != 1 ){
				$information->permissionError = true;
				$this->_helper->redirector('index','index');		
			}
		
			$upload_path = "documents/";
			$filename_name = $admin->admin_id.'_'.$v['project_id'].'_'.hash('sha256',$admin->admin_id.time().rand(0,100000));
			// "C:\\inetpub\\wwwroot\\dm.plw-bau.de\\".
			move_uploaded_file($_FILES["documents_file"]["tmp_name"], $upload_path.$filename_name);
		
		/*	if( !$v['documents_data'] ) $v['documents_data'] = '00-00-0000';
			if( !$v['documents_cp'] ) $v['documents_cp'] = '00-00-0000';
			if( !$v['documents_checkdate'] ) $v['documents_checkdate'] = '00-00-0000';
			if( !$v['documents_paydate'] ) $v['documents_paydate'] = '00-00-0000';*/
			if( !$v['documents_price_paym'] ) $v['documents_price_paym'] = 0;
			
			if( $v['client_id'] == 0 ){		
				$data = array(
					'client_name' => str_replace("&amp;","&",$v['documents_client'])
				);
				$client_id = $Client->insert($data);
			}else{
				$client_id = $v['client_id'];
			}
		
			$data = array(
				'project_id' => $v['project_id'],
				'currency_id' => isset($v['currency_id'])?$v['currency_id']:1,
				'documents_name' => $v['documents_name'],
				'documents_client' => str_replace("&amp;","&",$v['documents_client']),
				'client_id' => $client_id,
				'documents_nr' => $v['documents_nr'],
				'documents_filename' => $_FILES["documents_file"]["name"],
				'documents_filesize' => $_FILES["documents_file"]["size"],
				'documents_filetype' => $_FILES["documents_file"]["type"],
				'documents_file' => $filename_name,
				'admin_id' => $admin->admin_id,				
				'documents_price_netto' => str_replace(",",".",$v['documents_price_netto']),
				'documents_price_brutto' => str_replace(",",".",$v['documents_price_brutto']),
				'documents_price_tax' => str_replace(",",".",$v['documents_price_tax']),
				'documents_price_rabate' => str_replace(",",".",$v['documents_price_rabate']),
				'documents_price_tax_sum' => str_replace(",",".",$v['documents_price_tax_sum']),
				'documents_price_rabate_sum' => str_replace(",",".",$v['documents_price_rabate_sum']),			
				'documents_data' => Lib_Date::convertDate($v['documents_data'],"d-m-Y","Y-m-d"),
				'documents_cp' => Lib_Date::convertDate($v['documents_cp'],"d-m-Y","Y-m-d"),
				'documents_checkdate' => Lib_Date::convertDate($v['documents_checkdate'],"d-m-Y","Y-m-d"),
				'documents_paydate' => Lib_Date::convertDate($v['documents_paydate'],"d-m-Y","Y-m-d"),
				'documents_ins' => Lib_Date::datetime(),
				'documents_edit' => Lib_Date::datetime(),				
				'documents_note' => $v['documents_note'],
				'documents_price_pay_method' => $v['documents_price_pay_method'],
				'documents_price_pay' => str_replace(",",".",$v['documents_price_pay']),				
				'documents_price_paym' => str_replace(",",".",$v['documents_price_paym'])
			);
			$idIns = $Documents->insert($data);
			
			
			
			if( $v['car_id'] != 0 ){
			
				$DocumentsCar = new DocumentsCar();
			
				$data = array(
					'documents_id' => $idIns,
					'car_id' => $v['car_id']
				);
			
				$idInsCarD = $DocumentsCar->insert($data);
			}
			
			
			
			$data = array(
				'documents_id' => $idIns,
				'documents_archive_filename' => $_FILES["documents_file"]["name"],
				'documents_archive_filesize' => $_FILES["documents_file"]["size"],
				'documents_archive_filetype' => $_FILES["documents_file"]["type"],
				'documents_archive_file' => $filename_name,
				'documents_archive_ins' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
			$idInsDA = $DocumentsArchive->insert($data);
			
			
					
		//	var_dump($data);die();
			$DocumentsHistory = new DocumentsHistory();
			$data = array(
				'documents_history_status' => 0,
				'documents_history_status_value' => 0,
				'documents_history_date' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id,
				'documents_id' => $idIns
			);
			$idIns = $DocumentsHistory->insert($data);
			
			$information->addDocumentsSuccess = true; 
			$this->_helper->redirector('index','documents');
			
		}		
		
		
		if( $filtrproject->project_id ){
			$this->view->filtr_project_id =  $filtrproject->project_id;
		}
		

		$db = Zend_Registry::get('db');
		$select = $db->select();
	//	$select->from('company')->join('project', 'company.company_id = project.company_id')->where('company.company_status = 0 AND project.project_status = 0 AND '.Lib_Permission::setPermissionProjectSQL())->order(array('company.company_name ASC','project.project_name ASC'));  
		$select->from('company')->join('project', 'company.company_id = project.company_id')->where(''.Lib_Permission::setPermissionProjectSQL())->order(array('company.company_name ASC','project.project_name ASC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		
		if( count($data) > 0 ) $this->view->dataTableCompany = $data;
	/*	
		$dataClient = $db->query("SELECT DISTINCT(documents_client) as client FROM `documents` ORDER BY client ASC")->fetchAll();
		$this->view->dataTableClient = $dataClient;
	*/	
		$dataClientDB = $db->query("SELECT * FROM `client` ORDER BY client_name ASC")->fetchAll();
		$this->view->dataTableClientDB = $dataClientDB;
		
		$dataCarDB = $db->query("SELECT * FROM `car` ORDER BY car_nr ASC")->fetchAll();
		$this->view->dataTableCarDB = $dataCarDB;		
		
		$dataCurrency = $Currency->fetchAll(); 		
		$this->view->dataTableCurrency = $dataCurrency;			
		$dataCurrencyArray = array();
		foreach($dataCurrency as $key => $val){
			$dataCurrencyArray[$val['currency_id']] = $val['currency_short'];
		}
		$this->view->dataTableCurrencyArray = $dataCurrencyArray;	
	}
	
	public function editAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');

		$Project = new Project();
		$Company = new Company();	
		$Client = new Client();	
		$Documents = new Documents();
		$DocumentsCar = new DocumentsCar();
		$DocumentsArchive = new DocumentsArchive();	
		$Currency = new Currency();	
		
		$filtrdocuments->last_open_document = $v['id'];		
		
		if( $information->editDocumentsSuccess ){
			$this->view->editDocumentsSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		
		if( isset($v['admin_editdocuments']) ){					
			
			if( $v['client_id'] == 0 ){		
				$data = array(
					'client_name' => str_replace("&amp;","&",$v['documents_client'])
				);
				$client_id = $Client->insert($data);
			}else{
				$client_id = $v['client_id'];
			}
			
			$data = array(
				'project_id' => $v['project_id'],
				'currency_id' => isset($v['currency_id'])?$v['currency_id']:1,
				'documents_name' => $v['documents_name'],
				'documents_client' => str_replace("&amp;","&",$v['documents_client']),
				'client_id' => $client_id,
				'documents_nr' => $v['documents_nr'],
				'documents_price_netto' => str_replace(",",".",$v['documents_price_netto']),
				'documents_price_brutto' => str_replace(",",".",$v['documents_price_brutto']),
				'documents_price_tax' => str_replace(",",".",$v['documents_price_tax']),
				'documents_price_rabate' => str_replace(",",".",$v['documents_price_rabate']),
				'documents_price_tax_sum' => str_replace(",",".",$v['documents_price_tax_sum']),
				'documents_price_rabate_sum' => str_replace(",",".",$v['documents_price_rabate_sum']),
				'documents_data' => Lib_Date::convertDate($v['documents_data'],"d-m-Y","Y-m-d"),
				'documents_cp' => Lib_Date::convertDate($v['documents_cp'],"d-m-Y","Y-m-d"),
				'documents_checkdate' => Lib_Date::convertDate($v['documents_checkdate'],"d-m-Y","Y-m-d"),
				'documents_paydate' => Lib_Date::convertDate($v['documents_paydate'],"d-m-Y","Y-m-d"),
				'documents_edit' => Lib_Date::datetime(),
				'documents_note' => $v['documents_note'],
				'documents_price_pay_method' => $v['documents_price_pay_method'],
				'documents_price_pay' => str_replace(",",".",$v['documents_price_pay']),
				'documents_price_paym' => str_replace(",",".",$v['documents_price_paym'])
			);
			if( Lib_Permission::CheckPermission('documentsadmin') == true ) $Documents->update( $data , ' documents_id='.$v['id'] );
			else $Documents->update( $data , 'admin_id='.$admin->admin_id.' AND documents_id='.$v['id'] );
			
			
			
				
			$where = array(
				'documents_id = ?' => $v['id']
			);	
			
			$DocumentsCar->delete($where);	
			if( $v['car_id'] != 0 ){					
				$data = array(
					'documents_id' => $v['id'],
					'car_id' => $v['car_id']
				);			
				$idInsCarD = $DocumentsCar->insert($data);
			}
			
			
						
			$DocumentsHistory = new DocumentsHistory();
			$data = array(
				'documents_history_status' => 3,
				'documents_history_status_value' => 0,
				'documents_history_date' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id,
				'documents_id' => $v['id']
			);
			$idIns = $DocumentsHistory->insert($data);
			
			
		
		
			$select = $Documents->select();
			$select->where('documents_id = ?', $v['id']);	
			$rowDoc = $Documents->fetchRow($select);
			
			
			
			
			
		// ===========================================================================	
			if( $_FILES["documents_file"]["tmp_name"] ){
			
		
			$upload_path = "documents/";
			$filename_name = $admin->admin_id.'_'.$rowDoc['project_id'].'_'.hash('sha256',$admin->admin_id.time().rand(0,100000));
			move_uploaded_file($_FILES["documents_file"]["tmp_name"], $upload_path.$filename_name);
				
			$data = array(
				'documents_filename' => $_FILES["documents_file"]["name"],
				'documents_filesize' => $_FILES["documents_file"]["size"],
				'documents_filetype' => $_FILES["documents_file"]["type"],
				'documents_file' => $filename_name
			);
			$Documents->update( $data , ' documents_id='.$v['id'] );
			
			
			$data = array(
				'documents_id' => $v['id'],
				'documents_archive_filename' => $_FILES["documents_file"]["name"],
				'documents_archive_filesize' => $_FILES["documents_file"]["size"],
				'documents_archive_filetype' => $_FILES["documents_file"]["type"],
				'documents_archive_file' => $filename_name,
				'documents_archive_ins' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
			$idInsDA = $DocumentsArchive->insert($data);
			
			
			
			}
		// ===========================================================================
			
			
			
			
			
			
			
			
			
			$information->editDocumentsSuccess = true; 
			$this->_helper->redirector('edit','documents',null,array('id' => $v['id']));			
		}		
		
		
		
		$select = $Documents->select();
		$select->where('documents_id = ?', $v['id']);	
		$row = $Documents->fetchRow($select);
		$this->view->documentsData = $row;
		
		$select = $Client->select();
		$select->where('client_id = ?', $row->client_id);	
		$rowClient = $Client->fetchRow($select);
		$this->view->clientData = $rowClient;	
		
		$select = $DocumentsCar->select();
		$select->where('documents_id = ?', $v['id']);	
		$rowDocumentsCar = $DocumentsCar->fetchRow($select);
		$this->view->documentsDataCar = $rowDocumentsCar;
		
		if( Lib_Permission::getPermissionProject( $row['project_id'] ) != 1 ){
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		

		$db = Zend_Registry::get('db');
		$select = $db->select();
		$select->from('company')->join('project', 'company.company_id = project.company_id')->order(array('company.company_name ASC','project.project_name ASC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		
		if( count($data) > 0 ) $this->view->dataTableCompany = $data;
		
	/*
		$dataClient = $db->query("SELECT DISTINCT(documents_client) as client FROM `documents` ORDER BY client ASC")->fetchAll();
		$this->view->dataTableClient = $dataClient;
	*/
	
		$dataClientDB = $db->query("SELECT * FROM `client` ORDER BY client_name ASC")->fetchAll();
		$this->view->dataTableClientDB = $dataClientDB;
		
		$dataCarDB = $db->query("SELECT * FROM `car` ORDER BY car_nr ASC")->fetchAll();
		$this->view->dataTableCarDB = $dataCarDB;
		
		$dataCurrency = $Currency->fetchAll(); 		
		$this->view->dataTableCurrency = $dataCurrency;			
		$dataCurrencyArray = array();
		foreach($dataCurrency as $key => $val){
			$dataCurrencyArray[$val['currency_id']] = $val['currency_short'];
		}
		$this->view->dataTableCurrencyArray = $dataCurrencyArray;	
	}
	
	public function viewAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');	
		$filtrdocuments = new Zend_Session_Namespace('filtrdocuments');	
		
		$Project = new Project();
		$Company = new Company();	
		$Client = new Client();	
		$Documents = new Documents();
		$DocumentsCar = new DocumentsCar();
		$DocumentsArchive = new DocumentsArchive();	
		$Currency = new Currency();	
		
		
		$Car = new Car();	
		$dataCar = $Car->fetchAll(null, 'car_nr ASC'); 		
		foreach($dataCar as $key => $val){
			$vCar[$val['car_id']] = $val['car_nr'];
		}
		$this->view->dCar = $vCar;
		
		
		$filtrdocuments->last_open_document = $v['id'];
		
		if( isset($v['admin_editdocuments']) ){	
		
		
		
		
		// ===========*********************************=====================================
		
		
			$select = $Documents->select();
			$select->where('documents_id = ?', $v['id']);	
			$row = $Documents->fetchRow($select);
			$this->view->documentsData = $row;	
		
			if( Lib_Permission::getPermissionProject( $row['project_id'] ) != 1 ){
				$information->permissionError = true;
				$this->_helper->redirector('index','index');		
			}
			
			if( !isset($v['documents_viewed']) ) $v['documents_viewed'] = 0;
			if( !isset($v['documents_sent']) ) $v['documents_sent'] = 0;
			if( !isset($v['documents_pay']) ) $v['documents_pay'] = 0;
			if( !isset($v['documents_pay2']) ) $v['documents_pay2'] = 0;
			if( !isset($v['documents_pay3']) ) $v['documents_pay3'] = 0;
			if( !isset($v['documents_pay4']) ) $v['documents_pay4'] = 0;
			if( !isset($v['documents_prepared']) ) $v['documents_prepared'] = 0;
			
			$DocumentsHistory = new DocumentsHistory();
			
			if( $v['documents_viewed'] != $row->documents_viewed ){
				$data = array(
					'documents_history_status' => 1,
					'documents_history_status_value' => $v['documents_viewed'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_sent'] != $row->documents_sent ){
				$data = array(
					'documents_history_status' => 2,
					'documents_history_status_value' => $v['documents_sent'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay'] != $row->documents_pay ){
				$data = array(
					'documents_history_status' => 5,
					'documents_history_status_value' => $v['documents_pay'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay2'] != $row->documents_pay2 ){
				$data = array(
					'documents_history_status' => 6,
					'documents_history_status_value' => $v['documents_pay2'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay3'] != $row->documents_pay3 ){
				$data = array(
					'documents_history_status' => 7,
					'documents_history_status_value' => $v['documents_pay3'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay4'] != $row->documents_pay4 ){
				$data = array(
					'documents_history_status' => 8,
					'documents_history_status_value' => $v['documents_pay4'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_prepared'] != $row->documents_prepared ){
				$data = array(
					'documents_history_status' => 9,
					'documents_history_status_value' => $v['documents_prepared'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			$data = array(
				'documents_viewed' => $v['documents_viewed'],
				'documents_sent' => $v['documents_sent'],
				'documents_pay' => $v['documents_pay'],
				'documents_pay2' => $v['documents_pay2'],
				'documents_pay3' => $v['documents_pay3'],
				'documents_pay4' => $v['documents_pay4'],
				'documents_prepared' => $v['documents_prepared']
			);
			$Documents->update( $data , 'documents_id='.$v['id'] );
		
		
		// ===========*********************************=====================================
		
		
		
		
		
		
		
		
		
		
		
			$select = $Documents->select();
			$select->where('documents_id = ?', $v['id']);	
			$rowDoc = $Documents->fetchRow($select);
		
		

			if( !$v['documents_price_paym'] ) $v['documents_price_paym'] = 0;		
			$data = array(
				'documents_paydate' => Lib_Date::convertDate($v['documents_paydate'],"d-m-Y","Y-m-d"),
				'documents_edit' => Lib_Date::datetime(),
				'documents_note' => $v['documents_note'],
				'documents_price_pay_method' => $v['documents_price_pay_method'],
				'documents_price_pay' => str_replace(",",".",$v['documents_price_pay']),
				'documents_price_paym' => str_replace(",",".",$v['documents_price_paym'])
			);
			$Documents->update( $data , ' documents_id='.$v['id'] );
						
			$DocumentsHistory = new DocumentsHistory();
			$data = array(
				'documents_history_status' => 3,
				'documents_history_status_value' => 0,
				'documents_history_date' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id,
				'documents_id' => $v['id']
			);
			$idIns = $DocumentsHistory->insert($data);
			
			
			
			
		// ===========================================================================	
			if( $_FILES["documents_file"]["tmp_name"] ){
			
		
			$upload_path = "documents/";
			$filename_name = $admin->admin_id.'_'.$rowDoc['project_id'].'_'.hash('sha256',$admin->admin_id.time().rand(0,100000));
			move_uploaded_file($_FILES["documents_file"]["tmp_name"], $upload_path.$filename_name);
				
			$data = array(
				'documents_filename' => $_FILES["documents_file"]["name"],
				'documents_filesize' => $_FILES["documents_file"]["size"],
				'documents_filetype' => $_FILES["documents_file"]["type"],
				'documents_file' => $filename_name
			);
			$Documents->update( $data , ' documents_id='.$v['id'] );
			
			
			$data = array(
				'documents_id' => $v['id'],
				'documents_archive_filename' => $_FILES["documents_file"]["name"],
				'documents_archive_filesize' => $_FILES["documents_file"]["size"],
				'documents_archive_filetype' => $_FILES["documents_file"]["type"],
				'documents_archive_file' => $filename_name,
				'documents_archive_ins' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
			$idInsDA = $DocumentsArchive->insert($data);
			
			
			
			}
		// ===========================================================================
			
			
			
			
			$information->editDocumentsSuccess = true; 
			$this->_helper->redirector('view','documents',null,array('id' => $v['id']));			
		}			
		
		if( $information->statusDocumentsSuccess ){ 
			$this->view->statusDocumentsSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}		
		
		if( $information->addFiltrDocumentsHistorySuccess ){ 
			$this->view->statusDocumentsSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}	
		
		
		if( isset($v['documents_history_status']) ){			
			if( $v['documents_history_status'] != 'all' ){
				$filtrdocuments->documents_history_status = $v['documents_history_status'];
				$information->addFiltrDocumentsHistorySuccess = true;
			}else{
				unset($filtrdocuments->documents_history_status);
				$information->addFiltrDocumentsHistoryRemove = true;
			}			
			$this->_helper->redirector('view','documents', null, array('id'=>$v['id']));	
		}
		
		if( $filtrdocuments->documents_history_status ){
			$this->view->documents_history_status =  $filtrdocuments->documents_history_status;
			if( $filtrdocuments->documents_history_status == -1 ) $valDHS = 0;
			else $valDHS = $filtrdocuments->documents_history_status;
			$search = 'documents_history_status='.$valDHS;
		}
		

		
		if( isset($v['admin_statusdocuments']) ){		
		
			$select = $Documents->select();
			$select->where('documents_id = ?', $v['id']);	
			$row = $Documents->fetchRow($select);
			$this->view->documentsData = $row;	
		
			if( Lib_Permission::getPermissionProject( $row['project_id'] ) != 1 ){
				$information->permissionError = true;
				$this->_helper->redirector('index','index');		
			}
			
			if( !isset($v['documents_viewed']) ) $v['documents_viewed'] = 0;
			if( !isset($v['documents_sent']) ) $v['documents_sent'] = 0;
			if( !isset($v['documents_pay']) ) $v['documents_pay'] = 0;
			if( !isset($v['documents_pay2']) ) $v['documents_pay2'] = 0;
			if( !isset($v['documents_pay3']) ) $v['documents_pay3'] = 0;
			
			$DocumentsHistory = new DocumentsHistory();
			
			if( $v['documents_viewed'] != $row->documents_viewed ){
				$data = array(
					'documents_history_status' => 1,
					'documents_history_status_value' => $v['documents_viewed'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_sent'] != $row->documents_sent ){
				$data = array(
					'documents_history_status' => 2,
					'documents_history_status_value' => $v['documents_sent'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay'] != $row->documents_pay ){
				$data = array(
					'documents_history_status' => 5,
					'documents_history_status_value' => $v['documents_pay'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay2'] != $row->documents_pay2 ){
				$data = array(
					'documents_history_status' => 6,
					'documents_history_status_value' => $v['documents_pay2'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			if( $v['documents_pay3'] != $row->documents_pay3 ){
				$data = array(
					'documents_history_status' => 7,
					'documents_history_status_value' => $v['documents_pay3'],
					'documents_history_date' => Lib_Date::datetime(),
					'admin_id' => $admin->admin_id,
					'documents_id' => $v['id']
				);
				$idIns = $DocumentsHistory->insert($data);
			}
			
			$data = array(
				'documents_viewed' => $v['documents_viewed'],
				'documents_sent' => $v['documents_sent'],
				'documents_pay' => $v['documents_pay'],
				'documents_pay2' => $v['documents_pay2'],
				'documents_pay3' => $v['documents_pay3']
			);
			$Documents->update( $data , 'documents_id='.$v['id'] );
						
			$information->statusDocumentsSuccess = true; 
			$this->_helper->redirector('view','documents',null,array('id' => $v['id']));			
		}else{
			$DocumentsHistory = new DocumentsHistory();
			$data = array(
				'documents_history_status' => 4,
				'documents_history_status_value' => 0,
				'documents_history_date' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id,
				'documents_id' => $v['id']
			);
			$idIns = $DocumentsHistory->insert($data);
		}	
		
		
		$select = $Documents->select();
		$select->where('documents_id = ?', $v['id']);	
		$row = $Documents->fetchRow($select);
		$this->view->documentsData = $row;	
		
		$select = $Client->select();
		$select->where('client_id = ?', $row->client_id);	
		$rowClient = $Client->fetchRow($select);
		$this->view->clientData = $rowClient;
		
		$select = $DocumentsCar->select();
		$select->where('documents_id = ?', $v['id']);	
		$rowDocumentsCar = $DocumentsCar->fetchRow($select);
		$this->view->documentsDataCar = $rowDocumentsCar;	
		
		if( Lib_Permission::getPermissionProject( $row['project_id'] ) != 1 ){
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}

		$db = Zend_Registry::get('db');	
		
		$limit = 10;
		$limitpage = 10;

		$page = $this->_request->getParams();
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
		
		$p = ($page-1)*$limit;		
		
		$select = $db->select();
		$select->from('documents_history')->join('admin', 'documents_history.admin_id = admin.admin_id')->where('documents_id = ?', $v['id']);
		if( isset($search) ) $select->where($search);
		$select->order(array('documents_history.documents_history_date DESC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = count($data);
		
		$Lib_Page = new Lib_Page();
		$Lib_Page->setLimit( $limit );
		$Lib_Page->setLimitPage( $limitpage );
		$Lib_Page->setMax( $dataCount );
		$Lib_Page->setActualId( $page );
		$Lib_Page->setController('documents');
		$Lib_Page->setAction('view');
		$Lib_Page->setGet('/id/'.$v['id']);
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;	
		
		
		$select = $db->select();
		$select->from('documents_history')->join('admin', 'documents_history.admin_id = admin.admin_id')->where('documents_id = ?', $v['id']);
		if( isset($search) ) $select->where($search);
		$select->order(array('documents_history.documents_history_date DESC'))->limit($limit,$p);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$this->view->dataTableDocumentsHistory = $data;
		
		$select = $db->select();
		$select->from('company')->join('project', 'company.company_id = project.company_id')->order(array('company.company_name ASC','project.project_name ASC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		
		if( count($data) > 0 ) $this->view->dataTableCompany = $data;
		
		$dataCurrency = $Currency->fetchAll(); 		
		$this->view->dataTableCurrency = $dataCurrency;			
		$dataCurrencyArray = array();
		foreach($dataCurrency as $key => $val){
			$dataCurrencyArray[$val['currency_id']] = $val['currency_short'];
		}
		$this->view->dataTableCurrencyArray = $dataCurrencyArray;	
	}
	
	public function openAction(){
		$admin = new Zend_Session_Namespace('admin');
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');
		
		$DocumentsArchive = new DocumentsArchive();
		$select = $DocumentsArchive->select();
		$select->where('documents_archive_id = ?', $v['id']);	
		$row = $DocumentsArchive->fetchRow($select);
		
		$Documents = new Documents();
		$select = $Documents->select();
		$select->where('documents_id = ?', $row['documents_id']);	
		$rowDoc = $Documents->fetchRow($select);
		
		if( Lib_Permission::getPermissionProject( $rowDoc['project_id'] ) != 1 ){
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		if ( isset($row->documents_archive_file) ) { 
			
			if( !$information->views ){
				$countVisit = $row['documents_archive_views']+1;
				$data = array(
					'documents_archive_views' => $countVisit
				);
				$DocumentsArchive->update( $data , 'documents_archive_id='.$v['id'] );
				$information->views = true;
			}
		
			$file = 'documents/'.$row->documents_archive_file;
			header('Content-Type: '.$row->documents_archive_filetype);
			header('Content-Disposition: inline; filename="'.$row->documents_archive_filename.'"');
			header('Content-Length: '.filesize($file));	
	
			ob_clean();
			flush();
			@readfile($file);
			exit;
		}else{
			$information->openDocumentsError = true; 
			$this->_helper->redirector('index','documents');			
		}
		
        $this->_helper->viewRenderer->setNoRender();
	}
	
	public function removeAction() {	
		$v = $this->_request->getParams();		
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
				
		$Documents = new Documents();
		$select = $Documents->select();
		$select->where('documents_id = ?', $v['id']);	
		$row = $Documents->fetchRow($select);
		
		if( Lib_Permission::getPermissionProject( $row['project_id'] ) != 1 ){
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$Documents = new Documents();
		if( Lib_Permission::CheckPermission('documentsadmin') == true ){
			$where = array(
				'documents_id = ?' => $v['id']
			);		
		}
		else{
			$where = array(
				'documents_id = ?' => $v['id'],
				'admin_id = ?' => $admin->admin_id
			);
		}
		$Documents->delete($where);	
		$information->removeSuccess = true; 
		$this->_helper->redirector('index','documents');		
	}
	
	public function removedocumentsarchiveAction() {	
		$v = $this->_request->getParams();		
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		
		$DocumentsArchive = new DocumentsArchive();
		if( Lib_Permission::CheckPermission('documentsarchivedel') == true ){
			$where = array(
				'documents_id = ?' => $v['id'],
				'documents_archive_id = ?' => $v['daid']
			);
			$DocumentsArchive->delete($where);	
		}
		
		$this->_helper->redirector('edit','documents',null,array('id' => $v['id']));	
	}
	
}
