<?php

class MYPDF extends TCPDF {
    public function Footer() {
        $this->SetY(-10);
        $this->SetFont('helvetica', 'N', 7);
        $this->Cell(0, 15, "Oprogramowanie dostarcza: www.technix.pl", 0, false, 'L', 0, '', 0, false, 'T', 'M');
        $this->Cell(0, 15, 'Strona '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
    }
}

class CalculationController extends Zend_Controller_Action {



	public function init() {
		$information = new Zend_Session_Namespace('information');	
		if( Lib_Permission::CheckPermission('calculation') != 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');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		if( $information->addProjectSuccess ){
			$this->view->addProjectSuccess = 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->addFiltrStatusSuccess ){
			$this->view->addFiltrStatusSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addFiltrStatusRemove ){
			$this->view->addFiltrStatusRemove = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( isset($v['filtrLimit']) ){
			$filtrcalculation->limit = $v['filtrLimit'];
			$this->_helper->redirector('index','calculation');	
		}
		
		
		if( isset($vPost['filtrCompany']) ){
			if( $vPost['filtrCompany'] != 'all' ){
				$filtrcalculation->company_id = $vPost['filtrCompany'];
				$information->addFiltrCompanySuccess = true;
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->company_id);
				$information->addFiltrCompanyRemove = true;
			}
			$this->_helper->redirector('index','calculation');	
		}
		
		if( isset($vPost['filtrClient']) ){
			if( $vPost['filtrClient'] != 'all' ){
				$filtrcalculation->client_id = $vPost['filtrClient'];
				if( $filtrcalculation->client_id == 0 ) $filtrcalculation->client_id = 0;
				$information->addFiltrStatusSuccess = true;
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->client_id);
				$information->addFiltrStatusRemove = true;
			}
			$this->_helper->redirector('index','calculation');	
		}
		
		
		if( isset($vPost['filtrProjectStatus']) ){
			if( $vPost['filtrProjectStatus'] != 'all' ){
				$filtrcalculation->project_status = $vPost['filtrProjectStatus'];
				$information->addFiltrStatusSuccess = true;
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->project_status);
				$information->addFiltrStatusRemove = true;
			}
			$this->_helper->redirector('index','calculation');	
		}
		
		
		
		
		
		
		
		if( $filtrcalculation->company_id ){
			$this->view->filtr_company_id =  $filtrcalculation->company_id;
			$search = 'company_id='.$filtrcalculation->company_id;
		}
		
		
		if( isset($filtrcalculation->client_id) ){
			$this->view->filtr_client_id =  $filtrcalculation->client_id;
			$this->view->filtr_client_id_filtr =  true;
			if( isset($search) ) $search = $search.' AND project_client_id_main='.$filtrcalculation->client_id;
			else $search = 'project_client_id_main='.$filtrcalculation->client_id;
		}
		
		if( $filtrcalculation->project_status ){
			$this->view->filtr_project_status =  $filtrcalculation->project_status;
			$status = $filtrcalculation->project_status - 1;
			if( isset($search) ) $search = $search.' AND project_status='.$status;
			else $search = 'project_status='.$status;
		}
		
		if( isset($search) ) $search = $search;
		else $search = null;
		
		if( !isset($search) ){
			$search = null;
		}
		
		
		
		
		
		
		$searchEmployeeProjectName = null;
		
		
		// filtr nazwa projektu - poczatek
		if( isset($vPost['removeEmployeeProjectName']) ){
			unset($filtrcalculation->employee_project_name);
			$information->addFiltrCompanyRemove = true;
			$this->_helper->redirector('index','calculation');	
		}
		if( isset($vPost['filtrEmployeeProjectName']) ){
			$filtrcalculation->employee_project_name = $vPost['filtrEmployeeProjectName'];
			$information->addFiltrStatusSuccess = true;
			$this->_helper->redirector('index','calculation');	
		}		
		if( $filtrcalculation->employee_project_name ){
			$this->view->filtr_name_employeeproject =  $filtrcalculation->employee_project_name;
			
			$searchEmployee = explode(" ",$filtrcalculation->employee_project_name);
			foreach($searchEmployee as $searchEmployeeKey => $searchEmployeeVal){
			
				if( !$searchEmployeeProjectName ){
					$searchEmployeeProjectName = "
						(
							project_name LIKE '".str_replace("*","%",$searchEmployeeVal)."' OR
							project_nr LIKE '".str_replace("*","%",$searchEmployeeVal)."'
						)
					";
				}else{
					$searchEmployeeProjectName = $searchEmployeeProjectName."
						AND (
							project_name LIKE '".str_replace("*","%",$searchEmployeeVal)."' OR
							project_nr LIKE '".str_replace("*","%",$searchEmployeeVal)."'
						)
					";				
				}
			
			}
		}
		if( !isset($searchEmployeeProjectName) ){
			$searchEmployeeProjectName = null;
		}
		// filtr nazwa projektu - koniec
		// ==========================================================
		
		
		
		
		
		if( $search == null AND $searchEmployeeProjectName != null ){
			$search = $searchEmployeeProjectName;
		}
		
		if( $search != null AND $searchEmployeeProjectName != null ){
			$search = $search.' AND '.$searchEmployeeProjectName;
		}
		
		
		if( $search != null ){
			$search = $search.' AND project_activ_settlement = 1';
		}else{
			$search = 'project_activ_settlement = 1';		
		}
		
		if( !$filtrcalculation->limit ){
			$filtrcalculation->limit = 10;
		}
		
		if( !isset($search) ){
			$search = null;
		}
		
		$this->view->filtrLimit =  $filtrcalculation->limit;
		$limit = $filtrcalculation->limit;
		$limitpage = 10;

		$page = $this->_request->getParams();
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
		
		/*
		if( $_GET['pV'] == true ){
			echo Lib_Permission::setPermissionCompanyCalcSQL();
			echo'<hr />';
			echo Lib_Permission::setPermissionProjectCalcSQL();
		}
		*/

		if( $search != null ){
			$search = $search.' AND '.Lib_Permission::setPermissionProjectCalcSQL();
		}else{
			$search = Lib_Permission::setPermissionProjectCalcSQL();		
		}		
		
		$search = ' WHERE '.$search;
		
		$ask = '
			SELECT 
			COUNT(*) AS project_count
			FROM project
			'.$search.'
			ORDER BY project_ins DESC
		';
		//echo$ask;die();
		$data = $db->query($ask)->fetchAll();
		$dataCount = $data[0]['project_count'];
		
		$p = ($page-1)*$limit;
		$ask = '
			SELECT 
			*, 
			(SELECT COUNT(*) FROM project_file WHERE project.project_id = project_file.project_id AND project_file.project_file_type = 0) AS project_file_count0, 
			(SELECT COUNT(*) FROM project_file WHERE project.project_id = project_file.project_id AND project_file.project_file_type = 1) AS project_file_count1 
			FROM project
			'.$search.'
			ORDER BY project_ins DESC
			LIMIT '.$p.','.$limit.'
		';
		//echo$ask;die();
		$data = $db->query($ask)->fetchAll();
		$this->view->dataTable = $data;		
	
/*	
		$Project = new Project();	
		$dataCount = count($Project->fetchAll($search , 'project_ins DESC')); 
			$p = ($page-1)*$limit;		
		$data = $Project->fetchAll($search , 'project_ins DESC', $limit,$p); 		
		$this->view->dataTable = $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('calculation');
		$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::setPermissionCompanyCalcSQL(), " company_name ASC "); 		
		if( count($data) > 0 ) $this->view->dataTableCompany = $data;
		
		$ask = "SELECT project_client_id_main, client_name, COUNT(*) AS count FROM project p LEFT JOIN `client` c ON p.project_client_id_main = c.client_id GROUP BY project_client_id_main";
		$data = $db->query($ask)->fetchAll();		
		$this->view->dataTableClientMain = $data;		
		
	}








	
	
	
	public function productAction() {	
	
		$this->_helper->redirector('productv2','calculation');
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();

		
		$Client = new Client();
		$data = $Client->fetchAll('client_activ_product = 1', "client_name ASC "); 		
		if( count($data) > 0 ) $this->view->dataTableClient = $data;
		
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 


	}








	
	
	
	public function productv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();

		
		$Client = new Client();
		$data = $Client->fetchAll('client_activ_product = 1', "client_name ASC "); 		
		if( count($data) > 0 ) $this->view->dataTableClient = $data;
		
		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompany( $val['product_company_id'] );
		}

		$this->view->dataTableCompanyGroup = $dataCompany;
		
	}




	
	
	public function productcatalogAction() {		
		$v = $this->_request->getParams();	
		$this->_helper->redirector('productcatalogv2','calculation',null,array('id' => $v['id']));
		
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		$db = Zend_Registry::get('db');
		
		$Product = new Product();
		
		$vPost = $this->_request->getPost();
		
		
		
		if( $vPost['filtr_status_h'] == 1 ){
			if( $vPost['filtr_status'] == 'all' ){
				$filtrcalculation->filtr_status = $vPost['filtr_status'];
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->filtr_status);
			}
			$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));	
		}
		
		$searchActiveProduct = ' AND product_activ = 0';
		if( $filtrcalculation->filtr_status ){
			$this->view->filtr_status =  $filtrcalculation->filtr_status;
			$searchActiveProduct = '';
		}
		
		$searchClient = '';
		if( $v['id'] ){
		$Client = new Client();
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->clientData = $row;
		$searchClient = 'client_id = '.$v['id'].' AND  ';
		}
		
		$select = $db->select();
		$select->from('product',array('COUNT(product.product_id) as count', 'product.product_id'));
		if( $v['id'] ) $select->where('client_id = '.$v['id']);	 
		$select->where('product_activ = 1');	
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];	
		$this->view->productCountNoActiv = $dataCount;
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 
		
		$productList = array();
		foreach( $d as $key => $val ){	
			
			$productList[$val['product_group_id']]['product_group_name'] = $val['product_group_name'];
			$productList[$val['product_group_id']]['product_group_child'] = $val['product_group_child'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
				
					$productList[$val['product_group_id']]['child'][$val2['product_group_id']]['product_group_name'] = $val2['product_group_name'];
					$data = $Product->fetchAll($searchClient.'product_group_id = '.$val2['product_group_id'].$searchActiveProduct, "product_name ASC "); 		
					$productList[$val['product_group_id']]['child'][$val2['product_group_id']]['product'] = $data;
				
				}
			}else{						
				$data = $Product->fetchAll($searchClient.'product_group_id = '.$val['product_group_id'].$searchActiveProduct, "product_name ASC "); 		
				$productList[$val['product_group_id']]['product'] = $data;				
			}
			
		}
	
	
		$this->view->productList = $productList; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
	}




	
	
	public function productcatalogv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		$db = Zend_Registry::get('db');
		
		$Product = new Product();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		if( $vPost['filtr_status_h'] == 1 ){
			if( $vPost['filtr_status'] == 'all' ){
				$filtrcalculation->filtr_status = $vPost['filtr_status'];
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->filtr_status);
			}
			$this->_helper->redirector('productcatalogv2','calculation',null,array('id' => $v['id']));	
		}
		
		$searchActiveProduct = ' AND p.product_activ = 0';
		if( $filtrcalculation->filtr_status ){
			$this->view->filtr_status =  $filtrcalculation->filtr_status;
			$searchActiveProduct = '';
		}
		
		$searchClient = '';
		if( $v['id'] ){
		$Client = new Client();
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('productv2','calculation');			
		}
		
		$this->view->clientData = $row;
		$searchClient = ' AND p.client_id = '.$v['id'];
		}
		
		$select = $db->select();
		$select->from('product',array('COUNT(product.product_id) as count', 'product.product_id'));
		if( $v['id'] ) $select->where('client_id = '.$v['id']);	 
		$select->where('product_activ = 1');	
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];	
		$this->view->productCountNoActiv = $dataCount;
		
		
		
		
		// budowanie drzewa kategorii
		
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 
		
		$productList = array();
		foreach( $d as $key => $val ){	
			
			$productList[$val['product_group_id']]['product_group_name'] = $val['product_group_name'];
			$productList[$val['product_group_id']]['product_group_child'] = $val['product_group_child'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
				
					$productList[$val['product_group_id']]['child'][$val2['product_group_id']]['product_group_name'] = $val2['product_group_name'];
					$data = $Product->fetchAll($searchClient.'product_group_id = '.$val2['product_group_id'].$searchActiveProduct, "product_name ASC "); 		
					$productList[$val['product_group_id']]['child'][$val2['product_group_id']]['product'] = $data;
				
				}
			}else{						
				$data = $Product->fetchAll($searchClient.'product_group_id = '.$val['product_group_id'].$searchActiveProduct, "product_name ASC "); 		
				$productList[$val['product_group_id']]['product'] = $data;				
			}
			
		}
		*/
		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompany( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;
		
	
		$ask = "
		
			SELECT * FROM 
				product_company pc,
				product_group pg,
				product p
			WHERE
				pc.product_company_id = p.product_company_id AND
				pg.product_group_id = p.product_group_id AND
				pg.product_group_id = p.product_group_id
				".$searchClient."
				".$searchActiveProduct."
			ORDER BY
				pc.product_company_name ASC,
				pg.product_group_name_full ASC,
				p.product_name ASC
		
		";
	
		$productList = $db->query($ask)->fetchAll();
		$this->view->productList = $productList; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
	}




	
	
	public function productcataloggroupAction() {	
		$v = $this->_request->getParams();	
		$this->_helper->redirector('productcataloggroupv2','calculation',null,array('id' => $v['id']));
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		$db = Zend_Registry::get('db');
		
		$Product = new Product();
		
		$vPost = $this->_request->getPost();
		
		
		
		if( $vPost['filtr_status_h'] == 1 ){
			if( $vPost['filtr_status'] == 'all' ){
				$filtrcalculation->filtr_status = $vPost['filtr_status'];
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->filtr_status);
			}
			$this->_helper->redirector('productcataloggroup','calculation',null,array('id' => $v['id']));	
		}
		
		$searchActiveProduct = ' AND product_activ = 0';
		if( $filtrcalculation->filtr_status ){
			$this->view->filtr_status =  $filtrcalculation->filtr_status;
			$searchActiveProduct = '';
		}
		
		
		
		$ProductGroup = new ProductGroup();
		$select = $ProductGroup->select();
		$select->where('product_group_id = ?', $v['id']);
		$select->where('product_group_child = ?', 0);	
		$row = $ProductGroup->fetchRow($select);
		
		
		
