<?php

/**
 * DocumentsController - app core
 * 
 * @author Lukáš Havlíček
 * @version 1.0
 */

class DocumentsController extends Zend_Controller_Action 
{ 	
	public function init()
	{
		$this->view->topmenu = 2;
		$category = (int) $this->_getParam('section');
		$this->view->leftmenu = $category;
		
		$table = new Categoryies();
		$this->view->item = $table->fetchRow($table->select()->where('id_category = ?', $category));
	}
	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
    	$category = (int) $this->_getParam('section', 0);
    	
    	$table = new Categoryies();
    	
    	if ($category) {
			$this->view->item = $table->fetchRow($table->select()->where('id_category = ?', $category));    		
    	} else {
    		$class = new stdClass();
    		$class->category_name = '';
    		$class->id_category = 0;
    		$this->view->item = $class;
    	}
    	
    	
		$user = Zend_Registry::get('user');
		$isLoggedAdmin = Zend_Registry::get('isLoggedAdmin');    	
    	$categoryList = $table->getAllDescendants($category);
    	
		$table = new Rights();
		$select = $table->getDocuments($user->id_user, $categoryList, $isLoggedAdmin);
		
		$page = (int) $this->_getParam('page');
    	if ($page < 1  || !$page) $page = 1;
    	
    	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($select));
    	$paginator->setCurrentPageNumber($page);
    	$paginator->setItemCountPerPage(15);
    	$paginator->setPageRange(10);
    	
    	$this->view->data = $paginator;
    	$this->view->page = $page;
    }
    
    public function addAction()
    {
    	$form = $this->getForm(true);
    	$category = (int) $this->_getParam('section');
    	
    	$user = Zend_Registry::get('user');
    	
    	$rights = new Rights();
    	$rightsA = $rights->getCategoryRights($user->id_user, $user->super_admin);
    	
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			$table = new Documents();
    			
    			if (!$form->doc_file->receive()) {
					$this->_redirect('/documents/add');
    			}

				$location = $form->doc_file->getFileName();
				
    			$values = $form->getValues();
    			
    			if ((int)$rightsA[$values['id_category']]['add'] != 1) $this->_redirect('/documents');
				
    			$filename = $values['doc_file'];
    			unset($values['doc_file']);
    			
    			$values['doc_created'] = new Zend_Db_Expr('NOW()');
    			$values['doc_active'] = true;
    			$values['id_user'] = $user->id_user;
    			$idDoc = $table->insert($values);
    			
    			
    			$parts = explode('.', $filename);
    			$ext = end($parts);
    			
    			$newName = $idDoc . '-' . substr(sha1(time() . 'asde'), 1, 21) . '.file';
    			
    			rename($location, './data/documents/' . $newName);
    			
    			
    			$ver = new Versions();
    			
    			$data['id_document'] = $idDoc;
    			$data['id_user'] = $user->id_user;
    			$data['ver_number'] = 1;
    			$data['ver_file'] = $newName;
    			$data['ver_filename'] = $filename;
    			$data['ver_added'] = new Zend_Db_Expr('NOW()');
    			
    			$idVersion = $ver->insert($data);
    			
    			$users = new Users();
    			$allUsers = array();
    			$rows = $users->fetchAll(true);
    			foreach ($rows as $i) {
    				$allUsers[] = $i->id_user;
    			}
    			
    			$conf = new VersionConfirm();
    			foreach ($allUsers as $i) {
    				$vals = array();
    				$vals['id_version'] = $idVersion;
    				$vals['id_user'] = $i;
    				
    				$conf->insert($vals);	
    			}
    			
    			$hist = new History();
    			
    			$data2['id_document'] = $data['id_document']; 
    			$data2['id_user'] = $data['id_user']; 
    			$data2['history_added'] = new Zend_Db_Expr('NOW()');
    			$data2['history_action'] = 'doc_added';
    			
    			$hist->insert($data2);
    			
    			$this->_redirect('/documents/index/section/' . $category . '/msg/1');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    		
    	}
    	
    	$this->view->form = $form;
    	$this->view->rights = $rightsA;
    	
    	$this->view->edit = 0;
    	$this->render('add-edit');
    }
    
    public function detailAction()
    {
    	$form = $this->getForm(true);
    	$table = new Documents();
    	$category = (int) $this->_getParam('section');
    	
    	$user = Zend_Registry::get('user');
    	
    	$rights = new Rights();
    	$rightsA = $rights->getCategoryRights($user->id_user, $user->super_admin);
    	
    	if ($this->_request->isPost()) {
    		
    		if ($form->isValid($_POST)) {
    			
    			$values = $form->getValues();
    			
    			$where  = $table->getAdapter()->quoteInto('id_document = ?', $values['id_document']);
    			
    			$idDocument = $values['id_document'];
    			unset($values['id_document']);
    			unset($values['doc_file']);
    			if ($table->update($values, $where)) {
    				
    				$hist = new History();
    			
	    			$data2['id_document'] = $idDocument;
	    			$data2['id_user'] = $user->id_user; 
	    			$data2['history_added'] = new Zend_Db_Expr('NOW()');
	    			$data2['history_action'] = 'doc_edited';
	    			
	    			$hist->insert($data2);
    			}
    			$this->_redirect('/documents/detail/id/' . $idDocument . '/msg/2');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    		
    	}
    	
    	$id = (int) $this->_getParam('id');
    	
    	$this->view->docRights = $rights->getDocRights($user->id_user, $id, $user->super_admin);
    	
    	$row = $table->fetchRow($table->select()->where('id_document = ?', $id));
    	if (!$row) $this->_redirect('/documents');
    	
    	$form->populate($row->toArray());
    	
    	$this->view->form = $form;
    	$this->view->rights = $rightsA;
    	$this->view->id_category = $category;
    	$this->view->edit = 1;
    	
    	//versions and revisions
    	
    	$tableVer = new Versions();
    	$versions = $tableVer->fetchAll(
    					$tableVer->select()->setIntegrityCheck(false)
    							 ->from(array('v' => $tableVer->info('name')),
    							 			array(
    							 				'v.id_version',
    							 				'v.id_document',
    							 				'v.id_user',
    							 				'v.ver_note',
    							 				'u.user_firstname AS firstname',
    							 				'u.user_surname AS surname',
    							 				'v.ver_number',
    							 				'v.ver_added'
    							 			)
    							 	)
    							 ->where('id_document = ?', $id)
    							 ->joinLeft(array('u' => 'iso_users'), 'u.id_user = v.id_user', 'u.id_user')
    							 ->order('ver_number DESC')
    					);
    					

    	$versAndRevs = array();
    	
    	$tableRev = new Revisions();
    	foreach ($versions as $i) {
    		$revisions = $tableRev->fetchAll(
    					 	$tableRev->select()->setIntegrityCheck(false)
    							     ->from(array('r' => $tableRev->info('name')),
    							 			array(
    							 				'r.id_revision',
    							 				'r.id_version',
    							 				'r.id_user',
    							 				'r.rev_note',
    							 				'u.user_firstname AS firstname',
    							 				'u.user_surname AS surname',
    							 				'r.rev_number',
    							 				'r.rev_added'
    							 			)
    							 	)
    							 	 ->where('r.id_version = ?', $i->id_version)
    							 	 ->joinLeft(array('u' => 'iso_users'), 'u.id_user = r.id_user', 'u.id_user')
    							 	 ->order('rev_number DESC')
    				      );
    				      
   			$revs = array();
   			foreach ($revisions as $j) {
   				$revs[] = $j;
   			}
   			
   			$versAndRevs[] = array('ver' => $i, 'revs' => $revs);
    			
    		
    		
    	}
    	
		$this->view->versions = $versAndRevs;
    	$this->render('add-edit');
    }
    
    private function getForm($rootLess = false)
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    				
    	$form->addElement(new Zend_Form_Element_Text(array(
    					'name'	=> 'doc_name',
    					'label' => 'Název dokumentu',
    					'required' => true
    				)));
    				
    	$table = new Categoryies();
    	$multi = $table->getParentsForSelect($rootLess);
    				
    	$form->addElement(new Zend_Form_Element_Select(array(
    					'name'	=> 'id_category',
    					'multioptions'	=> $multi
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Textarea(array(
    					'name'	=> 'doc_note',
    					'label'	=> 'poznamka-f'
    				)));
    				
    	$form->addElement(new Zend_Form_Element_File(array(
    					'name'	=> 'doc_file',
    					'destination' => './data/tmp',
    					
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Hidden(array(
    					'name'	=> 'id_document'
    				)));
    	
    	return $form;
    }
    
    public function documentAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$ver = (int) $this->_getParam('ver', 0);
    	$rev = (int) $this->_getParam('rev', 0);
    	
    	if (!$id || (!$ver && !$rev)) $this->_redirect('/');
    	
    	if ($ver) {
    		
    		$table = new Versions();
    		$row = $table->fetchRow($table->select()->where('id_version = ?', $ver));		
    		$pointer = 'ver_file';
    		$filepointer = 'ver_filename';
    		
    	} elseif ($rev) {
    		
			$table = new Revisions();
    		$row = $table->fetchRow($table->select()->where('id_revision = ?', $rev));
    		$pointer = 'rev_file';
    		$filepointer = 'rev_filename';
    		
    	}
    
    	
    	if (!$row) $this->_redirect('/');
    	
    	
    	$filename = './data/documents/' . $row->$pointer;
		if (is_file($filename)) {
			$ext = end(explode('.', $row->$pointer));
			
			switch( $ext ) {
			  	case "pdf": $ctype="application/pdf"; break;
			  	case "exe": $ctype="application/octet-stream"; break;
			  	case "zip": $ctype="application/zip"; break;
			  	case "doc": $ctype="application/msword"; break;
			  	case "xls": $ctype="application/vnd.ms-excel"; break;
			  	case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			  	case "gif": $ctype="image/gif"; break;
			  	case "png": $ctype="image/png"; break;
			  	case "jpeg":
			  	case "jpg": $ctype="image/jpg"; break;
			  	case "mp3": $ctype="audio/mpeg"; break;
			  	case "wav": $ctype="audio/x-wav"; break;
			  	case "mpeg":
			  	case "mpg":
			  	case "mpe": $ctype="video/mpeg"; break;
			  	case "mov": $ctype="video/quicktime"; break;
			  	case "avi": $ctype="video/x-msvideo"; break;
			  	case "txt": $ctype="text/plain"; break;
			
			 	//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
			 	case "php":
			 	case "html":
			  	case "htm": die("<b>Cannot be used for '$ext' files!</b>"); break;
			  	default:    $ctype="application/force-download";
			}
			
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: public"); 
			header("Content-Description: File Transfer"); 
		    header("Content-Type: $ctype");
		    header("Content-Length: " . filesize($filename));
		    header("Content-Disposition: attachment; filename={$row->$filepointer};");
			header("Content-Transfer-Encoding: binary"); 
		    readfile($filename);
		    exit;
		} else {
			$this->_redirect('/documents/detail/id/'. $id);
		}
		
		die();

    }
    
    public function allUsersAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	$table = new Documents();
    	
    	$row = $table->fetchRow($table->select()->where('id_document = ?', $id)->where('doc_active = 1'));
    	
    	if (!$row) $this->_redirect('/documents');
    	
	    $rights = new Rights();
	    	$select = $rights->select()->setIntegrityCheck(false)
	    					 ->from(array('r' => 'iso_rights_group_category'), array(
	    					 			'r.id_rights',
	    					 			'r.id_group',
	    					 			'g.group_name',
	    					 			'u.user_firstname',
	    					 			'u.user_surname',
	    					 		))
	    				     ->joinLeft(array('g' => 'iso_groups'), 'g.id_group = r.id_group', 'g.id_group')
	    				     ->joinLeft(array('ug' => 'iso_user_group'), 'ug.id_group = g.id_group', 'ug.id_group')
	    				     ->joinLeft(array('u' => 'iso_users'), 'ug.id_user = u.id_user', 'u.id_user')
	    				     ->where('r.id_category = ?', $row->id_category)
	    				     ->where('r.rights_active = 1')
	    				     ->where('ug.active = 1')
	    				     ->where('u.user_active = 1')
	    				     ->where('r.read = 1');
	    				     
	    				    
	    $rows = $rights->fetchAll($select);
	    
	    $result = array();
	    foreach ($rows as $i) {
	    		
	    	if (!isset($result[$i->id_user])) {
	    	
	    		$result[$i->id_user] = $i->toArray();
	    		$result[$i->id_user]['group_name'] = array($i->id_group => $result[$i->id_user]['group_name']);
	    	} else {
	    		$result[$i->id_user]['group_name'][$i->id_group] = $i->group_name;
	    	}
	    }
    	

    	$this->view->data = $result;	
    	$this->view->item = $row;	
    }
    
    public function addVersionAction()
    {
    	$id = (int) $this->_getParam('id', 0);
    	
    	$doc = new Documents();
    	$item = $doc->fetchRow($doc->select()->where('id_document = ?', $id));
    	
    	if (!$item) $this->_redirect('/documents');
    	
    	
    	$form = $this->getAddVerForm();
    	
    	$request = $this->getRequest();
    	
    	if ($request->isPost()) {
    		
    		if ($form->isValid($request->getPost())) {
    			
    			if (!$form->ver_file->receive() || $_FILES['ver_file']['name'] == null) {
					$this->_redirect('/documents/detail/id/' . $id);
    			}
				
				$location = $form->ver_file->getFileName();
    			
    			$user = Zend_Registry::get('user');
    			
    			$values = $form->getValues();
				
    			$filename = $values['ver_file'];
    			
    			$parts = explode('.', $filename);
    			$ext = end($parts);
    			
    			$newName = $id . '-' . substr(sha1(time()), 0 , 25) . '.file';
    			
    			rename($location, './data/documents/' . $newName);
    			
    			
    			$ver = new Versions();
    			
    			$data['id_document'] = $id;
    			$data['id_user'] = $user->id_user;
    			$data['ver_number'] = $ver->getVerNumberForInsert($id);
    			$data['ver_file'] = $newName;
    			$data['ver_filename'] = $filename;
    			$data['ver_added'] = new Zend_Db_Expr('NOW()');
    			
    			$idVersion = $ver->insert($data);
    			
    			
    			$users = new Users();
    			$allUsers = array();
    			$rows = $users->fetchAll(true);
    			foreach ($rows as $i) {
    				$allUsers[] = $i->id_user;
    			}
    			
    			$conf = new VersionConfirm();
    			foreach ($allUsers as $i) {
    				$vals = array();
    				$vals['id_version'] = $idVersion;
    				$vals['id_user'] = $i;
    				$vals['version_confirm_added'] = new Zend_Db_Expr('NOW()');
    				
    				$conf->insert($vals);	
    			}
    			
    			
    			
    			$hist = new History();
    			
    			$data2['id_document'] = $data['id_document']; 
    			$data2['id_user'] = $data['id_user']; 
    			$data2['history_added'] = new Zend_Db_Expr('NOW()');
    			$data2['history_action'] = 'ver_added';
    			
    			$hist->insert($data2);
    			
    			$this->_redirect('/documents/detail/id/' . $id . '/msg/1');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    	}
    	
    	$this->view->form = $form;
    	$this->view->item = $item;
    	
    	
    	
//    	$ver = new Versions();
//    	$rows = $ver->fetchAll($ver->select()->where('id_document = ?', $id));
//    	
//    	$vers = array();
//    	foreach ($rows as $i) {
//    		$vers[$i->id_version] = number_format($i->ver_number, 1, '.', '');
//    	}
//    	
//    	$this->view->vers = $vers;
    	
    		
    	
    	
    }
    
    private function getAddVerForm()
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    				
    				
    	$form->addElement(new Zend_Form_Element_File(array(
    					'name'	=> 'ver_file',
    					'label'	=> 'Soubor',
    					'required' => true,
    					'destination' => './data/tmp',
    					'validators' => array('notEmpty')
    					
    				)));
    				
    	$form->addElement(new Zend_Form_Element_Hidden(array(
    					'name'	=> 'id_document'
    				)));
    	
    	return $form;
    }
    
    public function addRevisionAction()
    {
    	
    	$id = (int) $this->_getParam('id', 0);
    	
    	$doc = new Documents();
    	$item = $doc->fetchRow($doc->select()->where('id_document = ?', $id));
    	
    	if (!$item) $this->_redirect('/documents');
    	
    	
    	$form = $this->getAddRevForm($id);
    	
    	$request = $this->getRequest();
    	
    	if ($request->isPost()) {
    		
    		if ($form->isValid($request->getPost())) {
    			
    			if (!$form->rev_file->receive()) {
					$this->_redirect('/documents/detail/id/' . $id);
    			}

				$location = $form->rev_file->getFileName();
				
    			
    			$user = Zend_Registry::get('user');
    			
    			$values = $form->getValues();
				
    			$filename = $values['rev_file'];
    			
    			$parts = explode('.', $filename);
    			$ext = end($parts);
    			
    			$newName = $id . '-' . substr(sha1(time()), 0 , 30) . '.file';
    			
    			rename($location, './data/documents/' . $newName);
    			
    			
    			$rev = new Revisions();
    			
    			$data['id_version'] = $values['id_version'];
    			$data['id_user'] = $user->id_user;
    			$data['rev_number'] = $rev->getRevNumberForInsert($values['id_version']);
    			$data['rev_file'] = $newName;
    			$data['rev_filename'] = $filename;
    			$data['rev_added'] = new Zend_Db_Expr('NOW()');
    			
    			$idRevision = $rev->insert($data);
    			
    			
    			$users = new Users();
    			$allUsers = array();
    			$rows = $users->fetchAll(true);
    			foreach ($rows as $i) {
    				$allUsers[] = $i->id_user;
    			}
    			
    			$conf = new RevisionConfirm();
    			foreach ($allUsers as $i) {
    				$vals = array();
    				$vals['id_revision'] = $idRevision;
    				$vals['id_user'] = $i;
    				$vals['revision_confirm_added'] = new Zend_Db_Expr('NOW()');
    				
    				$conf->insert($vals);	
    			}
    			
    			$hist = new History();
    			
    			$data2['id_document'] = $id; 
    			$data2['id_user'] = $data['id_user']; 
    			$data2['history_added'] = new Zend_Db_Expr('NOW()');
    			$data2['history_action'] = 'rev_added';
    			
    			$hist->insert($data2);
    			
    			$this->_redirect('/documents/detail/id/' . $id . '/msg/1');
    			
    		} else {
    			
    			$form->populate($form->getUnfilteredValues());
    			
    			if ($form->isErrors()) {
    				$helper = new FormHelper();
    				$errors = $helper->errorsToString($form);
    				$this->view->errors = $errors;
    			}
                        	
    		}
    	}
    	
    	$this->view->form = $form;
    	$this->view->item = $item;
    	
    }
    
    private function getAddRevForm($idDocument)
    {
    	$form = new Zend_Form();
    	$form->clearDecorators();
    	
    	$ver = new Versions();
    	$rows = $ver->fetchAll($ver->select()->where('id_document = ?', $idDocument)->order('ver_number DESC'));
    	
    	$vers = array();
    	foreach ($rows as $i) {
    		$vers[$i->id_version] = number_format($i->ver_number, 1, '.', '');
    	}
    	
    	
    	
    	$form->addElement(new Zend_Form_Element_Select(array(
    					'name'	=> 'id_version',
    					'multioptions' => $vers
    					
    				)));
    				
    				
    	$form->addElement(new Zend_Form_Element_File(array(
    					'name'	=> 'rev_file',
    					'label'	=> 'Soubor',
    					'required' => true,
    					'destination' => './data/tmp',
    					'validators' => array('notEmpty')
    					
    				)));
    				
    	return $form;
    }
    
    public function activateAction()
    {
    	$isLoggedAdmin = Zend_Registry::get('isLoggedAdmin');
    	$id = (int) $this->_getParam('id', 0);
    	$section = (int) $this->_getParam('section', 0);
    	$page = (int) $this->_getParam('page', 1);
    	if ($id && $isLoggedAdmin) $this->changeState($id, 1, $section, $page);
    	$this->_redirect('/documents/index/section/' . $section);
    }
    
    public function deactivateAction()
    {	
    	$isLoggedAdmin = Zend_Registry::get('isLoggedAdmin');
    	$id = (int) $this->_getParam('id', 0);
    	$section = (int) $this->_getParam('section', 0);
    	$page = (int) $this->_getParam('page', 1);
    	if ($id && $isLoggedAdmin) $this->changeState($id, 0, $section, $page);
    	$this->_redirect('/documents/index/section/' . $section);
    }
    
    private function changeState($id, $state, $section, $page)
    {
    	$table = new Documents();
    	$row = $table->fetchRow($table->select()->where('id_document = ?', (int) $id));
    	if ($row) {
    		$row->doc_active = (int) $state;
    		$row->save();
    		$this->_redirect('/documents/index/msg/4/section/' . $section . '/page/' . $page);
    	} else {
    		$this->_redirect('/documents/index/section/' . $section . '/page/' . $page);
    	}
    }
    
    public function deleteAction()
    {
    	$id   = (int) $this->getRequest()->getParam('id', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$user = Zend_Registry::get('user');
    	
    	$rights = new Rights();
    	
    	
    	if (!$rights->isAllowed($user->id_user, $id, 'del', $user->super_admin)) $this->_redirect('/documents');
    	
    	$table = new Documents();
    	
    	
    	if ($thru && $id) {

    		$row = $table->fetchRow($table->select()->where('id_document = ?', (int) $id));
    		if (!$row) $this->_redirect('/documents');
    		
	    		$row->delete();

	    		$versions = new Versions();
	    		$verConf = new VersionConfirm();
	    		
	    		$rows = $versions->fetchAll($versions->select()->where('id_document = ?', $id));
	    		$versionsIDS = array();
	    		
	    		foreach ($rows as $i) {
	    			$versionsIDS[] = $i->id_version;
	    			@unlink('./data/documents/' . $i->ver_file);
	    			
	    			$row = $verConf->fetchRow($verConf->select()->where('id_version = ?', $i->id_version));
	    			if ($row) {
	    				$row->delete();
	    			}
	    			
	    			$i->delete();
	    		}
	    		
	    		$revisions = new Revisions();
	    		$revConf = new RevisionConfirm();
	    		
	    		foreach ($versionsIDS as $i) {
	    			
	    			$row = $revisions->fetchRow($revisions->select()->where('id_version = ?', $i));
	    			if ($row) {
	    				@unlink('./data/documents/' . $row->rev_file);
	    			
		    			$row2 = $revConf->fetchRow($revConf->select()->where('id_revision = ?', $row->id_revision));
		    			if ($row2) {
		    				$row2->delete();
		    			}
	    				$row->delete();
	    			}
	    			
	    		}
	    		
	    		$this->_redirect('/documents/index/msg/4/section/' . $section . '/page/' . $page);
    	}
    		
    	
    	if ($this->_request->isPost()) {
    		$id = (int) $this->_request->getPost('id');
    		
    		if (!$rights->isAllowed($user->id_user, $id, 'del', $user->super_admin)) $this->_redirect('/');
    		
    		if ($id) {
    			$row = $table->fetchRow($table->select()->where('id_document = ?', (int) $id));
    		if (!$row) $this->_redirect('/documents');
    		
	    		$row->delete();

	    		$versions = new Versions();
	    		$verConf = new VersionConfirm();
	    		
	    		$rows = $versions->fetchAll($versions->select()->where('id_document = ?', $id));
	    		$versionsIDS = array();
	    		
	    		foreach ($rows as $i) {
	    			$versionsIDS[] = $i->id_version;
	    			@unlink('./data/documents/' . $i->ver_file);
	    			
	    			$row = $verConf->fetchRow($verConf->select()->where('id_version = ?', $i->id_version));
	    			if ($row) {
	    				$row->delete();
	    			}
	    			
	    			$i->delete();
	    		}
	    		
	    		$revisions = new Revisions();
	    		$revConf = new RevisionConfirm();
	    		
	    		foreach ($versionsIDS as $i) {
	    			
	    			$row = $revisions->fetchRow($revisions->select()->where('id_version = ?', $i));
	    			if ($row) {
	    				@unlink('./data/documents/' . $row->rev_file);
	    			
		    			$row2 = $revConf->fetchRow($revConf->select()->where('id_revision = ?', $row->id_revision));
		    			if ($row2) {
		    				$row2->delete();
		    			}
	    				$row->delete();
	    			}
	    			
	    		}
	    		
	    		$this->_redirect('/documents/index/msg/4/section/' . $section . '/page/' . $page);
    		} else {
    			$this->_redirect('/admin/documents');
    		}
    	} else {
    		$row = $table->fetchRow($table->select()->where('id_document = ?', $id));
    		if ($row) {
    			$this->view->data = $row;
    		} else {
    			$this->_redirect('/admin/documents');
    		}
    	}
    }
    
    
    public function deleteVersionAction()
    {
    	$id   = (int) $this->getRequest()->getParam('id', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$user = Zend_Registry::get('user');
    	
    	$rights = new Rights();
    	
    	if (!$id) $this->_redirect('/documents');
    	
    	$ver = new Versions();
    	$version = $ver->fetchRow($ver->select()->where('id_version = ?', $id));
    	
    	if (!$version) $this->_redirect('/documents');
    
    	if (!$rights->isAllowed($user->id_user, $version->id_document, 'del', $user->super_admin)) $this->_redirect('/documents');
    			
    	if ($thru) {

	    	//delete version document
    		@unlink('./data/documents/' . $version->ver_file);
    		
    		//delete this version revisions
    		$revisions = new Revisions();
	    	$revConf = new RevisionConfirm();
	    		
	    			
    		$rows = $revisions->fetchAll($revisions->select()->where('id_version = ?', $version->id_version));

    		foreach ($rows as $i) {
    			@unlink('./data/documents/' . $i->rev_file);
	    			
		    	$rows2 = $revConf->fetchAll($revConf->select()->where('id_revision = ?', $i->id_revision));
		    	foreach ($rows2 as $j) {
		    		$j->delete();
		    	}
	    		
		    	$i->delete();
	    	}
    		
    		
    		$verConf = new VersionConfirm();
    		$rows3 = $verConf->fetchAll($verConf->select()->where('id_version = ?', $version->id_version));
    		foreach ($rows3 as $i) {
		    	$i->delete();
		    }
		    
		    $idDoc = $version->id_document;
		    
		    if ($version->delete()) {
		    	$this->_redirect('/documents/detail/id/' . $idDoc . '/msg/4#versrefs');	
		    }
	    	
		    $this->_redirect('/documents/detail/id/' . $idDoc . '/msg/5#versrefs');
    		
    	}
    		

    	$row = $ver->fetchRow($ver->select()->setIntegrityCheck(false)
    							  ->from(array('v' => 'iso_versions'), array(
    							      			'v.id_version',
    							  				'v.ver_number'								
    							      ))
    							  ->join(array('d' => 'iso_documents'), 'v.id_document = d.id_document', array('d.id_document','d.doc_name'))
    							  ->where('v.id_version = ?', $version->id_version));
    	if ($row) {
    		$this->view->data = $row;
    	} else {
    		$this->_redirect('/documents');
   		}
    }
    
    public function deleteRevisionAction()
    {
    	$id   = (int) $this->getRequest()->getParam('id', 0);
    	$thru = (int) $this->_getParam('thru', 0);
    	
    	$user = Zend_Registry::get('user');
    	
    	$rights = new Rights();
    	
    	if (!$id) $this->_redirect('/documents');
    	
    	$rev = new Revisions();
    	$revision = $rev->fetchRow($rev->select()->where('id_revision = ?', $id));
    	
    	if (!$revision) $this->_redirect('/documents');
    	
    	$ver = new Versions();
    	$version = $ver->fetchRow($ver->select()->where('id_version = ?', $revision->id_version));
    	
    	if (!$version) $this->_redirect('/documents');
    
    	if (!$rights->isAllowed($user->id_user, $version->id_document, 'del', $user->super_admin)) $this->_redirect('/documents');
    			
    	if ($thru) {

	    	//delete version document
    		@unlink('./data/documents/' . $revision->rev_file);
    		
	    	$revConf = new RevisionConfirm();
			$rows = $revConf->fetchAll($revConf->select()->where('id_revision = ?', $revision->id_revision));
	    			
    		foreach ($rows as $i) {
		    	$i->delete();
		    }
	    		
		    
		    $idDoc = $version->id_document;
		    
		    if ($revision->delete()) {
		    	$this->_redirect('/documents/detail/id/' . $idDoc . '/msg/6#versrefs');	
		    }
	    	
		    $this->_redirect('/documents/detail/id/' . $idDoc . '/msg/7#versrefs');
    		
    	}
    		

    	$row = $rev->fetchRow($rev->select()->setIntegrityCheck(false)
    							  ->from(array('r' => 'iso_revisions'), array(
    							      			'r.id_revision',
    							  				'r.rev_number'								
    							      ))
    							  ->join(array('v' => 'iso_versions'), 'v.id_version = r.id_version', array('v.id_version','v.ver_number'))
    							  ->join(array('d' => 'iso_documents'), 'v.id_document = d.id_document', array('d.id_document','d.doc_name'))
    							  ->where('v.id_version = ?', $version->id_version));
    	if ($row) {
    		$this->view->data = $row;
    	} else {
    		$this->_redirect('/documents');
   		}
    }
    
    
    public function noteVersionAction()
    {
    	$id = $this->_getParam('id', 0);
    	if (!$id) $this->_redirect('/documents');
    	
    	$table = new Versions();
    	$row = $table->fetchRow($table->select()->setIntegrityCheck(false)->from($table)
    								  ->joinUsing('iso_documents', 'id_document')
    								  ->where('id_version = ?', $id));
    	
    	if (!$row) $this->_redirect('/documents');
    	
    	$user = Zend_Registry::get('user');

    	$rights = new Rights();
    	if (!$rights->isAllowed($user->id_user, $row->id_document, 'edit', $user->super_admin));
    	
    	if ($this->_request->isPost()) {
    		$row2 = $table->fetchRow($table->select()
 	   								  	  ->where('id_version = ?', $id));
 	   								  	  
 	  		if ($row2) {
 	  			$row2->ver_note = $this->_request->getPost('note');
 	  			$row2->save();
 	  		}
 	  		
 	  		$this->_redirect('/documents/detail/id/' . $row->id_document . '#vershrefs');
    	}
    	
    	$this->view->note = $row->ver_note;
    	$this->view->id   = $row->id_version;
    	$this->view->ver_number   = $row->ver_number;
    	$this->view->rev_number   = 0;
    	$this->view->id_document  = $row->id_document;
    	$this->view->doc_name   = $row->doc_name;
    	$this->view->version = true;
    	
    	$this->render('note-edit');
    }
    
    public function noteRevisionAction()
    {$id = $this->_getParam('id', 0);
    	if (!$id) $this->_redirect('/documents');
    	
    	$table = new Revisions();
    	$row = $table->fetchRow($table->select()->setIntegrityCheck(false)->from(array('r' => 'iso_revisions'))
    								  ->join(array('v' => 'iso_versions'), 'v.id_version = r.id_version')							  
    								  ->join(array('d' => 'iso_documents'), 'd.id_document = v.id_document')
    								  ->where('id_revision = ?', $id));
    	
    	if (!$row) $this->_redirect('/documents');
    	
    	$user = Zend_Registry::get('user');

    	$rights = new Rights();
    	if (!$rights->isAllowed($user->id_user, $row->id_document, 'edit', $user->super_admin));
    	
    	if ($this->_request->isPost()) {
    		$row2 = $table->fetchRow($table->select()
 	   								  	  ->where('id_revision = ?', $id));
 	   								  	  
 	  		if ($row2) {
 	  			$row2->rev_note = $this->_request->getPost('note');
 	  			$row2->save();
 	  		}
 	  		
 	  		$this->_redirect('/documents/detail/id/' . $row->id_document . '#vershrefs');
    	}
    	
    	$this->view->note = $row->rev_note;
    	$this->view->id   = $row->id_revision;
    	$this->view->ver_number   = $row->ver_number;
    	$this->view->id_document  = $row->id_document;
    	$this->view->rev_number   = $row->rev_number;
    	$this->view->doc_name   = $row->doc_name;
    	$this->view->version = false;
    	
    	$this->render('note-edit');
    }
    
    public function versionConfirmSummaryAction()
    {
    	$isLoggedAdmin = Zend_Registry::get('isLoggedAdmin');
    	if (!$isLoggedAdmin) $this->_redirect('/documents');
    	
    	$id = $this->_getParam('id', 0);
    	if (!$id) $this->_redirect('/documents');
    	
    	$table = new Versions();
    	$row = $table->fetchRow($table->select()->setIntegrityCheck(false)->from($table)
    								  ->joinUsing('iso_documents', 'id_document')
    								  ->where('id_version = ?', $id));
    	
    	if (!$row) $this->_redirect('/documents');
    	
    	
    	$table = new VersionConfirm();
    	$rows = $table->fetchAll($table->select()->setIntegrityCheck(false)->from(array('vc' => 'iso_version_confirm'))
    								  ->join(array('v' => 'iso_versions'), 'v.id_version = vc.id_version')							  
    								  ->join(array('u' => 'iso_users'), 'u.id_user = vc.id_user')
    								  ->where('vc.id_version = ?', $id)
    								  ->where('vc.version_confirm_confirmed IS NOT NULL'));
    	
    	$this->view->data = $rows;
    	$this->view->version = true;
    	
    	$this->view->ver_number   = $row->ver_number;
    	$this->view->id_document  = $row->id_document;
    	$this->view->rev_number   = 0;
    	$this->view->doc_name   = $row->doc_name;
    	$this->render('confirm-summary');
    }
    
    public function revisionConfirmSummaryAction()
    {
    	$isLoggedAdmin = Zend_Registry::get('isLoggedAdmin');
    	if (!$isLoggedAdmin) $this->_redirect('/documents');
    	
    	$id = $this->_getParam('id', 0);
    	if (!$id) $this->_redirect('/documents');
    	
    	$table = new Revisions();
    	$row = $table->fetchRow($table->select()->setIntegrityCheck(false)->from(array('r' => 'iso_revisions'))
    								  ->join(array('v' => 'iso_versions'), 'v.id_version = r.id_version')							  
    								  ->join(array('d' => 'iso_documents'), 'd.id_document = v.id_document')
    								  ->where('id_revision = ?', $id));
    	
    	if (!$row) $this->_redirect('/documents');
    	
    	
    	$table = new RevisionConfirm();
    	$rows = $table->fetchAll($table->select()->setIntegrityCheck(false)->from(array('rc' => 'iso_revision_confirm'))
    								  ->join(array('r' => 'iso_revisions'), 'r.id_revision = rc.id_revision')							  
    								  ->join(array('v' => 'iso_versions'), 'v.id_version = r.id_version')							  
    								  ->join(array('u' => 'iso_users'), 'u.id_user = rc.id_user')
    								  ->where('rc.id_revision = ?', $id)
    								  ->where('rc.revision_confirm_confirmed IS NOT NULL'));
    	
    	$this->view->data = $rows;
    	$this->view->version = false;
    	
    	$this->view->ver_number   = $row->ver_number;
    	$this->view->id_document  = $row->id_document;
    	$this->view->rev_number   = $row->rev_number;
    	$this->view->doc_name   = $row->doc_name;
    	$this->render('confirm-summary');
    }
}