		$ProductCompany = new ProductCompany();
		$select = $ProductCompany->select();
		$select->where('product_company_id = ?', $row['product_company_id']);
		$pgData = $ProductCompany->fetchRow($select);
		$this->view->product_company_info = $pgData;
		
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productgroupData = $row;
		
		
		$select = $db->select();
		$select->from('product',array('COUNT(product.product_id) as count', 'product.product_id'));
		$select->where('product_group_id = '.$v['id']);	 
		$select->where('product_activ = 1');	
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];	
		$this->view->productCountNoActiv = $dataCount;
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 

		$d1 = Lib_Calculation::categoryProduct();
		$d2 = array();
		foreach( $d1 as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		
		
		$productList = array();
		foreach( $d as $key => $val ){			
			$data = $Product->fetchAll('product_group_id = '.$v['id'].' AND  client_id = '.$val['client_id'].$searchActiveProduct, "product_name ASC "); 	
			$productList[$val['client_id']]['client_name'] = $val['client_name'];	
			$productList[$val['client_id']]['product'] = $data;	
		}	
		
		$this->view->productList = $productList; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
	}




	
	
	public function productcataloggroupv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		$db = Zend_Registry::get('db');
		
		$Product = new Product();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		if( $vPost['filtr_status_h'] == 1 ){
			if( $vPost['filtr_status'] == 'all' ){
				$filtrcalculation->filtr_status = $vPost['filtr_status'];
			}else{
				//Zend_Session::namespaceUnset('filtrcalculation');
				unset($filtrcalculation->filtr_status);
			}
			$this->_helper->redirector('productcataloggroup','calculation',null,array('id' => $v['id']));	
		}
		
		$searchActiveProduct = ' AND product_activ = 0';
		if( $filtrcalculation->filtr_status ){
			$this->view->filtr_status =  $filtrcalculation->filtr_status;
			$searchActiveProduct = '';
		}
		
		
		
		$ProductGroup = new ProductGroup();
		$select = $ProductGroup->select();
		$select->where('product_group_id = ?', $v['id']);
		$select->where('product_group_child = ?', 0);	
		$row = $ProductGroup->fetchRow($select);
		
		
		
		$ProductCompany = new ProductCompany();
		$select = $ProductCompany->select();
		$select->where('product_company_id = ?', $row['product_company_id']);
		$pgData = $ProductCompany->fetchRow($select);
		$this->view->product_company_info = $pgData;
		
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productgroupData = $row;
		
		
		$select = $db->select();
		$select->from('product',array('COUNT(product.product_id) as count', 'product.product_id'));
		$select->where('product_group_id = '.$v['id']);	 
		$select->where('product_activ = 1');	
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];	
		$this->view->productCountNoActiv = $dataCount;
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
		
		/*
		$d1 = Lib_Calculation::categoryProduct();
		$d2 = array();
		foreach( $d1 as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		*/		
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		/*
		$productList = array();
		foreach( $d as $key => $val ){			
			$data = $Product->fetchAll('product_group_id = '.$v['id'].' AND  client_id = '.$val['client_id'].$searchActiveProduct, "product_name ASC "); 	
			$productList[$val['client_id']]['client_name'] = $val['client_name'];	
			$productList[$val['client_id']]['product'] = $data;	
		}	
		*/
	
		$search = ' AND p.product_group_id = '.$v['id'];
		$ask = "
		
			SELECT * FROM 
				client c,
				product p
			WHERE
				c.client_id = p.client_id
				".$search."
				".$searchActiveProduct."
			ORDER BY
				c.client_name ASC,
				p.product_name ASC
		
		";
	
		$productList = $db->query($ask)->fetchAll();
		
		$this->view->productList = $productList; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
	}
	
	public function productcatalogremoveAction() {	
		$v = $this->_request->getParams();		
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');	
		
		$Product = new Product();
		
		$where = array(
			'product_id = ?' => $v['idp']
		);
		$Product->delete($where);
		
		if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
			$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
		}else{
			$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));
		}
	}



	
	
	public function productcatalogaddAction() {	
		$this->_helper->redirector('productcatalogaddv2','calculation');
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$Product = new Product();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		$Client = new Client();
		if( $v['id'] ){
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
	//		$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->clientData = $row;
		}
		
		
		$ProductGroup = new ProductGroup();
		if( $v['idg'] ){
		$select = $ProductGroup->select();
		$select->where('product_group_id = ?', $v['idg']);	
		$row = $ProductGroup->fetchRow($select);
		
		if( !$row ){
	//		$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productgroupData = $row;
		}
		
		
		
		
		if( isset($v['calculation_addproduct']) ){	
		
			$data = array(
				'product_group_id' => $v['product_group_id'],
				'product_company_id' => 1,
				'product_name' => $v['product_name'],
				'product_notice' => $v['product_notice'],
				'product_nr' => $v['product_nr'],
				'product_price' => isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00',	
				'product_unit_id' => $v['product_unit_id'],			
				'product_nc' => isset($v['product_nc'])?$v['product_nc']:'0',		
				'client_id' => $v['client_id'],
				'product_ins' => Lib_Date::datetime(),
				'product_edit' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
			$Product->insert($data);
			
		//	$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));
			
		//	var_dump($data);		

		
			if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
				$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
			}else{
				$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));
			}		
		
		}	
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 

		$this->view->client_id = $v['id']; 
		$this->view->product_group_id = $v['idg']; 

	}



	
	
	public function productcatalogaddv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$Product = new Product();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		$Client = new Client();
		if( $v['id'] ){
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
	//		$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->clientData = $row;
		}
		
		
		$ProductGroup = new ProductGroup();
		if( $v['idg'] ){
		$select = $ProductGroup->select();
		$select->where('product_group_id = ?', $v['idg']);	
		$row = $ProductGroup->fetchRow($select);
		
		if( !$row ){
	//		$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productgroupData = $row;
		}
		
		
		
		
		if( isset($v['calculation_addproduct']) ){	
		
			$select = $ProductGroup->select();
			$select->where('product_group_id = ?', $v['product_group_id']);
			$rowGroup = $ProductGroup->fetchRow($select);
		
			$data = array(
				'product_group_id' => $v['product_group_id'],
				'product_company_id' => $rowGroup['product_company_id'],
				'product_name' => $v['product_name'],
				'product_notice' => $v['product_notice'],
				'product_nr' => $v['product_nr'],
				'product_price' => isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00',	
				'product_unit_id' => $v['product_unit_id'],			
				'product_nc' => isset($v['product_nc'])?$v['product_nc']:'0',		
				'client_id' => $v['client_id'],
				'product_ins' => Lib_Date::datetime(),
				'product_edit' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
		//	var_dump($data);die();
			$Product->insert($data);
			
		//	$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));
			
		//	var_dump($data);		

		
			if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
				$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
			}else{
				$this->_helper->redirector('productcatalogv2','calculation',null,array('id' => $v['id']));
			}		
		
		}	
		
		
		
		
		// budowanie drzewa kategorii
		
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		*/
		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompany( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;
		
		
		
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 

		$this->view->client_id = $v['id']; 
		$this->view->product_group_id = $v['idg']; 

	}



	
	
	public function productcatalogeditAction() {	
		$v = $this->_request->getParams();
		$this->_helper->redirector('productcatalogaddv2','calculation',null,array('id' => $v['id']));
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$Product = new Product();
		
		$vPost = $this->_request->getPost();
		
		
		
		$Client = new Client();
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->clientData = $row;
		
		
		
		$select = $Product->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('product_id = ?', $v['idp']);	
		$row = $Product->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productData = $row;
		
		
		
		
		
		

		$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('product_history',array('COUNT(product_history_id) as count', 'product_history_id'))->join('admin', 'product_history.admin_id = admin.admin_id')->where('product_id = ?', $v['idp']);
		if( isset($search) ) $select->where($search);
		$select->order(array('product_history.product_history_ins DESC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];
		
		$Lib_Page = new Lib_Page();
		$Lib_Page->setLimit( $limit );
		$Lib_Page->setLimitPage( $limitpage );
		$Lib_Page->setMax( $dataCount );
		$Lib_Page->setActualId( $page );
		$Lib_Page->setController('calculation');
		$Lib_Page->setAction('productcatalogedit');
		$Lib_Page->setGet('/id/'.$v['id'].'/idp/'.$v['idp']);
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;	
		
		
		$select = $db->select();
		$select->from('product_history')->join('admin', 'product_history.admin_id = admin.admin_id')->where('product_id = ?', $v['idp']);
		if( isset($search) ) $select->where($search);
		$select->order(array('product_history.product_history_ins DESC'))->limit($limit,$p);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$this->view->dataTableProductHistory = $data;
		
		
		
		
		
		
		
		
		if( isset($v['calculation_editproduct']) ){	
		
			$v['product_nc'] = isset($v['product_nc'])?$v['product_nc']:'0';
			$data = array(
				'product_group_id' => $v['product_group_id'],
				'product_name' => $v['product_name'],
				'product_notice' => $v['product_notice'],
				'product_nr' => $v['product_nr'],
				'product_price' => isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00',	
				'product_unit_id' => $v['product_unit_id'],	
				'product_nc' => isset($v['product_nc'])?$v['product_nc']:'0',	
				'product_edit' => Lib_Date::datetime(),
				'product_activ' => $v['product_activ']
			);
			$Product->update($data,"client_id = ".$v['id']." AND product_id = ".$v['idp']);
			
			// zapis historii
			$ProductHistory = new ProductHistory();
			
			$v['product_price'] = isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00';
			$field = array(
				'product_group_id',
				'product_name',
				'product_notice',
				'product_nr',
				'product_price',	
				'product_unit_id',	
				'product_nc',	
				'product_activ'
			);
		/*	
		*/
		
			foreach( $field as $k => $val ){
			
				if( $row->$val != $v[$val] ){
					$dataHistory = array(
						'product_id' => $v['idp'],
						'admin_id' => $admin->admin_id,
						'product_history_field' => $val,
						'product_history_value_old' => $row->$val,
						'product_history_value_new' => $v[$val],
						'product_history_ins' => Lib_Date::datetime()
					);
					$ProductHistory->insert($dataHistory);
				}
			
			}
		
		
			if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
				$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
			}else{
				$this->_helper->redirector('productcatalog','calculation',null,array('id' => $v['id']));
			}		
		
		}	
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 


	}



	
	
	public function productcatalogeditv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$Product = new Product();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		$Client = new Client();
		$select = $Client->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('client_activ_product = ?', 1);	
		$row = $Client->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->clientData = $row;
		
		
		
		$select = $Product->select();
		$select->where('client_id = ?', $v['id']);
		$select->where('product_id = ?', $v['idp']);	
		$row = $Product->fetchRow($select);
		
		if( !$row ){
			$this->_helper->redirector('product','calculation');			
		}
		
		$this->view->productData = $row;
		
		
		
		
		
		

		$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('product_history',array('COUNT(product_history_id) as count', 'product_history_id'))->join('admin', 'product_history.admin_id = admin.admin_id')->where('product_id = ?', $v['idp']);
		if( isset($search) ) $select->where($search);
		$select->order(array('product_history.product_history_ins DESC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];
		
		$Lib_Page = new Lib_Page();
		$Lib_Page->setLimit( $limit );
		$Lib_Page->setLimitPage( $limitpage );
		$Lib_Page->setMax( $dataCount );
		$Lib_Page->setActualId( $page );
		$Lib_Page->setController('calculation');
		$Lib_Page->setAction('productcatalogedit');
		$Lib_Page->setGet('/id/'.$v['id'].'/idp/'.$v['idp']);
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;	
		
		
		$select = $db->select();
		$select->from('product_history')->join('admin', 'product_history.admin_id = admin.admin_id')->where('product_id = ?', $v['idp']);
		if( isset($search) ) $select->where($search);
		$select->order(array('product_history.product_history_ins DESC'))->limit($limit,$p);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$this->view->dataTableProductHistory = $data;
		
		
		
		
		
		
		
		
		if( isset($v['calculation_editproduct']) ){	
		
			$ProductGroup = new ProductGroup();
			$select = $ProductGroup->select();
			$select->where('product_group_id = ?', $v['product_group_id']);
			$rowGroup = $ProductGroup->fetchRow($select);
		
			$v['product_nc'] = isset($v['product_nc'])?$v['product_nc']:'0';
			$v['product_company_id'] = $rowGroup['product_company_id'];
			
			$data = array(
				'product_group_id' => $v['product_group_id'],
				'product_company_id' => $rowGroup['product_company_id'],
				'product_name' => $v['product_name'],
				'product_notice' => $v['product_notice'],
				'product_nr' => $v['product_nr'],
				'product_price' => isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00',	
				'product_unit_id' => $v['product_unit_id'],	
				'product_nc' => isset($v['product_nc'])?$v['product_nc']:'0',	
				'product_edit' => Lib_Date::datetime(),
				'product_activ' => $v['product_activ']
			);
			$Product->update($data,"client_id = ".$v['id']." AND product_id = ".$v['idp']);
			
			// zapis historii
			$ProductHistory = new ProductHistory();
			
			$v['product_price'] = isset($v['product_price'])?str_replace(",",".",$v['product_price']):'0.00';
			$field = array(
				'product_group_id',
				'product_company_id',
				'product_name',
				'product_notice',
				'product_nr',
				'product_price',	
				'product_unit_id',	
				'product_nc',	
				'product_activ'
			);
		/*	
		*/
		
			foreach( $field as $k => $val ){
			
				if( $row->$val != $v[$val] ){
					$dataHistory = array(
						'product_id' => $v['idp'],
						'admin_id' => $admin->admin_id,
						'product_history_field' => $val,
						'product_history_value_old' => $row->$val,
						'product_history_value_new' => $v[$val],
						'product_history_ins' => Lib_Date::datetime()
					);
					$ProductHistory->insert($dataHistory);
				}
			
			}
		
		
			if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
				$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
			}else{
				$this->_helper->redirector('productcatalogv2','calculation',null,array('id' => $v['id']));
			}		
		
		}	
		
		
		
		
		// budowanie drzewa kategorii
	
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		*/
		
		
		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompany( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 


	}
	
	public function productcheckcodeAction() {
		header("Content-Type:text/plain");
		$this->_helper->viewRenderer->setNoRender();
		$v = $this->_request->getParams();
		$valid = 0;
		// $valid = 0 - nie istnieje w bazie
		// $valid = 1 - istnieje w bazie
		
		$Product = new Product();	
		$select = $Product->select();		
//		$select->where("client_id = '".$v['id']."'");	
		$select->where("product_nr LIKE '".$v['d']."'");					
		$row = $Product->fetchRow($select);
		unset($Product);		

		if( $row ){
			$valid = 1;
		}else{
			$valid = 0;
		}
		
		echo $valid;
	}








	
	
	
	public function groupAction() {	
		$this->_helper->redirector('product','calculation');
			
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();		
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 
		
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']]['product_group_name'] = $val['product_group_name'];
			$d2[$val['product_group_id']]['product_group_child'] = $val['product_group_child'];
			$d2[$val['product_group_id']]['product_group_parent_id'] = $val['product_group_parent_id'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']]['product_group_name'] = "&emsp;&rarr; ".$val2['product_group_name'];
					$d2[$val2['product_group_id']]['product_group_child'] = $val2['product_group_child'];
					$d2[$val2['product_group_id']]['product_group_parent_id'] = $val2['product_group_parent_id'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 

		if( $_GET['viewList'] == true ){
			ob_start();
			var_dump(Lib_Calculation::categoryProductCompany(1));
			echo nl2br(ob_get_clean());
		}
	}








	
	
	
	public function groupv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$db = Zend_Registry::get('db');	
		$v = $this->_request->getParams();
		
		if( !isset($v['id']) ){
			$this->_helper->redirector('index','calculation');			
		}
		
		$ProductCompany = new ProductCompany();
		$select = $ProductCompany->select();
		$select->where('product_company_id = ?', $v['id']);
		$pgData = $ProductCompany->fetchRow($select);
		$this->view->product_company_info = $pgData;	

		$dataProductGroup = Lib_Calculation::categoryProductCompany($v['id']);
		$this->view->dataProductGroup = $dataProductGroup;	
	}








	
	
	
	public function groupaddAction() {	
		$this->_helper->redirector('product','calculation');
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		$ProductGroup = new ProductGroup();	
		
		
		if( isset($v['calculation_addgroup']) ){	
		
			if( $v['product_group_type'] == 1 ){
				$data = array(
					'product_company_id' => 1,
					'product_group_name' => $v['product_group_name'],
					'product_group_child' => 0,
					'product_group_parent_id' => 0
				);
			}
		
			if( $v['product_group_type'] == 2 ){
				$data = array(
					'product_company_id' => 1,
					'product_group_name' => $v['product_group_name'],
					'product_group_child' => 1,
					'product_group_parent_id' => 0
				);
			}
		
			if( $v['product_group_type'] == 3 ){
				$data = array(
					'product_company_id' => 1,
					'product_group_name' => $v['product_group_name'],
					'product_group_child' => 0,
					'product_group_parent_id' => $v['product_group_id']
				);
			}
			
			$ProductGroup->insert($data);
			
			$this->_helper->redirector('group','calculation');
				
		
		}		
		
		$data = $ProductGroup->fetchAll("product_group_child = 1", " product_group_name ASC "); 		
		$this->view->productgroupList = $data;
		
	}








	
	
	
	public function groupaddv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$db = Zend_Registry::get('db');	
		$v = $this->_request->getParams();
		
		if( !isset($v['id']) ){
			$this->_helper->redirector('index','calculation');			
		}
		
		$ProductCompany = new ProductCompany();
		$select = $ProductCompany->select();
		$select->where('product_company_id = ?', $v['id']);
		$pgData = $ProductCompany->fetchRow($select);
		$this->view->product_company_info = $pgData;	
		
		
		$ProductGroup = new ProductGroup();	
		
		
		if( isset($v['calculation_addgroup']) ){		
		
			$data = array(
				'product_company_id' => $v['id'],
				'product_group_name' => $v['product_group_name'],
				'product_group_child' => 0,
				'product_group_parent_id' => $v['product_group_parent_id']
			);
			
			$ProductGroup->insert($data);
			
			$this->_helper->redirector('groupv2','calculation',null,array('id' => $v['id']));
		
		}				

		$dataProductGroup = Lib_Calculation::categoryProductCompany($v['id']);
		$this->view->dataProductGroup = $dataProductGroup;	
		
	}








	
	
	
	public function groupeditAction() {	
		$this->_helper->redirector('product','calculation');
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		$ProductGroup = new ProductGroup();	
		
		
		if( isset($v['calculation_editgroup']) ){	
				
			$data = array(
				'product_group_name' => $v['product_group_name']
			);
			
			$ProductGroup->update($data,"product_group_id = ".$v['id']);
			
			$this->_helper->redirector('group','calculation');
				
		
		}		
		
		$select = $ProductGroup->select();			
		$select->where("product_group_id = ".$v['id']."");					
		$row = $ProductGroup->fetchRow($select);		
		$this->view->productgroup = $row;
		
	}








	
	
	
	public function groupeditv2Action() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtrcalculation = new Zend_Session_Namespace('filtrcalculation');
		
		$db = Zend_Registry::get('db');	
		$v = $this->_request->getParams();
		
		if( $information->errorParent ){
			$this->view->errorParent = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( !isset($v['id']) ){
			$this->_helper->redirector('index','calculation');			
		}			
		
		$ProductGroup = new ProductGroup();			
		$select = $ProductGroup->select();			
		$select->where("product_group_id = ".$v['id']."");					
		$row = $ProductGroup->fetchRow($select);		
		$this->view->productgroup = $row;
		
		$ProductCompany = new ProductCompany();
		$select = $ProductCompany->select();
		$select->where('product_company_id = ?', $row['product_company_id']);
		$pgData = $ProductCompany->fetchRow($select);
		$this->view->product_company_info = $pgData;
		
		if( isset($v['calculation_editgroup']) ){	
		
			if( Lib_Calculation::checkParent($v['id'],$v['product_group_parent_id']) == false ){				
				$information->errorParent = true;
				$this->_helper->redirector('groupeditv2','calculation',null,array('id' => $v['id']));	
			}else{
				$data = array(
					'product_group_name' => $v['product_group_name'],
					'product_group_parent_id' => $v['product_group_parent_id']
				);
				
				$ProductGroup->update($data,"product_group_id = ".$v['id']);
				
				$this->_helper->redirector('groupv2','calculation',null,array('id' => $row['product_company_id']));	
			}
		
		}		
		
		$dataProductGroup = Lib_Calculation::categoryProductCompany($row['product_company_id']);
		$this->view->dataProductGroup = $dataProductGroup;	
	}
	
	
	
	public function projecteditAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');		

		$Project = new Project();	
		$Client = new Client();	
		$ProjectFile = new ProjectFile();	
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		
		if( $information->addEmployeeProjectSuccess ){
			$this->view->addEmployeeProjectSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->addProjectFileSuccess ){
			$this->view->addProjectFileSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->removeSuccess ){
			$this->view->removeSuccess = true;
			Zend_Session::namespaceUnset('information');			
		}
		
			
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		if( isset($v['projectemp_edit']) ){	
		
			if( $v['project_h'] == null ) $h = -1;
			else $h = $v['project_h'];
		
			if( $v['project_m2'] == null ) $m2 = -1;
			else $m2 = $v['project_m2'];
			
			$data = array(
				'project_nr' => isset($v['project_nr'])?$v['project_nr']:'',
				'project_h' => $h,
				'project_m2' => $m2,
				
				'project_employee_name' => isset($v['project_employee_name'])?$v['project_employee_name']:'',
				'project_employee_phone' => isset($v['project_employee_phone'])?$v['project_employee_phone']:'',
				
				'project_employee_manager_name' => isset($v['project_employee_manager_name'])?$v['project_employee_manager_name']:'',
				'project_employee_manager_phone' => isset($v['project_employee_manager_phone'])?$v['project_employee_manager_phone']:'',
				
				'project_employee_cetla_name' => isset($v['project_employee_cetla_name'])?$v['project_employee_cetla_name']:'',
				'project_employee_cetla_phone' => isset($v['project_employee_cetla_phone'])?$v['project_employee_cetla_phone']:'',
				
				'project_status_finish' => isset($v['project_status_finish'])?$v['project_status_finish']:0,
				'project_status_calc' => isset($v['project_status_calc'])?$v['project_status_calc']:0,
				
				'project_client_id_main' => isset($v['project_client_id_main'])?$v['project_client_id_main']:0,
				
				'project_date_start' => Lib_Date::convertDate($v['project_date_start'],"d-m-Y","Y-m-d"),
				'project_date_stop' => Lib_Date::convertDate($v['project_date_stop'],"d-m-Y","Y-m-d"),
				
				'project_status' => $v['project_status'],
				'project_edit' => Lib_Date::datetime()
			);
			$Project->update($data, "project_id = ".$v['id']."" );
			
			$information->addEmployeeProjectSuccess = true; 
			$this->_helper->redirector('projectedit','calculation',null,array('id' => $v['id']));	
		}		
		
		
		if( isset($v['admin_addprojectdocuments']) ){
		
			$upload_path = "projectdocuments/";
			$filename_name = $admin->admin_id.'_'.$v['id'].'_'.hash('sha256',$admin->admin_id.time().rand(0,100000));
			move_uploaded_file($_FILES["project_file"]["tmp_name"], $upload_path.$filename_name);
		
			$data = array(
				'project_id' => $v['id'],
				'project_file_type' => $v['project_file_type'],
				'project_file_filename' => $_FILES["project_file"]["name"],
				'project_file_filesize' => $_FILES["project_file"]["size"],
				'project_file_filetype' => $_FILES["project_file"]["type"],
				'project_file_file' => $filename_name,
				'project_file_ins' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
		//	var_dump($data);die();
			$idInsDA = $ProjectFile->insert($data);	
			
			$information->addProjectFileSuccess = true; 
			$this->_helper->redirector('projectedit','calculation',null,array('id' => $v['id']));	
		}
		
		
		
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$select->where('project_activ_settlement = ?', 1);	
		$row = $Project->fetchRow($select);
		$this->view->projectData = $row;
		
		
		$data = $Client->fetchAll('client_activ_main_project = 1 OR client_id = '.$row['project_client_id_main'] , 'client_name ASC'); 	
		$this->view->clientData = $data;
		
		
		$select = $db->select();
		$select->from('project_file')->join('admin', 'project_file.admin_id = admin.admin_id');
		$select->where('project_file.project_file_type = 0');
		$select->where('project_file.project_id = '.$v['id']);
		$select->order(array('project_file.project_file_id ASC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$this->view->ProjectFile0 = $data;
				
		$select = $db->select();
		$select->from('project_file')->join('admin', 'project_file.admin_id = admin.admin_id');
		$select->where('project_file.project_file_type = 1');
		$select->where('project_file.project_id = '.$v['id']);
		$select->order(array('project_file.project_file_id ASC'));  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();
		$this->view->ProjectFile1 = $data;
		
		
		if( !$row ) $this->_helper->redirector('index','index');	
		
		
	
	}
	
	public function projectfileopenAction(){
		$admin = new Zend_Session_Namespace('admin');
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');
		
		$ProjectFile = new ProjectFile();
		$select = $ProjectFile->select();
		$select->where('project_file_id = ?', $v['id']);	
		$row = $ProjectFile->fetchRow($select);
		
		if ( isset($row->project_file_file) ) { 
			
			$countVisit = $row['project_file_views']+1;
			$data = array(
				'project_file_views' => $countVisit
			);
			$ProjectFile->update( $data , 'project_file_id='.$v['id'] );

		
			$file = 'projectdocuments/'.$row->project_file_file;
			header('Content-Type: '.$row->project_file_filetype);
			header('Content-Disposition: inline; filename="'.$row->project_file_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 projectfileremoveAction() {	
		$v = $this->_request->getParams();		
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		
		$ProjectFile = new ProjectFile();
		$where = array(
			'project_id = ?' => $v['id'],
			'project_file_id = ?' => $v['idf']
		);

		$ProjectFile->delete($where);	
		$information->removeSuccess = true; 
		$this->_helper->redirector('projectedit','calculation',null,array('id' => $v['id']));			
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*
	
		KALKULUJ
	
	*/
	
	
	
	public function calculationAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');		

		$Project = new Project();
		$EmployeeSettlement = new EmployeeSettlement();		
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$select->where('project_activ_settlement = ?', 1);	
		$row = $Project->fetchRow($select);
		$this->view->projectData = $row;
		
		if( !$row ) $this->_helper->redirector('index','index');	
		
		if( isset($v['moduleopen']) ){
			$this->view->moduleopen = $v['moduleopen'];
		}
	}
	
	
	
	
	public function calculationmainAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
	//	echo'calculationmain';
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			die();	
		}
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p,
			product_group pg,
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	
		
	//	var_dump($v['data']);
		
		$this->view->dataTableCheck = $v['data'];	
		
		
		// budowanie drzewa kategorii
		
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  
		*/

		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompanyNU( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;		
		
		/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		*/
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];

	}
	
	
	
	
	public function calculationmainaddproductorderAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
	//	echo'calculationmain';
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
	
		$Order = new Order();
		$select = $Order->select();
		$select->where('order_id = ?', $v['ido']);
		$row = $Order->fetchRow($select);
		$this->view->orderData = $row;
	
	/*
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p, 
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			c.client_name ASC,
			p.product_name ASC		
		";

*/		
		$ask = "
SELECT *
FROM `product_project` pp
LEFT JOIN `order_product` op ON ( pp.product_id = op.product_id AND op.order_id = ".$v['ido']." ),
product p,			 
client c, 
product_unit pu
WHERE 
p.product_id = pp.product_id
AND
p.product_unit_id = pu.product_unit_id 
AND
p.client_id = c.client_id
AND
pp.project_id = ".$v['id']."
AND 
op.order_id IS NULL	
ORDER BY
c.client_name ASC,
p.product_name ASC
		";
		
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	
		
		
		
		
		// budowanie drzewa kategorii
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		*/
		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompanyNU( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];
	}
	
	
	
	
	public function calculationmainallprintAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
	//	echo'calculationmain';
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();	
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$rowProject = $Project->fetchRow($select);
		$this->view->projectData = $rowProject;
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $rowProject->company_id);
		$rowCompany = $Company->fetchRow($select);
		$this->view->companyData = $rowCompany;
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p, 
			product_group pg,
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	
		
		
		
		
		
		// budowanie drzewa kategorii
		
		/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  
		*/
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];

		$this->view->sum_include = $v['sum_include'];
		$this->view->difference_include = $v['difference_include'];
		$this->view->cost = $v['cost'];
	}
	
	
	
	
	public function calculationorderAction() {	
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			die();	
		}
		
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtr = new Zend_Session_Namespace('filtrorder'.$v['id']);	
		$db = Zend_Registry::get('db');
		
		
		if( isset($vPost['filtr_order_nameadmin']) ){
			$filtr->filtr_order_nameadmin = $vPost['filtr_order_nameadmin'];
			if( $filtr->filtr_order_nameadmin == 'all' ){
				unset($filtr->filtr_order_nameadmin);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_name']) ){
			$filtr->filtr_order_name = $vPost['filtr_order_name'];
			if( $filtr->filtr_order_name == 'all' ){
				unset($filtr->filtr_order_name);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_status']) ){
			$filtr->filtr_order_status = $vPost['filtr_order_status'];
			if( $filtr->filtr_order_status == 'all' ){
				unset($filtr->filtr_order_status);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_pay']) ){
			$filtr->filtr_order_pay = $vPost['filtr_order_pay'];
			if( $filtr->filtr_order_pay == 'all' ){
				unset($filtr->filtr_order_pay);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_nr']) ){
			$filtr->filtr_order_nr = $vPost['filtr_order_nr'];
			if( $filtr->filtr_order_nr == '' ){
				unset($filtr->filtr_order_nr);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_product']) ){
			$filtr->filtr_order_product = $vPost['filtr_order_product'];
			if( $filtr->filtr_order_product == 'all' ){
				unset($filtr->filtr_order_product);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		
		if( isset($vPost['filtr_order_client']) ){
			$filtr->filtr_order_client = $vPost['filtr_order_client'];
			$filtr->filtr_client_id_filtr = true;			
			if( $filtr->filtr_order_client == 'all' ){
				unset($filtr->filtr_order_client);
				unset($filtr->filtr_client_id_filtr);
			}
			$filtr->filtr_page[$v['id']] = 1;
		}
		/*
		echo$filtr->filtr_order_name;
		echo$filtr->filtr_order_status;
		echo$filtr->filtr_order_nr;
		*/
		$limit = 10;
		$limitpage = 10;
		
		$order = array('order_realization DESC','order_ins DESC','order_edit DESC');

		$page = $this->_request->getParams();
			
		if( isset($page['page']) ) $filtr->filtr_page[$v['id']] = $page['page'];
		if( !isset($filtr->filtr_page[$v['id']]) ) $filtr->filtr_page[$v['id']] = 1;
		
		$page = $filtr->filtr_page[$v['id']];
	/*	
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
	*/	
		$p = ($page-1)*$limit;	
		
		
		
		$select = $db->select();
		
		if( $filtr->filtr_order_product ){
			$select->from('order',array('COUNT(order.order_id) as count', 'order.order_id'))->join('order_product', 'order.order_id = order_product.order_id')->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
			$select->where('product_id = '.$filtr->filtr_order_product);
		}
		else{			
			$select->from('order',array('COUNT(order.order_id) as count', 'order.order_id'))->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
		}				
		
		$select->where('project_id = '.$v['id']); 	 		
		if( $filtr->filtr_order_nameadmin ) $select->where('admin.admin_id = '.$filtr->filtr_order_nameadmin);	
		if( $filtr->filtr_order_name ) $select->where('employee.employee_id = '.$filtr->filtr_order_name);	 
		if( $filtr->filtr_order_status ) $select->where('order.order_status = '.($filtr->filtr_order_status-1));
		if( $filtr->filtr_order_pay ) $select->where('order.order_pay = '.($filtr->filtr_order_pay-1));
		if( $filtr->filtr_order_nr ) $select->where("order.order_nr2 LIKE '".str_replace("*","%",$filtr->filtr_order_nr)."'"); 
		if( isset($filtr->filtr_order_client) ) $select->where('order.order_client_id_main = '.$filtr->filtr_order_client);	 
		$select->order($order);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();	
		$dataCount = $data[0]['count'];		
		
		
		
		
		$select = $db->select();
		
		if( $filtr->filtr_order_product ){
			$select->from('order')->join('order_product', 'order.order_id = order_product.order_id')->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
			$select->where('product_id = '.$filtr->filtr_order_product);
		}
		else{
			$select->from('order')->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
		}		
		
		$select->where('project_id = '.$v['id']); 	
		if( $filtr->filtr_order_nameadmin ) $select->where('admin.admin_id = '.$filtr->filtr_order_nameadmin);	
		if( $filtr->filtr_order_name ) $select->where('employee.employee_id = '.$filtr->filtr_order_name); 
		if( $filtr->filtr_order_status ) $select->where('order.order_status = '.($filtr->filtr_order_status-1));
		if( $filtr->filtr_order_pay ) $select->where('order.order_pay = '.($filtr->filtr_order_pay-1));
		if( $filtr->filtr_order_nr ) $select->where("order.order_nr2 LIKE '".str_replace("*","%",$filtr->filtr_order_nr)."'"); 
		if( isset($filtr->filtr_order_client) ) $select->where('order.order_client_id_main = '.$filtr->filtr_order_client);
		
		$select->order($order)->limit($limit,$p);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();			
		$this->view->dataTable = $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('calculation');
		$Lib_Page->setAction('calculationorder');
		$Lib_Page->setGet('/id/'.$v['id']);
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;	
		
		$this->view->project_id = $v['id'];
		
		$this->view->filtr_order_nameadmin = $filtr->filtr_order_nameadmin;	
		$this->view->filtr_order_name = $filtr->filtr_order_name;		
		$this->view->filtr_order_status = $filtr->filtr_order_status;	
		$this->view->filtr_order_pay = $filtr->filtr_order_pay;		
		$this->view->filtr_order_nr = $filtr->filtr_order_nr;
		$this->view->filtr_order_client = $filtr->filtr_order_client;
		$this->view->filtr_order_product = $filtr->filtr_order_product;
		
		$this->view->filtr_client_id_filtr = $filtr->filtr_client_id_filtr;
		
		$Employee = new Employee();	
		$data = $Employee->fetchAll('employee_activ = 0 AND employee_activ_order = 1' , array('employee_secondname ASC','employee_firstname ASC'));		
		$this->view->dataTableEmployee = $data;
		
		
		$ask = "
			SELECT * FROM 
			`order` o,
			admin a
			WHERE
			a.admin_id = o.admin_id 
			AND
			o.project_id = ".$v['id']."
			GROUP BY o.admin_id
			ORDER BY
			admin_secondname ASC,
			admin_firstname ASC
		";
		$dataAdmin = $db->query($ask)->fetchAll();		
		$this->view->dataTableAdmin = $dataAdmin;
		
		
		$ask = "SELECT order_client_id_main, client_name, COUNT(*) AS count FROM `order` o LEFT JOIN `client` c ON o.order_client_id_main = c.client_id WHERE o.project_id = '".$v['id']."' GROUP BY order_client_id_main";
		$data = $db->query($ask)->fetchAll();		
		$this->view->dataTableClientMain = $data;
		
		
		$ask = "
			SELECT p.product_id AS product_id, product_name, COUNT(*) AS count FROM 
			`order` o,
			`order_product` op,
			`product` p
			WHERE
			o.project_id = '".$v['id']."' AND
			o.order_id = op.order_id AND
			op.product_id = p.product_id
			GROUP BY p.product_id
			ORDER BY p.product_name ASC
		";
		$data = $db->query($ask)->fetchAll();		
		$this->view->dataTableProduct = $data;	
	}
	
	
	
	
	public function calculationorderaddfinishAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		$ask = "SELECT MAX( `order_nr` ) AS nr FROM `order` WHERE project_id = '".$v['id']."'";
		$order = $db->query($ask)->fetchAll();	
		if( !$order ) $nrnew = 1;
		else{
			$nrnew = $order[0]['nr']+1;
		}
		
		$Order = new Order();
		$OrderProduct = new OrderProduct();
		
		if( $vPost['order_realization'] == '' ) $vPost['order_realization'] = '0000-00-00';
		else{
			$vPost['order_realization'] = Lib_Date::convertDate($vPost['order_realization'],"d-m-Y","Y-m-d");
		}
		
		$data = array(
			'order_nr' => $nrnew,
			'project_id' => $v['id'],
			'employee_id' => $vPost['employee_id'],
			'order_realization' => $vPost['order_realization'],
			'order_notice' => $vPost['order_notice'],
			'order_status' => $vPost['order_status'],
			'order_client_id_main' => isset($v['order_client_id_main'])?$v['order_client_id_main']:0,
			'order_afterProject' => isset($v['order_afterProject'])?$v['order_afterProject']:0,
			'order_ins' => Lib_Date::datetime(),
			'order_edit' => Lib_Date::datetime(),
			'admin_id' => $admin->admin_id
		);		
	//	var_dump($data);
	//	die();
		
		$idIns = $Order->insert($data);
		
		foreach( $vPost['project_order_product'] as $key => $val ){
			$data = array(
				'order_id' => $idIns,
				'product_id' => $key,
				'order_product_price' => str_replace(",",".",$vPost['order_product_price'][$key]),
				'order_product_count' => str_replace(",",".",$vPost['project_order_product_count'][$key]),
				'order_product_notice' => $vPost['project_order_product_note'][$key]
			);
			$OrderProduct->insert($data);
		}
		
		$this->_helper->viewRenderer->setNoRender();

		if( $v['calculationorderadd2_button'] == true ) $this->_helper->redirector('calculation','calculation',null,array('id' => $v['id'],'moduleopen' => 'calculationmainaddproductorder/id/'.$v['id'].'/ido/'.$idIns));
		else $this->_helper->redirector('calculation','calculation',null,array('id' => $v['id'],'moduleopen' => 'calculationorder'));
	}
	
	
	
	
	
	
	
	public function calculationorderremoveAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		$this->_helper->viewRenderer->setNoRender();
		
		$Order = new Order();
		
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		
		if( Lib_Permission::getPermissionProjectCalc( $row['project_id'] ) != 1 ){	
			die();		
		}
		
		
		$where = array(
			'order_id = ?' => $v['id']
		);
		$Order->delete($where);	
		
		
		if( $v['return'] AND $v['return_n'] AND $v['return_id'] ){
			$this->_helper->redirector($v['return'],'calculation',null,array($v['return_n'] => $v['return_id']));
		}else{
			$this->_helper->redirector('calculation','calculation',null,array('id' => $v['project_id'],'moduleopen' => 'calculationorder'));
		}
	}
	
	public function calculationordereditfinishAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		$Order = new Order();
		$OrderProduct = new OrderProduct();
		
		
		
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		
		if( Lib_Permission::getPermissionProjectCalc( $row['project_id'] ) != 1 ){	
			die();		
		}
		
		
		
		if( $vPost['order_realization'] == '' ) $vPost['order_realization'] = '0000-00-00';
		else{
			$vPost['order_realization'] = Lib_Date::convertDate($vPost['order_realization'],"d-m-Y","Y-m-d");
		}
		
		$data = array(
			'employee_id' => $vPost['employee_id'],
			'order_realization' => $vPost['order_realization'],
			'order_nr2' => $vPost['order_nr2'],
			'order_notice' => $vPost['order_notice'],
			'order_pay' => isset($vPost['order_pay'])?$vPost['order_pay']:0,
			'order_paypartial' => isset($vPost['order_paypartial'])?$vPost['order_paypartial']:0,
			'order_nmz' => isset($vPost['order_nmz'])?$vPost['order_nmz']:0,
			'order_rabat' => isset($vPost['order_rabat'])?$vPost['order_rabat']:0,
			'order_status' => $vPost['order_status'],
			'order_client_id_main' => isset($v['order_client_id_main'])?$v['order_client_id_main']:0,
			'order_afterProject' => isset($v['order_afterProject'])?$v['order_afterProject']:0,
			'order_edit' => Lib_Date::datetime()
		);		
		$Order->update($data,"order_id = ".$v['id']);
		
		$where = array(
			'order_id = ?' => $v['id']
		);
		$OrderProduct->delete($where);
		
		foreach( $vPost['project_order_product'] as $key => $val ){
			$data = array(
				'order_id' => $v['id'],
				'product_id' => $key,
				'order_product_price' => str_replace(",",".",$vPost['order_product_price'][$key]),
				'order_product_count' => str_replace(",",".",$vPost['project_order_product_count'][$key]),
				'order_product_notice' => $vPost['project_order_product_note'][$key]
			);
			$OrderProduct->insert($data);
		}
		
		$this->_helper->viewRenderer->setNoRender();

		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		$project_id = $row['project_id'];
	
		$this->_helper->redirector('calculation','calculation',null,array('id' => $project_id,'moduleopen' => 'calculationorder'));
	}
	
	
	
	
	public function calculationorderaddAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		$where = '';
		$i = -1;
		foreach( $vPost['data'] as $key => $val ){
			$i++;
			if( $i == 0 ) $where = $where.'p.product_id = '.$key;
			else $where = $where.' OR p.product_id = '.$key;
		}
		
		$where = ' AND ('.$where.')';
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p, 
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			".$where."
			ORDER BY
			c.client_name ASC,
			p.product_name ASC		
		";
		
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	

		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  
/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
*/
		$this->view->categoryListFull = Lib_Calculation::categoryProductListFull(); 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];
		$this->view->product_count = $vPost['data'];		
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$select->where('project_activ_settlement = ?', 1);	
		$row = $Project->fetchRow($select);
		$this->view->projectData = $row;
			
		$Employee = new Employee();	
		$data = $Employee->fetchAll('employee_activ = 0 AND employee_activ_order = 1' , array('employee_secondname ASC','employee_firstname ASC'));		
		$this->view->dataTableEmployee = $data;	

		$Client = new Client();	
		$data = $Client->fetchAll('client_activ_main_order = 1' , 'client_name ASC'); 	
		$this->view->clientData = $data;
	}
	
	
	
	
	public function calculationordereditAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
	
		$Order = new Order();
		$OrderProduct = new OrderProduct();
		
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		
		if( Lib_Permission::getPermissionProjectCalc( $row['project_id'] ) != 1 ){	
			die();		
		}
		
		
		if( $v['operation'] == 'addproduct' ){
		
			
			foreach( $v['data'] as $key => $val ){
				unset($data);
				$data = array(
					'order_id' => $v['id'],
					'product_id' => $key,
					'order_product_price' => str_replace(",",".",$v['datap'][$key]),
					'order_product_count' => str_replace(",",".",$val),
					'order_product_notice' => ''
				);
				$OrderProduct->insert($data);
		//	var_dump($data);
			}
			
		
		}
		
		
		
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		$this->view->orderData = $row;
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = ".$v['id']."
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			AND
			pp.project_id = '".$row->project_id."'
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
	//	echo$ask;
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	

		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
*/
		$this->view->categoryListFull = Lib_Calculation::categoryProductListFull(); 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];
		$this->view->product_count = $vPost['data'];
			
		$Employee = new Employee();	
		$data = $Employee->fetchAll('employee_activ = 0 AND employee_activ_order = 1' , array('employee_secondname ASC','employee_firstname ASC'));		
		$this->view->dataTableEmployee = $data;	
		
		
		$OrderFiles = new OrderFiles();
		$data = $OrderFiles->fetchAll('order_id = '.$v['id'] , array('order_files_ins  DESC'));		
		$this->view->dataTableOrderFiles = $data;

		$Client = new Client();	
		$data = $Client->fetchAll('client_activ_main_order = 1 OR client_id = '.$row['order_client_id_main'] , 'client_name ASC'); 	
		$this->view->clientData = $data;	
	}
	
	
	
	
	public function calculationorderaddfileAction() {	
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
	
		if( isset($v['calculationorderaddfile_button']) ){
		
			$upload_path = "orderdocuments/";
			$filename_name = $admin->admin_id.'_'.$v['id'].'_'.$v['ido'].'_'.hash('sha256',$admin->admin_id.time().rand(0,100000));
			move_uploaded_file($_FILES["order_files_file"]["tmp_name"], $upload_path.$filename_name);
			
			
			
			$OrderFiles = new OrderFiles();
			$data = array(
				'order_id' => $v['ido'],
				'order_files_filename' => $_FILES["order_files_file"]["name"],
				'order_files_filesize' => $_FILES["order_files_file"]["size"],
				'order_files_filetype' => $_FILES["order_files_file"]["type"],
				'order_files_file' => $filename_name,
				'order_files_notice' => $v['order_files_notice'],
				'order_files_ins' => Lib_Date::datetime(),
				'admin_id' => $admin->admin_id
			);
			$idInsDA = $OrderFiles->insert($data);
	
			header("location: ".WWW_PATH."/calculation/calculation/id/".$v['id']."?moduleopen=calculationorderedit/id/".$v['ido']);
			
		//	$this->_helper->redirector('calculation','calculation',null,array('id' => $project_id,'moduleopen' => 'calculationorderedit').'?test=1');
			
		}
	}
	
	
	
	
	public function calculationorderfileremoveAction() {	
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		$OrderFiles = new OrderFiles();
		$where = array(
			'order_files_id = ?' => $v['idf']
		);
		$OrderFiles->delete($where);
	
		header("location: ".WWW_PATH."/calculation/calculation/id/".$v['id']."?moduleopen=calculationorderedit/id/".$v['ido']);
	
	}
	
	
	public function openAction(){
		$admin = new Zend_Session_Namespace('admin');
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');
		
		$OrderFiles = new OrderFiles();
		$select = $OrderFiles->select();
		$select->where('order_files_id = ?', $v['id']);	
		$row = $OrderFiles->fetchRow($select);
				
		if ( isset($row->order_files_file) ) { 
			
			if( !$information->views ){
				$countVisit = $row['order_files_views']+1;
				$data = array(
					'order_files_views' => $countVisit
				);
				$OrderFiles->update( $data , 'order_files_id='.$v['id'] );
				$information->views = true;
			}
		
			$file = 'orderdocuments/'.$row->order_files_file;
			header('Content-Type: '.$row->order_files_filetype);
			header('Content-Disposition: inline; filename="'.$row->order_files_filename.'"');
			header('Content-Length: '.filesize($file));	
	
			ob_clean();
			flush();
			@readfile($file);
			exit;
		}else{
			$information->openDocumentsError = true; 
			$this->_helper->redirector('index','calculation');			
		}
		
        $this->_helper->viewRenderer->setNoRender();
	}
	
	
	
	
	public function calculationorderprintAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
	
		$Order = new Order();
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		$this->view->orderData = $row;
		
		if( Lib_Permission::getPermissionProjectCalc( $row['project_id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $row->project_id);
		$rowProject = $Project->fetchRow($select);
		$this->view->projectData = $rowProject;
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $rowProject->company_id);
		$rowCompany = $Company->fetchRow($select);
		$this->view->companyData = $rowCompany;
	
		$this->view->project_id = $row->project_id;
		/*
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			`order` o,	
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			o.order_id = ".$v['id']."
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			c.client_name ASC,
			p.product_name ASC		
		";
		*/
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = ".$v['id']."
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			AND
			pp.project_id = '".$row->project_id."'
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
	//	echo$ask;
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	

		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d; 
		
		/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		*/
		$this->view->categoryListFull = Lib_Calculation::categoryProductListFull(); 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->order_id = $v['id'];
		
		$Employee = new Employee();	
		$data = $Employee->fetchAll('employee_activ = 0 AND employee_activ_order = 1' , array('employee_secondname ASC','employee_firstname ASC'));		
		$this->view->dataTableEmployee = $data;		
		
		$this->view->noprint = $v['noprint'];	
	}
	
	
	
	
	public function calculationorderallprintAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$rowProject = $Project->fetchRow($select);
		$this->view->projectData = $rowProject;
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $rowProject->company_id);
		$rowCompany = $Company->fetchRow($select);
		$this->view->companyData = $rowCompany;
				
		$order = array('order_ins DESC','order_edit DESC');	
		
		$select = $db->select();
		$select->from('order')->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
		$select->where('project_id = '.$v['id']); 	 
		$select->order($order);  
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();			
		$this->view->dataTable = $data;		
		
		$this->view->project_id = $v['id'];
		$this->view->include_order = $v['include_order'];
	}
	
	
	
	
	public function calculationrequestAction() {	
	
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
	//	echo'calculationrequest';
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			die();	
		}
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p 
			LEFT JOIN product_project pp
			ON pp.product_id = p.product_id AND pp.project_id = ".$v['id'].", 
			client c, 
			product_unit pu,
			product_group pg
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			AND
			p.product_activ = 0
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	
			
			
		
		
		
		// budowanie drzewa kategorii
		
	/*
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
	*/

		
		$ProductCompany = new ProductCompany();
		$dataCompany = $ProductCompany->fetchAll(null, "product_company_name ASC ")->toArray(); 		

		foreach( $dataCompany as $key => $val ){
			$dataCompany[$key]['d'] = Lib_Calculation::categoryProductCompanyNU( $val['product_company_id'] );
		}
		
		$this->view->dataTableCompanyGroup = $dataCompany;
	
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];
		
	}
	
	
	
	
	public function calculationrequestv2Action() {	
	
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
	//	echo'calculationrequest';
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p 
			LEFT JOIN product_project pp
			ON pp.product_id = p.product_id AND pp.project_id = ".$v['id'].", 
			client c, 
			product_unit pu,
			product_group pg
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			AND
			p.product_activ = 0
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$data = $db->query($ask)->fetchAll();
				
		$this->view->dataTable = $data;	
			
			
		
		
		
		// budowanie drzewa kategorii
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::clientProduct();
		$this->view->clientList = $d; 
	
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
		$this->view->project_id = $v['id'];
		
	}
	
	
	
	
	public function calculationrequestaddproductAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		$db = Zend_Registry::get('db');
		$this->_helper->viewRenderer->setNoRender();
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		$ProductProject = new ProductProject();
		$ProductProjectHistory = new ProductProjectHistory();
		
		$select = $ProductProject->select();
		$select->where('project_id = ?', $v['id']);	
		$select->where('product_id = ?', $v['pid']);	
		$row = $ProductProject->fetchRow($select);
		
		
		
		$v['price'] = isset($v['price'])?str_replace(",",".",$v['price']):'0.00';
		$v['count'] = isset($v['count'])?str_replace(",",".",$v['count']):'0.00';
		$cost = $v['price']*$v['count'];
		
		
		if( $row AND $v['count'] < 0 ){
		
			$where = array(
				'product_project_id = ?' => $row->product_project_id
			);
			$ProductProject->delete($where);
		
		}else if( $row ){
		
			$data = array(
				'project_id' => $v['id'],
				'product_id' => $v['pid'],
				'product_project_price' => $v['price'],
				'product_project_cost' => $cost,
				'product_project_count' => $v['count'],
				'product_project_edit' => Lib_Date::datetime()
			);
		
			$ProductProject->update($data,"product_project_id = ".$row->product_project_id);		
		}else if( !$row AND $v['count'] >= 0 ){
		
			$data = array(
				'project_id' => $v['id'],
				'product_id' => $v['pid'],
				'product_project_price' => $v['price'],
				'product_project_cost' => $cost,
				'product_project_count' => $v['count'],
				'product_project_ins' => Lib_Date::datetime(),
				'product_project_edit' => Lib_Date::datetime()
			);
		
			$ProductProject->insert($data);
		}
		
		
		$data = array(
			'project_id' => $v['id'],
			'product_id' => $v['pid'],
			'product_project_history_price' => $v['price'],
			'product_project_history_cost' => $cost,
			'product_project_history_count' => $v['count'],
			'product_project_history_ins' => Lib_Date::datetime(),
			'admin_id' => $admin->admin_id
		);
		
		$ProductProjectHistory->insert($data);
		
	}
	
	
	
	
	public function orderAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtr = new Zend_Session_Namespace('filtrorder');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		
		$iFiltr = 0;
		
		if( isset($vPost['filtr_project_id']) ){
			if( $vPost['filtr_project_id'] != 0 ){
				$filtr->filtr_project_id = $vPost['filtr_project_id'];
			}else{
				unset($filtr->filtr_project_id);
			}	
			$iFiltr = 1;
		}
		
		if( isset($vPost['filtr_admin_id']) ){
			if( $vPost['filtr_admin_id'] != 0 ){
				$filtr->filtr_admin_id = $vPost['filtr_admin_id'];
			}else{
				unset($filtr->filtr_admin_id);
			}	
			$iFiltr = 1;
		}
		
		if( isset($vPost['filtr_employee_id']) ){
			if( $vPost['filtr_employee_id'] != 0 ){
				$filtr->filtr_employee_id = $vPost['filtr_employee_id'];
			}else{
				unset($filtr->filtr_employee_id);
			}	
			$iFiltr = 1;
		}
		
		if( isset($vPost['order_date_start']) ){
			if( $vPost['order_date_start'] != '' ){
				$filtr->order_date_start = $vPost['order_date_start'];
			}else{
				unset($filtr->order_date_start);
			}	
			$iFiltr = 1;
		}
		
		if( isset($vPost['order_date_stop']) ){
			if( $vPost['order_date_stop'] != '' ){
				$filtr->order_date_stop = $vPost['order_date_stop'];
			}else{
				unset($filtr->order_date_stop);
			}	
			$iFiltr = 1;
		}
		
		if( isset($vPost['product_name']) ){
			if( $vPost['product_name'] != '' ){
				$filtr->product_name = $vPost['product_name'];
			}else{
				unset($filtr->product_name);
			}	
			$iFiltr = 1;
		}
		
		
		if( $iFiltr != 0 ){
			$this->_helper->redirector('order','calculation');		
		}
		
		
		
		
		
		
	
		$limit = 10;
		$limitpage = 10;

		$page = $this->_request->getParams();
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
		
		$p = ($page-1)*$limit;	
	
		$search1 = '';
		if( isset($filtr->filtr_project_id) ){		
			
			if( Lib_Permission::getPermissionProjectCalc( $filtr->filtr_project_id ) != 1 ){				
				unset($filtr->filtr_project_id);
				$information->permissionError = true;
				$this->_helper->redirector('index','index');		
			}
		
			$search1 = " AND o.project_id = '".$filtr->filtr_project_id."' ";
		}
	
		$search2 = '';
		if( isset($filtr->filtr_admin_id) ){
			$search2 = " AND o.admin_id = '".$filtr->filtr_admin_id."' ";		
		}
	
		$search3 = '';
		if( isset($filtr->filtr_employee_id) ){
			$search3 = " AND o.employee_id = '".$filtr->filtr_employee_id."' ";			
		}
	
		$search4 = '';
		if( isset($filtr->order_date_start) ){
			$search4 = " AND o.order_realization >= '".Lib_Date::convertDate($filtr->order_date_start,"d-m-Y","Y-m-d")."' ";			
		}
	
		$search5 = '';
		if( isset($filtr->order_date_stop) ){
			$search5 = " AND o.order_realization <= '".Lib_Date::convertDate($filtr->order_date_stop,"d-m-Y","Y-m-d")."' ";					
		}
	
		$search6 = '';
		if( isset($filtr->product_name) ){		
			$search6 = " AND p.product_name LIKE '".str_replace("*","%",$filtr->product_name)."' ";				
		}
	
		$search = $search1.$search2.$search3.$search4.$search5.$search6;
	//	echo$search;

		if( $search != '' ){
			$search = $search.' AND '.Lib_Permission::setPermissionProjectCalcSQL('pro.');
		}else{
			$search = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('pro.');		
		}	
	
		$ask = "
SELECT count(op.order_product_id) AS count_order FROM 

`order` o 
LEFT JOIN
order_product op ON o.order_id = op.order_id
LEFT JOIN
product p ON 
(op.product_id = p.product_id)
LEFT JOIN
admin a ON o.admin_id = a.admin_id
LEFT JOIN
employee e ON o.employee_id = e.employee_id
LEFT JOIN
project pro ON pro.project_id = o.project_id
LEFT JOIN
company c ON pro.company_id = c.company_id

WHERE
1 
".$search."
GROUP BY o.order_id
ORDER BY count_order DESC, order_ins DESC		
		";
		
		$data = $db->query($ask)->fetchAll();
		$dataCount = count($data);
	
	
		$ask = "
SELECT o.*, a.*, e.*, pro.*, c.*, count(op.order_product_id) AS count_order FROM 

`order` o 
LEFT JOIN
order_product op ON o.order_id = op.order_id
LEFT JOIN
product p ON 
(op.product_id = p.product_id)
LEFT JOIN
admin a ON o.admin_id = a.admin_id
LEFT JOIN
employee e ON o.employee_id = e.employee_id
LEFT JOIN
project pro ON pro.project_id = o.project_id
LEFT JOIN
company c ON pro.company_id = c.company_id

WHERE
1 
".$search."
GROUP BY o.order_id
ORDER BY order_realization DESC, count_order DESC, order_ins DESC	
LIMIT ".$p.",".$limit."	
		";
		
		$data = $db->query($ask)->fetchAll();
	
		$this->view->orderList = $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('calculation');
		$Lib_Page->setAction('order');
	//	$Lib_Page->setGet('/id/'.$v['id']);
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;
		
		
		
		
		
		
		$ask = "SELECT * FROM `order` o, admin a WHERE a.admin_id = o.admin_id GROUP BY o.admin_id ORDER BY admin_secondname ASC, admin_firstname ASC";
		$data = $db->query($ask)->fetchAll();	
		$this->view->adminList = $data; 
		
		
	
		$ask = "SELECT * FROM `order` o, employee e WHERE e.employee_id = o.employee_id GROUP BY o.employee_id ORDER BY employee_secondname ASC, employee_firstname ASC";
		$data = $db->query($ask)->fetchAll();	
		$this->view->employeeList = $data; 
		
		$ask = "SELECT * FROM `order` o, project p, company c WHERE p.project_id = o.project_id AND p.company_id = c.company_id AND ".Lib_Permission::setPermissionProjectCalcSQL('p.')." GROUP BY o.project_id ORDER BY company_name ASC, project_name ASC";
		$data = $db->query($ask)->fetchAll();	
		$this->view->projectList = $data; 
		
		
		
		
		$this->view->filtr_project_id = $filtr->filtr_project_id; 
		$this->view->filtr_admin_id = $filtr->filtr_admin_id; 
		$this->view->filtr_employee_id = $filtr->filtr_employee_id; 
		$this->view->order_date_start = $filtr->order_date_start; 
		$this->view->order_date_stop = $filtr->order_date_stop; 
		$this->view->product_name = $filtr->product_name; 
		
	}
	
	
	
	
	
	public function orderraportAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtr = new Zend_Session_Namespace('filtrorder');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( isset($vPost['order_raport']) ){
			$this->_helper->redirector('orderraport','calculation',null,array(
				'order_raport_date' => $vPost['order_raport_date'], 
				'order_raport_project_id' => $vPost['order_raport_project_id'], 
				'order_raport_client_id' => $vPost['order_raport_client_id'], 
				'order_raport_employee_id' => $vPost['order_raport_employee_id'], 
				'order_raport_admin_id' => $vPost['order_raport_admin_id']
			));		
		}
		
		if( 
			!isset($v['order_raport_date']) OR
			!isset($v['order_raport_project_id']) OR
			!isset($v['order_raport_client_id']) OR
			!isset($v['order_raport_employee_id']) OR
			!isset($v['order_raport_admin_id']) OR
			$v['order_raport_date'] == ''
		){
			$this->_helper->redirector('orderraport','calculation',null,array(
				'order_raport_date' => date('d-m-Y'), 
				'order_raport_project_id' => 'all', 
				'order_raport_client_id' => 'all', 
				'order_raport_employee_id' => 'all', 
				'order_raport_admin_id' => 'all')
			);
		}
	
	
	
		
		// projekt/budowa
		$ask = "SELECT * FROM `order` o, project p, company c WHERE p.project_id = o.project_id AND p.company_id = c.company_id AND ".Lib_Permission::setPermissionProjectCalcSQL('p.')." GROUP BY o.project_id ORDER BY company_name ASC, project_name ASC";
		$data = $db->query($ask)->fetchAll();	
		$this->view->projectList = $data; 	
	
		// firma budowlana
		$ask = "SELECT o.order_client_id_main AS client_id, c.client_name AS client_name, COUNT(order_id) AS order_count FROM `order` o LEFT JOIN `client` c ON c.client_id = o.order_client_id_main GROUP BY o.order_client_id_main ORDER BY client_name;";
		$data = $db->query($ask)->fetchAll();	
		$this->view->clientOrderList = $data; 
	
		// osoba zamawiajaca
		$ask = "SELECT e.employee_id AS employee_id, e.employee_firstname AS employee_firstname, e.employee_secondname AS employee_secondname, COUNT(order_id) AS order_count FROM `order` o LEFT JOIN `employee` e ON e.employee_id = o.employee_id GROUP BY o.employee_id ORDER BY employee_secondname, employee_firstname;";
		$data = $db->query($ask)->fetchAll();	
		$this->view->employeeOrderList = $data; 
	
		// osoba dodajaca
		$ask = "SELECT * FROM `order` o, admin a WHERE a.admin_id = o.admin_id GROUP BY o.admin_id ORDER BY admin_secondname ASC, admin_firstname ASC";
		$data = $db->query($ask)->fetchAll();	
		$this->view->adminList = $data;
	
	
	
	
	
		$this->view->order_raport_date = $v['order_raport_date'];
		$this->view->order_raport_project_id = $v['order_raport_project_id'];
		$this->view->order_raport_client_id = $v['order_raport_client_id'];
		$this->view->order_raport_employee_id = $v['order_raport_employee_id'];
		$this->view->order_raport_admin_id = $v['order_raport_admin_id'];
		
		
		
		$whereProject = '';
		if( $v['order_raport_project_id'] == 'all' ){
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.');
		}else{
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.').' AND o.project_id = '.(int)$v['order_raport_project_id'];			
		}
		
		
		$whereClient = '';
		if( $v['order_raport_client_id'] == 'all' ){
			$whereClient = '';
		}else if( $v['order_raport_client_id'] == 'null' ){
			$whereClient = ' AND order_client_id_main = 0';		
		}else{
			$whereClient = ' AND order_client_id_main = '.(int)$v['order_raport_client_id'];			
		}
		
		
		$whereEmp = '';
		if( $v['order_raport_employee_id'] == 'all' ){
			$whereEmp = '';
		}else{
			$whereEmp = ' AND o.employee_id = '.(int)$v['order_raport_employee_id'];			
		}
		
		
		$whereAdmin = '';
		if( $v['order_raport_admin_id'] == 'all' ){
			$whereAdmin = '';
		}else{
			$whereAdmin = ' AND o.admin_id = '.(int)$v['order_raport_admin_id'];			
		}
		
		
		// lista zamowien
		$ask = "
			SELECT * FROM 
				`order` o 
			LEFT JOIN 
				`client` c ON c.client_id = o.order_client_id_main  
			LEFT JOIN 
				`employee` e ON e.employee_id = o.employee_id 
			LEFT JOIN 
				`admin` a ON a.admin_id = o.admin_id 
			WHERE
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin."
			ORDER BY order_ins DESC;
		";
//		echo$ask;
		$data = $db->query($ask)->fetchAll();	
		$this->view->dataTable = $data; 
		
		
		
		
		
		
		
		
		/*
		$ask = "
		
			SELECT 
			
			*,
			p.product_name, 
			p.product_id AS product_id, 
			COUNT(order_product_count) AS order_products_count, 
			SUM(order_product_count) AS order_products_count_sum, 
			pp.product_project_price AS product_project_price, 
			SUM(order_product_count*pp.product_project_price) AS product_all_sum 
			
			FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id 
            AND 
            o.project_id = pp.project_id

			".$whereClient."
			".$whereEmp."
			
            GROUP BY op.product_id
            
			ORDER BY
			p.product_name ASC,
			c.client_name ASC
		
		";
		*/
		
		$ask = "
			SELECT *, p.product_name, p.product_id AS product_id, COUNT(order_product_count) AS order_products_count, SUM(order_product_count) AS order_products_count_sum, pp.product_project_price AS product_project_price, SUM(order_product_count*pp.product_project_price) AS product_all_sum FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id 
            AND 
            o.project_id = pp.project_id
            AND
			
			o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
			".$whereProject."
			".$whereClient."
			".$whereEmp."
			".$whereAdmin."
            
            GROUP BY op.product_id
            
            
			ORDER BY
			p.product_name ASC,
			c.client_name ASC
		";
			
		$data = $db->query($ask)->fetchAll();	
		$this->view->dataTableProduct = $data; 
		
		$ask = "
			SELECT SUM(order_rabat) AS rabat FROM 
				`order` o 
			WHERE
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin.";
		";
//		echo$ask;
		$data = $db->query($ask)->fetchAll();	
		$this->view->rabatOrder = $data[0]['rabat']; 
		
		
		
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

		/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2;
		*/
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
	}
	
	
	
	
	
	public function orderraportprintAction() {	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');
		$filtr = new Zend_Session_Namespace('filtrorder');	
		$db = Zend_Registry::get('db');
		
		$v = $this->_request->getParams();
		$vPost = $this->_request->getPost();
		
		if( 
			!isset($v['order_raport_date']) OR
			!isset($v['order_raport_project_id']) OR
			!isset($v['order_raport_client_id']) OR
			!isset($v['order_raport_employee_id']) OR
			!isset($v['order_raport_admin_id']) OR
			$v['order_raport_date'] == ''
		){
			$this->_helper->redirector('orderraport','calculation',null,array(
				'order_raport_date' => date('d-m-Y'), 
				'order_raport_project_id' => 'all', 
				'order_raport_client_id' => 'all', 
				'order_raport_employee_id' => 'all', 
				'order_raport_admin_id' => 'all')
			);
		}

		
		$this->view->order_raport_date = $v['order_raport_date'];
		$this->view->order_raport_project_id = $v['order_raport_project_id'];
		$this->view->order_raport_client_id = $v['order_raport_client_id'];
		$this->view->order_raport_employee_id = $v['order_raport_employee_id'];
		$this->view->order_raport_admin_id = $v['order_raport_admin_id'];
		
		$this->view->add_raport_product = $v['add_raport_product'];
		$this->view->add_detail_order = $v['add_detail_order'];
		
		
		$whereProject = '';
		if( $v['order_raport_project_id'] == 'all' ){
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.');
		}else{
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.').' AND o.project_id = '.(int)$v['order_raport_project_id'];		
		}
		
		
		$whereClient = '';
		if( $v['order_raport_client_id'] == 'all' ){
			$whereClient = '';
		}else if( $v['order_raport_client_id'] == 'null' ){
			$whereClient = ' AND order_client_id_main = 0';		
		}else{
			$whereClient = ' AND order_client_id_main = '.(int)$v['order_raport_client_id'];			
		}
		
		
		$whereEmp = '';
		if( $v['order_raport_employee_id'] == 'all' ){
			$whereEmp = '';
		}else{
			$whereEmp = ' AND o.employee_id = '.(int)$v['order_raport_employee_id'];			
		}
		
		
		$whereAdmin = '';
		if( $v['order_raport_admin_id'] == 'all' ){
			$whereAdmin = '';
		}else{
			$whereAdmin = ' AND o.admin_id = '.(int)$v['order_raport_admin_id'];			
		}
		
		
		// lista zamowien
		$ask = "
			SELECT * FROM 
				`order` o 
			LEFT JOIN 
				`client` c ON c.client_id = o.order_client_id_main  
			LEFT JOIN 
				`employee` e ON e.employee_id = o.employee_id 
			LEFT JOIN 
				`admin` a ON a.admin_id = o.admin_id 
			WHERE
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin."
			ORDER BY order_ins DESC;
		";		
		$data = $db->query($ask)->fetchAll();	
		$this->view->dataTable = $data; 
		
		
		
		$ask = "
			SELECT *, p.product_name, p.product_id AS product_id, COUNT(order_product_count) AS order_products_count, SUM(order_product_count) AS order_products_count_sum, pp.product_project_price AS product_project_price, SUM(order_product_count*pp.product_project_price) AS product_all_sum FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id 
            AND 
            o.project_id = pp.project_id
            AND
			
			o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
			".$whereProject."
			".$whereClient."
			".$whereEmp."
			".$whereAdmin."
            
            GROUP BY op.product_id
            
            
			ORDER BY
			p.product_name ASC,
			c.client_name ASC
		";
			
		$data = $db->query($ask)->fetchAll();	
		$this->view->dataTableProduct = $data; 
		
		$ask = "
			SELECT SUM(order_rabat) AS rabat FROM 
				`order` o 
			WHERE
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin.";
		";		
		$data = $db->query($ask)->fetchAll();	
		$this->view->rabatOrder = $data[0]['rabat']; 
		
		
		
		
		$d = Lib_Calculation::categoryProduct();
		$this->view->categoryList = $d;  

		/*
		$d2 = array();
		foreach( $d as $key => $val ){
			$d2[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		$this->view->categoryListFull = $d2;
		*/
		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$this->view->categoryListFull = $d2; 
		
		$d = Lib_Calculation::unitList();
		$this->view->unitList = $d; 
		
	}
	
	
	
	
	
	
	
	
	
	
	/* PDFy */
	




			
		
	function pdfhtml_order($id){
		$db = Zend_Registry::get('db');	
	
		$Order = new Order();
		$select = $Order->select();
		$select->where('order_id = ?', $id);
		$orderData = $Order->fetchRow($select);
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $orderData->project_id);
		$projectData = $Project->fetchRow($select);
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $projectData->company_id);
		$companyData = $Company->fetchRow($select);
		
		/*
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			`order` o,	
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			o.order_id = ".$id."
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			c.client_name ASC,
			p.product_name ASC		
		";
		*/
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			`order` o,	
			product_group pg,
			order_product op,
			product p, 		
			product_project pp, 		 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			o.order_id = ".$id."
			AND
			o.order_id = op.order_id 
			AND
			op.product_id = p.product_id 
			AND
			pp.product_id = p.product_id 
			AND 
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			AND
			pp.project_id = '".$orderData->project_id."'
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
	//	echo$ask;
		$dataTable = $db->query($ask)->fetchAll();

		
		$categoryList = Lib_Calculation::categoryProduct();
/*
		$categoryListFull = array();
		
		foreach( $categoryList as $key => $val ){
			$categoryListFull[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$categoryListFull[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'].'1';
				}
			}
		}
		*/

		
		$d2 = Lib_Calculation::categoryProductListFull();		
		$categoryListFull = $d2; 
		
		
		$unitList = Lib_Calculation::unitList();
		
		
		
		



	$html.='<h4 style="font-size: x-large;">'.@LANG_header_title_printdate_order.' '.$orderData['order_nr'];


				 if( $orderData['order_status'] == 0 ){
					$html.=' <span bgcolor="#777" style="font-size: large;color:#fff;"> '.@LANG_productcatalog_order_status_0.' </span>';	
				 }
			
				 if( $orderData['order_status'] == 1 ){
					$html.=' <span bgcolor="#f0ad4e" style="font-size: large;color:#fff;"> '.@LANG_productcatalog_order_status_1.' </span>';
				 }
			
				 if( $orderData['order_status'] == 2 ){
					$html.=' <span bgcolor="#5bc0de" style="font-size: large;color:#fff;"> '.@LANG_productcatalog_order_status_2.' </span>';
				 }
			
				 if( $orderData['order_status'] == 3 ){
					$html.=' <span bgcolor="#5cb85c" style="font-size: large;color:#fff;"> '.@LANG_productcatalog_order_status_3.' </span>';
				 }
			
				 if( $orderData['order_status'] == 4 ){
					$html.=' <span bgcolor="#d9534f" style="font-size: large;color:#fff;"> '.@LANG_productcatalog_order_status_4.' </span>';		
				 }

$html.='</h4>';


$html.='<h5 style="font-size: large;">'.$companyData['company_name'].' / '.$projectData['project_name'].'</h5>';		
		
		
		



$html.='<b>'.@LANG_header_title_printdate_order_addadmin.'</b> '.Lib_Documents::AdminName($orderData['admin_id']).'<br />';

$html.='<b>'.@LANG_header_title_printdate_order_addins.'</b> '.$orderData['order_ins'].'<br />';

$html.='<b>'.@LANG_header_title_printdate_order_addedit.'</b> '.$orderData['order_edit'].'<br /><br />';


if( $orderData['order_realization'] != '0000-00-00' ){
$html.='<b>'.@LANG_header_title_printdate_order_date.'</b> '.$orderData['order_realization'].'<br />';
}

$emp = Lib_Employee::Employee($orderData['employee_id']); 

$html.='<b>'.@LANG_header_title_printdate_order_user.'</b> '.$emp['employee_firstname'].' '.$emp['employee_secondname'].'<br />';

	if( $orderData['order_notice'] != '' ){
	
	$html.='
	<br />
	<b>'.@LANG_header_title_printdate_order_notice.'</b>
	<div class="printNotice">'.$orderData['order_notice'].'</div>	
	<br />';
	
	}
		
		
		
$width = array(30,250,80,75,85,180);
		

$html.='
<br />
<table border="1" cellpadding="6" cellspacing="0">
	<thead>
		<tr style="font-weight: bold;">
			<th width="'.$width[0].'">	
			</th>
			<th width="'.$width[1].'">
'.@LANG_productcatalog_name.', '.@LANG_productcatalog_code.'
<br />
<small style="color:#888;">'.@LANG_productcatalog_client.', '.@LANG_productcatalog_group.'</small>
			</th>
			<th width="'.$width[2].'">'.@LANG_productcatalog_price.'</th>
			<th width="'.$width[3].'">'.@LANG_productcatalog_order_count.'</th>
			<th width="'.$width[4].'">'.@LANG_productcatalog_order_cost.'</th>
			<th width="'.$width[5].'">
				'.@LANG_productcatalog_order_notic.'			
			</th>
		</tr>
	</thead>
	<tbody>';		
		
		


$i = 0; foreach ($dataTable as $key => $val): $i++;

		$html.='<tr>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>
			<td width="'.$width[1].'">
				'.$val['product_name'].', '.$val['product_nr'].'
				<br />
				<small style="color:#888;"><b>'.$val['client_name'].'</b>, '.$categoryListFull[$val['product_group_id']].'</small>
			</td>
			<td width="'.$width[2].'">'.$val['order_product_price'].' &euro; / '.$unitList[$val['product_unit_id']].'
			</td>
			
			<td width="'.$width[3].'">			
				'.$val['order_product_count'].' '.$unitList[$val['product_unit_id']].'
			</td>
			
			<td width="'.$width[4].'">			
				'.number_format($val['order_product_count']*$val['order_product_price'],2).' &euro;
			</td>
			
			<td width="'.$width[5].'">
				<b>'.$val['order_product_notice'].'</b>	
			</td>
		</tr>';

endforeach;
		
		
		
		$orderInfo = Lib_Calculation::infoOrder($val['order_id']);
		$html = $html.'
		<tr style="font-weight: bold;">
			<td colspan="4" align="right" bgcolor="#cef6ce">'.@LANG_calculation_calculation_order_countcost1.'</td>
			<td colspan="2"><b>'.number_format($orderInfo['order_sum'],2).' &euro;'.'</b> </td>
		</tr>
	</tbody>
</table>
		';
		
		return $html;
	}
			
		
	function generate_calculationorderpdf($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
			
			
		
		
		
			$html = $this->pdfhtml_order($v['id']);
			
			$name = mb_strtolower (@LANG_pdf_order_nr.' '.$v['id'], 'UTF-8');
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage();
			
			$pdf->writeHTML($html, true, 0, true, true);
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	public function calculationorderpdfAction() {	
		$information = new Zend_Session_Namespace('information');
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		$this->_helper->viewRenderer->setNoRender();
		
		$Order = new Order();
		$select = $Order->select();
		$select->where('order_id = ?', $v['id']);
		$row = $Order->fetchRow($select);
		
		if( Lib_Permission::getPermissionProjectCalc( $row['project_id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
			
		$this->generate_calculationorderpdf();		
	}
			
		
	function generate_calculationorderallpdf($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
			
		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$projectData = $Project->fetchRow($select);
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $projectData->company_id);
		$companyData = $Company->fetchRow($select);
				
		$order = array('order_ins DESC','order_edit DESC');	
		
		$select = $db->select();
		$select->from('order')->join('employee', 'order.employee_id = employee.employee_id')->join('admin', 'order.admin_id = admin.admin_id');
		$select->where('project_id = '.$v['id']); 	 
		$select->order($order);  
		$stmt = $db->query($select);
		$dataTable = $stmt->fetchAll();	
			
		
		$html = '
		<h4 style="font-size: x-large;">
			'.$companyData['company_name'].'
			<br />
			'.$projectData['project_name'].'
		</h4>
		';
		
		$projectInfo = Lib_Calculation::infoProject( $v['id'] );

		$r = $projectInfo['project_sum'] - $projectInfo['project_order_sum'];

		$color = "green;";				
		if( $r < 0 ) $color = "red;";
		
		$html .= '<h5 style="font-size: large;">';				
		$html .= @LANG_project_list_calculation0.' <b>'.number_format($projectInfo['project_sum'],2).' &euro;'.'</b>';
		$html .='<br />';

		$html .= @LANG_project_list_calculation1.' <b style="color:'.$color.'">'.number_format($projectInfo['project_order_sum'],2).' &euro;'.'</b>';
		$html .='<br />';

		$html .= @LANG_project_list_calculation2.' <b style="color:'.$color.'">'.number_format($r,2).' &euro;'.'</b> ';
		$html .='<br /><br />';
		$html .= '</h5>';				
		
		
		
		
		
$width = array(30,125,125,100,200,125);
		
		
		
		$html .= '
		<table border="1" cellpadding="6" cellspacing="0">
	<thead>
		<tr style="font-weight: bold;">
			<th width="'.$width[0].'">'.@LANG_calculation_calculation_order_lp.'</th>
			<th width="'.$width[1].'">'.@LANG_calculation_calculation_order_nr.'</th>
			<th width="'.$width[2].'">'.@LANG_calculation_calculation_order_employee.'</th>
			<th width="'.$width[3].'">'.@LANG_calculation_calculation_order_realization.'</th>
			<th width="'.$width[4].'">'.@LANG_calculation_calculation_order_countcost.'</th>
			<th width="'.$width[5].'">'.@LANG_calculation_calculation_order_status.'</th>
		</tr>
	</thead>
	<tbody>
	';
		

		


$i = 0; foreach ($dataTable as $key => $val): $i++;


if( $val['order_status'] == 0 ){
	$span = '<span bgcolor="#777" style="color:#fff;"> '.@LANG_productcatalog_order_status_0.' </span>';
}
if( $val['order_status'] == 1 ){
	$span = '<span bgcolor="#f0ad4e" style="color:#fff;"> '.@LANG_productcatalog_order_status_1.' </span>';
}
if( $val['order_status'] == 2 ){
	$span = '<span bgcolor="#5bc0de" style="color:#fff;"> '.@LANG_productcatalog_order_status_2.' </span>';
}
if( $val['order_status'] == 3 ){
	$span = '<span bgcolor="#5cb85c" style="color:#fff;"> '.@LANG_productcatalog_order_status_3.' </span>';
}
if( $val['order_status'] == 4 ){
	$span = '<span bgcolor="#d9534f" style="color:#fff;"> '.@LANG_productcatalog_order_status_4.' </span>';
}

		$orderInfo = Lib_Calculation::infoOrder($val['order_id']);
		$html.='<tr>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>
			<td width="'.$width[1].'">
				'.@LANG_calculation_calculation_order_nrval.' '.$val['order_id'].'
			</td>
			<td width="'.$width[2].'">'.$val['employee_firstname'].' '.$val['employee_secondname'].'
			</td>
			
			<td width="'.$width[3].'">			
				'.(( $val['order_realization'] != '0000-00-00' )?Lib_Date::convertDate($val['order_realization']):'-').'
			</td>
			
			<td width="'.$width[4].'">			
				'.@LANG_calculation_calculation_order_countcost0.' <b>'.number_format($orderInfo['order_count']).'</b><br />
				'.@LANG_calculation_calculation_order_countcost1.' <b>'.number_format($orderInfo['order_sum'],2).' &euro;'.'</b>
			</td>
			
			<td width="'.$width[5].'" align="center">
				'.$span.'		
			</td>
		</tr>';

endforeach;		
		
		
		
		
		$html .= '		
	</tbody>
</table>	
		';
		
		
		
		//	$html = $this->pdfhtml_order($v['id']);
			
			$name = mb_strtolower (@LANG_pdf_order_all.' '.$projectData->project_name, 'UTF-8');
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage();			
			$pdf->writeHTML($html, true, 0, true, true);
			

		
		
		if( $v['include_order'] == 1 ){
		
			foreach( $dataTable as $key => $val ){
				$ht = $this->pdfhtml_order($val['order_id']);
				$pdf->AddPage();			
				$pdf->writeHTML($ht, true, 0, true, true);
			}
		
		}			
			
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	
	
	
	
	public function orderraportpdfAction() {	
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		$this->_helper->viewRenderer->setNoRender();
			
		$this->generate_orderraportpdf();		
	}
			
		
	function generate_orderraportpdf($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	

		
		
		
		$whereProject = '';
		if( $v['order_raport_project_id'] == 'all' ){
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.');
		}else{
			$whereProject = ' AND '.Lib_Permission::setPermissionProjectCalcSQL('o.').' AND o.project_id = '.(int)$v['order_raport_project_id'];	
		}
		
		
		$whereClient = '';
		if( $v['order_raport_client_id'] == 'all' ){
			$whereClient = '';
		}else if( $v['order_raport_client_id'] == 'null' ){
			$whereClient = ' AND order_client_id_main = 0';		
		}else{
			$whereClient = ' AND order_client_id_main = '.(int)$v['order_raport_client_id'];			
		}
		
		
		$whereEmp = '';
		if( $v['order_raport_employee_id'] == 'all' ){
			$whereEmp = '';
		}else{
			$whereEmp = ' AND o.employee_id = '.(int)$v['order_raport_employee_id'];			
		}
		
		
		$whereAdmin = '';
		if( $v['order_raport_admin_id'] == 'all' ){
			$whereAdmin = '';
		}else{
			$whereAdmin = ' AND o.admin_id = '.(int)$v['order_raport_admin_id'];			
		}
		
		
		// lista zamowien
		$ask = "
			SELECT * FROM 
				`order` o 
			LEFT JOIN 
				`client` c ON c.client_id = o.order_client_id_main  
			LEFT JOIN 
				`employee` e ON e.employee_id = o.employee_id 
			LEFT JOIN 
				`admin` a ON a.admin_id = o.admin_id 
			WHERE
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin."
			ORDER BY order_ins DESC;
		";
		$data = $db->query($ask)->fetchAll();	
		$dataTable = $data; 			
		
			
		$color = "green;";				
		if( $r < 0 ) $color = "red;";
		
		$html .= '<h4 style="font-size: large;">';				
		$html .= @LANG_calculation_orderraport_top_order;
		$html .= '</h4>';	
		$html .='<br />';
		
		
$width = array(30,170,125,70,115,120,75);
		
		
		
		$html .= '
		<table border="1" cellpadding="6" cellspacing="0">
	<thead>
		<tr style="font-weight: bold;">
			<th width="'.$width[0].'">'.@LANG_calculation_calculation_order_lp.'</th>
			<th width="'.$width[1].'">'.@LANG_calculation_calculation_order_nr.'</th>
			<th width="'.$width[2].'">'.@LANG_calculation_calculation_order_employee.'</th>
			<th width="'.$width[3].'">'.@LANG_calculation_calculation_order_realization.'</th>
			<th width="'.$width[4].'">'.@LANG_calculation_calculation_order_countcost.'</th>
			<th width="'.$width[5].'"></th>
			<th width="'.$width[6].'">'.@LANG_calculation_calculation_order_status.'</th>
		</tr>
	</thead>
	<tbody>
	';
		

		

$sumP = 0;
$i = 0; foreach ($dataTable as $key => $val): $i++;


if( $val['order_status'] == 0 ){
	$span = '<span bgcolor="#777" style="color:#fff;"> '.@LANG_productcatalog_order_status_0.' </span>';
}
if( $val['order_status'] == 1 ){
	$span = '<span bgcolor="#f0ad4e" style="color:#fff;"> '.@LANG_productcatalog_order_status_1.' </span>';
}
if( $val['order_status'] == 2 ){
	$span = '<span bgcolor="#5bc0de" style="color:#fff;"> '.@LANG_productcatalog_order_status_2.' </span>';
}
if( $val['order_status'] == 3 ){
	$span = '<span bgcolor="#5cb85c" style="color:#fff;"> '.@LANG_productcatalog_order_status_3.' </span>';
}
if( $val['order_status'] == 4 ){
	$span = '<span bgcolor="#d9534f" style="color:#fff;"> '.@LANG_productcatalog_order_status_4.' </span>';
}

		$orderInfo = Lib_Calculation::infoOrder($val['order_id']);
		$sumP = $sumP + $orderInfo['order_sum'];
		$html.='<tr>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>
			<td width="'.$width[1].'">
				'.(( $val['order_nr2'] != '' )?@LANG_calculation_order_filtr_nr.' '.$val['order_nr2'].'<br />':'').'			
				
				<font style="color:#888;">'.@LANG_calculation_calculation_order_admin.' '.$val['admin_firstname'].' '.$val['admin_secondname'].'</font>
				<br />
				<font style="color:#888;">'.@LANG_calculation_calculation_order_nrval.' '.$val['order_nr'].'</font>
				
				
			</td>
			<td width="'.$width[2].'">'.$val['employee_firstname'].' '.$val['employee_secondname'].'
			</td>
			
			<td width="'.$width[3].'">			
				'.(( $val['order_realization'] != '0000-00-00' )?Lib_Date::convertDate($val['order_realization']):'-').'
			</td>
			
			<td width="'.$width[4].'">			
				'.@LANG_calculation_calculation_order_countcost0.' <b>'.number_format($orderInfo['order_count']).'</b><br />
				'.@LANG_calculation_calculation_order_countcost1.' <b><br />'.number_format($orderInfo['order_sum'],2).' &euro;'.'</b>
			</td>
			
			<td width="'.$width[5].'" align="center">
				'.Lib_Calculation::infoMainProject( $val['order_client_id_main'] ).'
			</td>
			
			<td width="'.$width[6].'" align="center">
				'.$span.'		
			</td>
		</tr>';

endforeach;		


		$html .= '		
		<tr>
		
			<td colspan="4" style="text-align:right;font-size:12px;">
			'.@LANG_calculation_calculation_orders_countcost1.'
			</td>
			<td style="font-size:12px;">
			<b>'.number_format($sumP,2).'&nbsp;&euro;'.'</b>
			</td>
			<td colspan="2"></td>
		
		</tr>	
		';		
		
		
		
		$html .= '		
	</tbody>
</table>	
		';
		
		
			
		
		
		
		
		
		
		//	$html = $this->pdfhtml_order($v['id']);
			
			$name = mb_strtolower (@LANG_pdf_orderraport_all.' '.Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d"), 'UTF-8');
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage();			
			$pdf->writeHTML($html, true, 0, true, true);
			

		
		
		

		$html = '';
		if( $v['add_raport_product'] == 1 ){
		
			$ask = "
				SELECT *, p.product_name, p.product_id AS product_id, COUNT(order_product_count) AS order_products_count, SUM(order_product_count) AS order_products_count_sum, pp.product_project_price AS product_project_price, SUM(order_product_count*pp.product_project_price) AS product_all_sum FROM 
				`order` o,	
				product_group pg,
				order_product op,
				product p, 		
				product_project pp, 		 
				client c, 
				product_unit pu
				WHERE
				p.product_group_id = pg.product_group_id 
				AND
				o.order_id = op.order_id 
				AND
				op.product_id = p.product_id 
				AND
				pp.product_id = p.product_id 
				AND 
				p.product_unit_id = pu.product_unit_id 
				AND
				p.client_id = c.client_id 
				AND 
				o.project_id = pp.project_id
				AND
				
				o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
				".$whereProject."
				".$whereClient."
				".$whereEmp."
				".$whereAdmin."
				
				GROUP BY op.product_id
				
				
				ORDER BY
				p.product_name ASC,
				c.client_name ASC
			";
				
			$data = $db->query($ask)->fetchAll();	
			$dataTableProduct = $data; 
			
			$ask = "
				SELECT SUM(order_rabat) AS rabat FROM 
					`order` o 
				WHERE
					o.order_realization = '".Lib_Date::convertDate($v['order_raport_date'],"d-m-Y","Y-m-d")."'
					".$whereProject."
					".$whereClient."
					".$whereEmp."
					".$whereAdmin.";
			";
			$data = $db->query($ask)->fetchAll();	
			$rabatOrder = $data[0]['rabat']; 
			
			$d = Lib_Calculation::categoryProduct();
			$this->view->categoryList = $d;  

			$d2 = array();
			foreach( $d as $key => $val ){
				$d2[$val['product_group_id']] = $val['product_group_name'];
				if( $val['product_group_child'] == 1 ){
					foreach( $val['child'] as $key2 => $val2 ){
						$d2[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
					}
				}
			}
			$categoryListFull = $d2;
			
			$d = Lib_Calculation::unitList();
			$unitList = $d; 

		
			$html .= '<h4 style="font-size: large;">';				
			$html .= @LANG_calculation_orderraport_top_product;
			$html .= '</h4>';	
			$html .='<br />';
			
			$width = array(30,400,75,75,125);
			
			$html .= '
			<table border="1" cellpadding="6" cellspacing="0">
				<thead>
					<tr style="font-weight: bold;">
						<th width="'.$width[0].'">'.@LANG_calculation_calculation_order_lp.'</th>
						<th width="'.$width[1].'">
							'.@LANG_productcatalog_name.', '.@LANG_productcatalog_code.'
							<br />
							<font style="color:#888;">'.@LANG_productcatalog_client.', '.@LANG_productcatalog_group.'</font>
						</th>
						<th width="'.$width[2].'">'.@LANG_productcatalog_price.'</th>
						<th width="'.$width[3].'">'.@LANG_productcatalog_order_count.'</th>
						<th width="'.$width[4].'">'.@LANG_productcatalog_product_sum.'</th>
					</tr>
				</thead>
				<tbody>
			';
			
			$sumP = 0;			
			
			$i = 0; foreach ($dataTableProduct as $key => $val): $i++;

				$html.='<tr>
				
					<td width="'.$width[0].'">
						'.$i.'.'.'
					</td>
					<td width="'.$width[1].'">
						'.$val['product_name'].' '.$val['product_nr'].'
						<br />
						<font style="color:#888;"><b>'.$val['client_name'].'</b>, '.$categoryListFull[$val['product_group_id']].'</font>
					</td>
					<td width="'.$width[2].'">'.$val['product_project_price'].' &euro; / '.$unitList[$val['product_unit_id']].'
					</td>
					
					<td width="'.$width[3].'">			
						'.$val['order_products_count_sum'].'
					</td>
					
					<td width="'.$width[4].'">			
						'.number_format($val['product_all_sum'],2).' &euro;
					</td>
				</tr>';

		
			$sumP = $sumP + $val['product_all_sum'];
			endforeach;	
			
			
			
$html .= '


	<tr>
		<td colspan="4" style="text-align:right;font-size:12px;">
			'.@LANG_calculation_calculation_product_countcost1.'
		</td>
		
		<td style="font-size:12px;"><b>'.number_format($sumP,2).'&nbsp;&euro;'.'</b>
		</td>
	</tr>
	
	
	
	
	<tr>
		<td colspan="4" style="text-align:right;font-size:12px;">
			'.@LANG_calculation_calculation_rabat_countcost1.'
		</td>
		
		<td style="font-size:12px;color:red;"><b>'.number_format($rabatOrder,2).'&nbsp;&euro;'.'</b></td>
	</tr>
	
	
	
	
	<tr>
		<td colspan="4" style="text-align:right;font-size:12px;">
			'.@LANG_calculation_calculation_productrabat_countcost1.'
		</td>
		
		<td style="font-size:12px;"><b>'.number_format($sumP+$rabatOrder,2).'&nbsp;&euro;'.'</b>
		</td>
	</tr>

';			
			
			
			
		
			$html .= '		
				</tbody>
			</table>	
			';

			$pdf->AddPage();			
			$pdf->writeHTML($html, true, 0, true, true);
		
		}	
		
		
		
		
		
		if( $v['add_detail_order'] == 1 ){
		
			foreach( $dataTable as $key => $val ){
				$ht = $this->pdfhtml_order($val['order_id']);
				$pdf->AddPage();			
				$pdf->writeHTML($ht, true, 0, true, true);
			}
		
		}			
			
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	
	public function calculationorderallpdfAction() {	
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		$this->_helper->viewRenderer->setNoRender();
			
		$this->generate_calculationorderallpdf();		
	}
			
		
	function generate_calculationmainallpdf($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
			




		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$projectData = $Project->fetchRow($select);
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $projectData->company_id);
		$companyData = $Company->fetchRow($select);
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p, 
			product_group pg,
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$dataTable = $db->query($ask)->fetchAll();
		
		
		
		// budowanie drzewa kategorii
		/*
		$categoryList = Lib_Calculation::categoryProduct();

		$categoryListFull = array();
		foreach( $categoryList as $key => $val ){
			$categoryListFull[$val['product_group_id']] = $val['product_group_name'];
			if( $val['product_group_child'] == 1 ){
				foreach( $val['child'] as $key2 => $val2 ){
					$categoryListFull[$val2['product_group_id']] = $val['product_group_name']." &rarr; ".$val2['product_group_name'];
				}
			}
		}
		*/
		$categoryListFull = Lib_Calculation::categoryProductListFull();		
		
		$clientList = Lib_Calculation::clientProduct();
	
		$unitList = Lib_Calculation::unitList();
		


		
		$html = '
		<h4 style="font-size: x-large;">
			'.$companyData['company_name'].'
			<br />
			'.$projectData['project_name'].'
		</h4>
		';
		
if( $v['cost'] == 1 ){
		$projectInfo = Lib_Calculation::infoProject( $v['id'] );

		$r = $projectInfo['project_sum'] - $projectInfo['project_order_sum'];

		$color = "green;";				
		if( $r < 0 ) $color = "red;";
		
		$html .= '<h5 style="font-size: large;">';				
		$html .= @LANG_project_list_calculation0.' <b>'.number_format($projectInfo['project_sum'],2).' &euro;'.'</b>';
		$html .='<br />';

		$html .= @LANG_project_list_calculation1.' <b style="color:'.$color.'">'.number_format($projectInfo['project_order_sum'],2).' &euro;'.'</b>';
		$html .='<br />';

		$html .= @LANG_project_list_calculation2.' <b style="color:'.$color.'">'.number_format($r,2).' &euro;'.'</b> ';
		$html .='<br /><br />';
		$html .= '</h5>';				
}		
		
		

		
		
		
		
$width = array(30,250,100,100,100,100);
		
		
		
		if( $v['cost'] == 1 ){
			$s0_html = '<th width="'.$width[2].'">'.@LANG_productcatalog_price.'</th>';
		}
		
		if( $v['sum_include'] == 1 ){
			$s1_html = '<th width="'.$width[4].'">'.@LANG_productcatalog_order.'</th>';
		}
		
		if( $v['difference_include'] == 1 ){
			$s2_html = '<th width="'.$width[5].'">'.@LANG_productcatalog_orderr.'</th>';		
		}
		
		
		$html .= '
		<table border="1" cellpadding="6" cellspacing="0">
	<thead>
		<tr style="font-weight: bold;">
			<th width="'.$width[0].'"></th>
			<th width="'.$width[1].'">
'.@LANG_productcatalog_name.', '.@LANG_productcatalog_code.'
<br />
<small style="color:#888;">'.@LANG_productcatalog_client.', '.@LANG_productcatalog_group.'</small>
			</th>
			'.$s0_html.'			
			<th width="'.$width[3].'">'.@LANG_productcatalog_request.'</th>
			'.$s1_html.'
			'.$s2_html.'			
		</tr>
	</thead>
	<tbody>
	';		

		


$i = 0; foreach ($dataTable as $key => $val): $i++;

				$orderInfo = Lib_Calculation::infoProductProject( $val['product_id'], $val['project_id'] );
				
				$s = 's0';
				
				$r_count = number_format($val['product_project_count'] - $orderInfo[$s]['product_count'],2);
				$r_cost = number_format($val['product_project_cost'] - $orderInfo[$s]['product_sum'],2);
				
				$color = "green;";				
				if( $r_count < 0 ) $color = "red;";
			
			
				$s = 's0';
				
				$r_count = number_format($val['product_project_count'] - $orderInfo[$s]['product_count'],2);
				$r_cost = number_format($val['product_project_cost'] - $orderInfo[$s]['product_sum'],2);
				
				$color2 = "green;";				
				if( $r_count < 0 ) $color2 = "red;";	
				
				
				
				
		
		
		if( $v['cost'] == 1 ){
			$s0_html = '<td width="'.$width[2].'">'.$val['product_project_price'].' &euro; / '.$unitList[$val['product_unit_id']].'
			</td>';
		}
		
		
		if( $v['sum_include'] == 1 ){
		
			$htmlt = '';			
			if( $v['cost'] == 1 ){
				$htmlt = '<br />
				'.@LANG_productcatalog_cost.' <b style="color:'.$color.'">'.number_format($orderInfo[$s]['product_sum'],2).' &euro;'.'</b>';
			}
		
			$s1_html = '<td width="'.$width[4].'">			
			
			
				'.@LANG_productcatalog_count.' <b style="color:'.$color.'">'.number_format($orderInfo[$s]['product_count'],2).' '.$this->unitList[$val['product_unit_id']].'</b>
				'.$htmlt.'
			
			</td>';
		}
		
		if( $v['difference_include'] == 1 ){
		
			$htmlt = '';			
			if( $v['cost'] == 1 ){
				$htmlt = '<br />
				'.@LANG_productcatalog_cost.' <b style="color:'.$color2.'">'.$r_cost.' &euro;'.'</b>';
			}
			
			
			$s2_html = '<td width="'.$width[5].'">		
			
			
				'.@LANG_productcatalog_count.' <b style="color:'.$color2.'">'.$r_count.' '.$this->unitList[$val['product_unit_id']].'</b>
				'.$htmlt.'
				
			
			</td>';		
		}
				
				
		
		$htmlt = '';			
		if( $v['cost'] == 1 ){
			$htmlt = '<br />		
				'.@LANG_productcatalog_cost.' <b>'.$val['product_project_cost'].' &euro;</b>';
		}		
		
		
		$color = '';
		if( $val['product_project_count'] == 0 ) $color = ' bgcolor="#f6cece"';
		
				
		$html.='<tr'.$color.'>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>
			<td width="'.$width[1].'">
				'.$val['product_name'].', '.$val['product_nr'].'
				<br />
				<small style="color:#888;"><b>'.$val['client_name'].'</b>, '.$categoryListFull[$val['product_group_id']].'</small>
			</td>
			
			
			
			'.$s0_html.'
			
			
			<td width="'.$width[3].'">			
				'.@LANG_productcatalog_count.' <b>'.$val['product_project_count'].' '.$unitList[$val['product_unit_id']].'</b>
				'.$htmlt.'
			</td>
			
			'.$s1_html.'	
			
			'.$s2_html.'					
			
		</tr>';

endforeach;


	
		$html .= '		
	</tbody>
</table>	
		';		
		
		
		
			
			$name = mb_strtolower (@LANG_pdf_calculation.' '.$projectData->project_name, 'UTF-8');
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage();
			
			$pdf->writeHTML($html, true, 0, true, true);
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	public function calculationmainallpdfAction() {	
		$information = new Zend_Session_Namespace('information');
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();		
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$this->_helper->viewRenderer->setNoRender();
			
		$this->generate_calculationmainallpdf();		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
			
		
	function generate_calculationpdf($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
			




		
		$Project = new Project();
		$select = $Project->select();
		$select->where('project_id = ?', $v['id']);
		$projectData = $Project->fetchRow($select);
		
		$Company = new Company();
		$select = $Company->select();
		$select->where('company_id = ?', $projectData->company_id);
		$companyData = $Company->fetchRow($select);
	
		$ask = "
			SELECT *, p.product_id AS product_id FROM 
			product p, 
			product_group pg,
			product_project pp,			 
			client c, 
			product_unit pu
			WHERE
			p.product_group_id = pg.product_group_id 
			AND
			pp.product_id = p.product_id 
			AND 
			pp.project_id = ".$v['id']."
			AND
			p.product_unit_id = pu.product_unit_id 
			AND
			p.client_id = c.client_id
			ORDER BY
			product_nc ASC,
			product_group_sort ASC,
			c.client_name ASC,
			p.product_name ASC		
		";
		$dataTable = $db->query($ask)->fetchAll();

		$categoryListFull = array();
		$categoryListFullMain = array();
	
		$categoryList = Lib_Calculation::categoryProductAllListFull();
		foreach( $categoryList as $key => $val ){
			$categoryListFull[$val['product_group_id']] = $val['product_group_name_full'];	
			$categoryListFullMain[$val['product_group_id']] = $val['product_group_main_id'];	
		}
		
		$clientList = Lib_Calculation::clientProduct();
	
		$unitList = Lib_Calculation::unitList();
		
		/*
		
		<table>
			<tr bgcolor="#d9534f">
			<td align="center"><br />
			<h1 style="color:#fff;">UWAGA! Trwaja prace w pliku podsumowania PDF.</h1>
			<h3 style="color:#fff;">Prezentowane dane moga nie byc precyzyjne.</h3><br />	
			</td>
			</tr>
		</table><br /><br />
		
		*/
		
		$html = '
		
		<h4 style="font-size: x-large;">
			'.$companyData['company_name'].'
			<br />
			'.$projectData['project_name'].'
		</h4>
		';
		
		$projectInfo = Lib_Calculation::infoProject( $v['id'] );

		$r = $projectInfo['project_sum'] - $projectInfo['project_order_sum'];

		$color = "green;";				
		if( $r < 0 ) $color = "red;";


if( $v['sum_summary_detail'] == 1 ){				
		$html .= '<h5 style="font-size: large;">';				
		$html .= @LANG_project_list_calculation0.' <b>'.number_format($projectInfo['project_sum'],2).' &euro;'.'</b>';
		$html .=', ';

		$html .= @LANG_project_list_calculation1.' <b style="color:'.$color.'">'.number_format($projectInfo['project_order_sum'],2).' &euro;'.'</b>';
		$html .=', ';

		$html .= @LANG_project_list_calculation2.' <b style="color:'.$color.'">'.number_format($r,2).' &euro;'.'</b> ';
		$html .= '</h5>';	
}					
		
		$html .= @LANG_project_list_calculation_gendate.' <b>'.date('d-m-Y H:i:s').'</b> ';
		
		
		
		$html .= '<br /><br />';
		
		
		
		
$i = 0; 
$idg = 0;
$rowSpan = array();
$rowSpanValSum = array();
$rowSpanValOrder = array();
foreach ($dataTable as $key => $val):
$i++;

$s = 's0';
$orderInfo = Lib_Calculation::infoProductProject( $val['product_id'], $val['project_id'] );

if( $v['sum_summary_detail'] == 1 ){
	$productPriceData = Lib_Calculation::infoProductProjectPrice( $val['product_id'], $val['project_id'] );
	$productPriceData_COUNT = count($productPriceData) + 1;
}else{
	$productPriceData_COUNT = 1;	
}

if( $categoryListFullMain[$val['product_group_id']] != $idg ){
	$rowSpan[$i] = $productPriceData_COUNT;
	$idg = $categoryListFullMain[$val['product_group_id']];
/*	
	$rowSpanValSum[$i] = $val['product_project_cost'];
	$rowSpanValOrder[$i] = $orderInfo[$s]['product_sum'];
*/	
	$rowSpanValSum[$i] = $val['product_project_count'];
	$rowSpanValOrder[$i] = $orderInfo[$s]['product_count'];
	$pam = $i;
}else{
	$rowSpan[$pam] = $rowSpan[$pam]+$productPriceData_COUNT;
/*
	$rowSpanValSum[$pam] = $rowSpanValSum[$pam]+$val['product_project_cost'];	
	$rowSpanValOrder[$pam] = $rowSpanValOrder[$pam]+$orderInfo[$s]['product_sum'];
*/
	$rowSpanValSum[$pam] = $rowSpanValSum[$pam]+$val['product_project_count'];	
	$rowSpanValOrder[$pam] = $rowSpanValOrder[$pam]+$orderInfo[$s]['product_count'];
}

endforeach;












		
		
$width = array(40,350,75,125,125,125,125,125,125);


		
		$html .= '
		<table border="1" cellpadding="8" cellspacing="0">
	<thead>
		<tr style="font-weight: bold; text-align:center;">
			<th colspan="3" width="'.($width[0]+$width[1]+$width[2]).'" bgcolor="#eee"></th>		
			<th colspan="3" width="'.($width[3]+$width[4]+$width[5]).'" bgcolor="#ddd">'.@LANG_pdf_table_thead_2.'</th>		
			<th colspan="3" width="'.($width[6]+$width[7]+$width[8]).'" bgcolor="#ccc">'.@LANG_pdf_table_thead_3.'</th>		
			<th width="'.$width[9].'" rowspan="2" style="border-right:2 solid white;border-top:2 solid white;"></th>			
		</tr>
		<tr style="font-weight: bold; text-align:center;">			
			<th width="'.$width[0].'" bgcolor="#eee">'.@LANG_pdf_table_thead2_1.'</th>		
			<th width="'.$width[1].'" bgcolor="#eee">'.@LANG_pdf_table_thead2_2.'</th>		
			<th width="'.$width[2].'" bgcolor="#eee">'.@LANG_pdf_table_thead2_3.'</th>		
			<th width="'.$width[3].'" bgcolor="#ddd">'.@LANG_pdf_table_thead2_4.'</th>		
			<th width="'.$width[4].'" bgcolor="#ddd">'.(($v['sum_summary_detail']==1)?@LANG_pdf_table_thead2_5:'').'</th>		
			<th width="'.$width[5].'" bgcolor="#ddd">'.(($v['sum_summary_detail']==1)?@LANG_pdf_table_thead2_6:'').'</th>		
			<th width="'.$width[6].'" bgcolor="#ccc">'.@LANG_pdf_table_thead2_7.'</th>		
			<th width="'.$width[7].'" bgcolor="#ccc">'.(($v['sum_summary_detail']==1)?@LANG_pdf_table_thead2_8:'').'</th>		
			<th width="'.$width[8].'" bgcolor="#ccc">'.@LANG_pdf_table_thead2_9.'</th>		
		</tr>
	</thead>
	<tbody>
		
		';
	




$i = 0; 
$j = 0; 
$idg = 0;


foreach ($dataTable as $key => $val): 

	$i++;	

	$orderInfo = Lib_Calculation::infoProductProject( $val['product_id'], $val['project_id'] );
	
	if( $v['sum_summary_detail'] == 1 ){
		$productPriceData = Lib_Calculation::infoProductProjectPrice( $val['product_id'], $val['project_id'] );
		$productPriceData_COUNT = count($productPriceData) + 1;
	}else{
		$productPriceData_COUNT = 1;	
	}
	/*
	var_dump($productPriceData);
	die();
	*/
	$s = 's0';

	$r_count = number_format($val['product_project_count'] - $orderInfo[$s]['product_count'],2);
	$r_cost = number_format($val['product_project_cost'] - $orderInfo[$s]['product_sum'],2);
				
	$color = "green;";				
	if( $r_count < 0 ) $color = "red;";
	
	$warp = '';

	$color = "green;";
	if( $val['product_project_count'] > 0 ){

		$warp = number_format($orderInfo[$s]['product_count']*100/$val['product_project_count'],2);
		if( $orderInfo[$s]['product_count']*100/$val['product_project_count'] > 100 ) $color = "red;";

		$warp = $warp.'%';
		
	}


	if( $categoryListFullMain[$val['product_group_id']] != $idg ){
		$idg = $categoryListFullMain[$val['product_group_id']];
		
		
		$color = "green;";
		if( $rowSpanValSum[$i] > 0 ){
			
			$sumGr = number_format($rowSpanValOrder[$i]*100/$rowSpanValSum[$i],2);
			
			if( $rowSpanValOrder[$i]*100/$rowSpanValSum[$i] > 100 ) $color = "red;";
			$sumGr = $sumGr.'%';
			
		}else{
			
			$sumGr = '';
			
		}


		$rowSpanV2 = $rowSpan[$i];// + $productPriceData_COUNT - 1;
		$rowHtml = '
		<td width="'.$width[9].'" style="text-align:center;font-size:x-large;" rowspan="'.$rowSpanV2.'">
			'.$categoryListFull[$categoryListFullMain[$val['product_group_id']]].'

			<br />
			<b style="color:'.$color.'">'.$sumGr.'</b>
		</td>
		';
		$j++;
	}else{
		$rowHtml = '';
	}


	if( $j%2 == 0 ){
		$styleClass = ' bgcolor="#eeeee1"';
	}else{
		$styleClass = ' bgcolor="#fff"';
	}				

	if( $val['product_project_count'] == 0 ){	
		$styleClass = ' bgcolor="#f6cece"';	
	}

	
	$html.='
		<tr'.$styleClass.'>
		
			<td width="'.$width[0].'" rowspan="'.$productPriceData_COUNT.'">
				'.$i.'.'.'
			</td>			
				
			<td width="'.$width[1].'" rowspan="'.$productPriceData_COUNT.'">
				'.$val['product_name'].', '.$val['product_nr'].'
			</td>
				
			<td width="'.$width[2].'" rowspan="'.$productPriceData_COUNT.'">
				'.$unitList[$val['product_unit_id']].'
			</td>
				
			<td width="'.$width[3].'" rowspan="'.$productPriceData_COUNT.'">
				'.number_format($val['product_project_count'],2).'
			</td>
			
			<td width="'.$width[4].'" rowspan="'.$productPriceData_COUNT.'">
				'.(($v['sum_summary_detail']==1)?$val['product_project_price'].' &euro;':'').'
			</td>
			
			<td width="'.$width[5].'" rowspan="'.$productPriceData_COUNT.'">
				'.(($v['sum_summary_detail']==1)?number_format($val['product_project_cost'],2).' &euro;':'').'
			</td>
	';
	
	/*
	$html.='	
			<td width="'.$width[6].'">
				'.number_format($orderInfo[$s]['product_count'],2).'
			</td>
			
			<td width="'.$width[7].'">
				'.(($v['sum_summary_detail']==1)?number_format($orderInfo[$s]['product_sum'],2).' &euro;':'').'
			</td>
			
			<td width="'.$width[8].'" style="text-align:center;">
				<b style="color:'.$color.'">'.$warp.'</b>
			</td>	
	';
			<td width="'.($width[6]+$width[7]).'" style="font-weight: bold; text-align:right;">
				'.@LANG_calculationpdf_sum.'
			</td>
			
	*/
	$html.='	
			<td width="'.$width[6].'" style="font-weight: bold; background-color:#ffe3bb;">
				'.number_format($orderInfo[$s]['product_count'],2).'
			</td>
			
			<td width="'.$width[7].'" style="font-weight: bold; background-color:#ffe3bb;">
				'.(($v['sum_summary_detail']==1)?number_format($orderInfo[$s]['product_sum'],2).' &euro;':'').'
			</td>
			
			<td width="'.$width[8].'" style="font-weight: bold; text-align:center; background-color:#ffe3bb;">
				<b style="color:'.$color.'">'.$warp.'</b>
			</td>	
	';
	
	$html.='		
			'.$rowHtml.'			
		</tr>
	';
	
	
	foreach ($productPriceData as $keyPriceData => $valPriceData):
	
	$warp = '';

	//$color = "green;";
	if( $val['product_project_count'] > 0 ){

		$warp = number_format($valPriceData['product_count']*100/$val['product_project_count'],2);
	//	if( $valPriceData['product_count']*100/$val['product_project_count'] > 100 ) $color = "red;";

		$warp = $warp.'%';
		
	}
	
	$html.='	
		<tr'.$styleClass.'>
			<td width="'.$width[6].'">
				'.number_format($valPriceData['product_count'],2).'
				'.(($v['sum_summary_detail']==1)?' x '.number_format($valPriceData['order_product_price'],2).' &euro;':'').'
			</td>
			
			<td width="'.$width[7].'">
				'.(($v['sum_summary_detail']==1)?number_format($valPriceData['product_sum'],2).' &euro;':'').'
			</td>
			
			<td width="'.$width[8].'" style="text-align:center;">
				<b style="color:'.$color.'">'.$warp.'</b>
			</td>		
		</tr>	
	';
	endforeach;

endforeach;


		
		$html .= '	
	</tbody>	
</table>	
		';	
		

		
		
		
		









		


	
	
$ask = "
SELECT c.client_name AS client_name, COUNT(*) AS ilosc, SUM(op.order_product_count*op.order_product_price) AS suma FROM 

`order` o, 
order_product op, 
product p, 
product_project pp, 
client c

WHERE 

op.order_id = o.order_id AND
op.product_id = p.product_id AND
op.product_id = pp.product_id AND
c.client_id = p.client_id AND
o.project_id = pp.project_id AND
o.project_id = ".$v['id']."

GROUP BY p.client_id

ORDER BY
client_name ASC
";


$dataTableClient = $db->query($ask)->fetchAll();


		
$width = array(40,200,200);


if( $v['sum_summary_detail'] == 1 ){
		
		$html .= '
		<br /><br /><br />
<table border="1" cellpadding="8" cellspacing="0">
	<tbody>
		
		';

$i = 0; foreach ($dataTableClient as $key => $val): $i++;

		$html.='<tr>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>			
				
			<td width="'.$width[1].'">
				'.$val['client_name'].'
			</td>
				
			<td width="'.$width[2].'">
				'.number_format($val['suma'],2).' &euro;
			</td>
			</tr>';
			
endforeach;





$ask = "SELECT SUM(order_rabat) AS rabatsum FROM `order` WHERE project_id = ".$v['id']."";
$dataTableRabat = $db->query($ask)->fetchAll();


		$html.='<tr>
		
			<td width="'.$width[0].'">
			
			</td>			
				
			<td width="'.$width[1].'">
				'.@LANG_productcatalog_order_rabat.'
			</td>
				
			<td width="'.$width[2].'">
				'.number_format($dataTableRabat[0]['rabatsum'],2).' &euro;
			</td>
			</tr>';



		$html .= '	
	</tbody>	
</table>	
		';		


}













if( $v['sum_summary_detail'] == 1 ){

	
$ask = "
SELECT order_afterProject, COUNT(*) AS iloscProduct, (SUM(op.order_product_count*op.order_product_price)) AS sumPrice, (SELECT SUM(order_rabat) FROM `order` o2 WHERE o2.project_id = o.project_id AND o2.order_afterProject = o.order_afterProject) AS sumRab
FROM 

`order` o, 
order_product op

WHERE 
op.order_id = o.order_id AND
o.project_id = ".$v['id']." 
GROUP BY o.order_afterProject
ORDER BY o.order_afterProject
";

$dataTableOrderTime = $db->query($ask)->fetchAll();

$width = array(40,300,150,150,150);
		
		$html .= '
		<br /><br /><br />
<table border="1" cellpadding="8" cellspacing="0">
	<thead>
		<tr style="font-weight: bold; text-align:center;">			
			<th width="'.$width[0].'" bgcolor="#eee"></th>		
			<th width="'.$width[1].'" bgcolor="#eee"></th>		
			<th width="'.$width[2].'" bgcolor="#ddd">'.@LANG_pdf_table_order_sumprice.'</th>		
			<th width="'.$width[3].'" bgcolor="#ddd">'.@LANG_pdf_table_order_sumrabat.'</th>		
			<th width="'.$width[4].'" bgcolor="#ddd">'.@LANG_pdf_table_order_sum.'</th>		
		</tr>
	</thead>
	<tbody>		
		';
		
$i = 0; foreach ($dataTableOrderTime as $key => $val): $i++;
		$html.='<tr>
		
			<td width="'.$width[0].'">
				'.$i.'.'.'
			</td>			
				
			<td width="'.$width[1].'">
				'.@constant(@LANG_order_timeType_.$val['order_afterProject']).'
			</td>		
				
			<td width="'.$width[2].'">
				'.number_format($val['sumPrice'],2).' &euro;
			</td>	
				
			<td width="'.$width[3].'">
				'.number_format($val['sumRab'],2).' &euro;
			</td>
				
			<td width="'.$width[4].'">
				'.number_format($val['sumPrice']+$val['sumRab'],2).' &euro;
			</td>
				
			</tr>';
			
endforeach;

		$html .= '	
	</tbody>	
</table>	
		';		

}




		
			
			$name = $projectData->project_id; //mb_strtolower (@LANG_pdf_calculation.' '.$projectData->project_name, 'UTF-8');
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage('L','A3');
			
			$pdf->writeHTML($html, true, 0, true, true);
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	public function calculationpdfAction() {	
		$information = new Zend_Session_Namespace('information');
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		
		if( Lib_Permission::getPermissionProjectCalc( $v['id'] ) != 1 ){	
			$information->permissionError = true;
			$this->_helper->redirector('index','index');		
		}
		
		$this->_helper->viewRenderer->setNoRender();
			
		$this->generate_calculationpdf();		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
			
		
	function generate_testpdfa3($save = false){
	
		$db = Zend_Registry::get('db');		
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();
		$this->_helper->viewRenderer->setNoRender();
	
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
			
			
		
		
		
			$html = 'test';
			
			$name = 'test';
			$nameFile = str_replace(" ","-",$name).'_'.date('d-m-Y_H-i-s');
		
			$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set document information
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('www.TECHNIX.pl');
			$pdf->SetTitle($nameFile);
			$pdf->SetSubject($nameFile);
			$pdf->SetKeywords($nameFile);
			$pdf->setPrintHeader(false);
			
			// set default header data
			$pdf->setFooterData(array(0,64,0), array(0,64,128));

			// set header and footer fonts
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

			// set margins
			$pdf->SetMargins(5, 5, 5);

			// set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, 5);

			// set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

			// ---------------------------------------------------------

			// set default font subsetting mode
			$pdf->setFontSubsetting(true);

			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('dejavusans', '', 7, '', true);

			// Add a page
			// This method has several options, check the source code documentation for more information.
			$pdf->AddPage('P','A3');			
			$pdf->writeHTML($html, true, 0, true, true);
			$pdf->AddPage('L','A3');			
			$pdf->writeHTML($html, true, 0, true, true);
			
			$pdf->AddPage('P','A4');			
			$pdf->writeHTML($html, true, 0, true, true);
			$pdf->AddPage('L','A4');			
			$pdf->writeHTML($html, true, 0, true, true);
			
			ob_end_clean();
			if( $save == false ) $pdf->Output($nameFile.'.pdf', 'I');
			else{
				$file = $_SERVER['DOCUMENT_ROOT'].'raport/'.$nameFile.'.pdf';
				$pdf->Output($file, 'F');
				return $file;
			}

		
	}
	
	
	public function testpdfa3Action() {	
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		$this->_helper->viewRenderer->setNoRender();
			
		$this->generate_testpdfa3();		
	}
	
	
	
	
	public function updateAction() {		
		$v = $this->_request->getParams();		
		$this->_helper->viewRenderer->setNoRender();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
	
		$Project = new Project();
		$data = array(
			$v['field'] => $v['fieldvalue']
		);
		$Project->update( $data , 'project_id='.$v['fieldid'] );

	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function testv2Action() {	
		$v = $this->_request->getParams();		
		$vPost = $this->_request->getPost();	
		$this->_helper->viewRenderer->setNoRender();
		
		ob_start();
		var_dump( Lib_Calculation::categoryProductCompany($v['id']) );
		echo nl2br(ob_get_clean());
	}

	

}
