<?php

/**
 * MessagesController - handles messages being sent between users
 * 
 * @author Lukáš Havlíček
 * @version 1.0
 */

class MessagesController extends Zend_Controller_Action 
{ 	
	public function init()
	{
		$this->view->topmenu = 5;
	}
	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
    	$this->view->leftmenu = 2;
    	$this->view->recieved = true;
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()->setIntegrityCheck(false)
       					->from($table)
       					->joinLeft('iso_users', 'iso_users.id_user = iso_messages.id_sender')
       					->where('id_reciever = ?', $ID)
       					->where('is_bin = 0')
       					->order(new Zend_Db_Expr('is_read ASC, datetime DESC'));
		
		$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;
    }
    
    public function sentAction() 
    {
    	
    	$this->view->leftmenu = 3;
    	$this->view->recieved = false;
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()->setIntegrityCheck(false)
       					->from($table)
       					->joinLeft('iso_users', 'iso_users.id_user = iso_messages.id_reciever')
       					->where('id_sender = ?', $ID)
       					->where('is_bin = 0')
       					->order(new Zend_Db_Expr('is_read ASC, datetime DESC, id_message DESC'));
		
		$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->render('index');
    }
    
    public function binAction() 
    {
    	$this->view->leftmenu = 4;
    	$ID = Zend_Registry::get('user')->id_user;
    	
		$recieved = (int) $this->_getParam('recieved', 1);
	
		$this->view->recieved = $recieved;
			
        $table = new Messages();
       	$select = $table->select()->setIntegrityCheck(false)
       					->from('iso_messages', array('*'));
       					
       	if ($recieved) {
       		$select->joinLeft('iso_users', 'iso_users.id_user = iso_messages.id_sender')
       			   ->where("id_reciever = $ID");
       	} else {
       		$select->joinLeft('iso_users', 'iso_users.id_user = iso_messages.id_reciever')
       			   ->where("id_sender = $ID");
       	}
       	
       	$select->where('is_bin = 1')
       		   ->order(new Zend_Db_Expr('is_read ASC, datetime DESC, id_message DESC'));
		
		$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;
    }
    
    public function detailAction() 
    {
    	$message = (int) $this->_getParam('id');
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()->setIntegrityCheck(false)
       					->from('iso_messages as m', array('m.*'))
       					->joinLeft('iso_users as p', 'p.id_user = m.id_sender', array('p.id_user as senderID', 'p.user_firstname as sendername', 'p.user_surname as sendersurname'))
       					->joinLeft('iso_users as q', 'q.id_user = m.id_reciever', array('q.id_user as recieverID', 'q.user_firstname as recievername', 'q.user_surname as recieversurname'))
       					->where('m.id_message = ?', $message)
       					->where("m.id_sender = $ID or m.id_reciever = $ID");
       					
    	$row = $table->fetchRow($select);
    	if ($row) {
    		$this->view->data = $row;
    		
    		$this->view->recieved = true;
    		if ($row->id_sender == $ID) {
    			$this->view->recieved = false;
    		}
    		
    		if ($ID == $row->id_reciever) {
    			$where = $table->getAdapter()->quoteInto('id_message = ?', $message);
	    		$table->update(array('is_read' => 1), $where);
    		}
    		
    	} else {
    		$this->_redirect();
    	}

    }
    
    public function trashAction() 
    {
    	$message = (int) $this->_getParam('id');
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()
       					->where('id_message = ?', $message)
       					->where("id_sender = $ID OR id_reciever = $ID");
       					
    	$row = $table->fetchRow($select);
    	if ($row) {
    		$row->is_bin = 1;
    		$row->save();
    		
    		if ($row->id_reciever == $ID) {
    			$this->_redirect('/messages/index/msg/1');
    		} else {
    			$this->_redirect('/messages/sent/msg/1');
    		}
    	} else {
    		$this->_redirect('/');
    	}

    }
    
    public function inboxAction() 
    {
    	$message = (int) $this->_getParam('id');
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()
       					->where('id_message = ?', $message)
       					->where("id_sender = $ID OR id_reciever = $ID");

       	$row = $table->fetchRow($select);
    	if ($row) {
    		$row->is_bin = 0;
    		$row->save();
    		
    		if ($row->id_reciever == $ID) {
    			$this->_redirect('/messages/bin');
    		} else {
    			$this->_redirect('/messages/bin/recieved/0');
    		}
    	} else {
    		$this->_redirect('/');
    	}

    }
    
    public function multiAction() {
    	
    	$ids = $this->_request->getPost('event');
    	$action = (int) $this->_request->getPost('action');
    	
    	switch ($action) {
    		case 1:
    			$this->multiMark($ids, 1);
    			break;
    			
    		case 2:
    			$this->multiMark($ids, 0);
    			break;
    			
    		case 3:
    			$this->multiTrash($ids);
    			break;
    	
    		default:
    			break;
    	}
    	
    }
    
    public function markAction() 
    {
    	$message = (int) $this->_getParam('id');
    	$this->multiMark(array($message), 1);
    }
    
    public function unmarkAction() 
    {
    	$message = (int) $this->_getParam('id');
    	$this->multiMark(array($message), 0);
    }
    
    private function multiMark($ids, $set_read)
    {
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()
       					->where('id_message IN (' . implode(',', $ids) . ')')
       					->where("id_sender = $ID OR id_reciever = $ID");

       	$rows = $table->fetchAll($select);
    	foreach ($rows as $row) {
    		$row->is_read = (int) $set_read;
    		$row->save();
    	}
    		
    	if ($rows[0]->id_reciever == $ID) {
    		if ($rows[0]->is_bin) {
    			$this->_redirect('/messages/bin');
    		} else {
    			$this->_redirect('/messages');
    		}
    	} else {
    		if ($rows[0]->is_bin) {
    			$this->_redirect('/messages/bin/recieved/0');
    		} else {
    			$this->_redirect('/messages/sent');
    		}
    	}
    	
    	$this->_redirect('/');
    	
    }
    
    private function multiTrash($ids)
    {
    	$ID = Zend_Registry::get('user')->id_user;
    	
        $table = new Messages();
       	$select = $table->select()
       					->where('id_message IN (' . implode(',', $ids) . ')')
       					->where("id_sender = $ID OR id_reciever = $ID");

       	$rows = $table->fetchAll($select);
    	foreach ($rows as $row) {
    		$row->is_bin = 1;
    		$row->save();
    	}
    		
    	if ($rows[0]->id_reciever == $ID) {
    			$this->_redirect('/messages');
    	} else {
    			$this->_redirect('/messages/sent');
    	}
    	
    	$this->_redirect('/');
    }
    
    public function deleteAction()
    {
    	$ID = Zend_Registry::get('user')->id_user;
    	
    	$id = (int) $this->_getParam('id', 0);
    	
        $table = new Messages();
       	$select = $table->select()
       					->where('id_message = ? ', $id)
       					->where("id_sender = $ID OR id_reciever = $ID");

       	$row = $table->fetchRow($select);
       	if ($row) {
       		
       		$recieved = 0;
       		if ($row->id_reciever == $ID) {
       			$recieved = 1;
       		}
       		
       		$row->delete();
       		
       		if ($recieved) {
				$this->_redirect('/messages/bin/msg/2');       			
       		} else {
       			$this->_redirect('/messages/bin/recieved/0/msg/2');
       		}
       	}
    }
    
    public function newMessageAction()
    {
    	$this->view->leftmenu = 1;
    	$ID = Zend_Registry::get('user')->id_user;
    	
    	$users = new Users();
    	$userRows = $users->fetchAll(true, 'user_surname ASC');
    	$this->view->users = $userRows;
    	
    	$groups = new Groups();
    	$groupRows = $groups->fetchAll(true, 'group_name ASC');
    	$this->view->groups = $groupRows;
    	
    	$reciever = '';
    	$subject = '';
    	$body = '';
    	
    	$error = false;
    	$sent = false;
    	
    	$request = $this->getRequest();
    	if ($request->isPost())
    	{
    		$reciever 	= $request->getPost('reciever');
    		$subject 	= $request->getPost('subject');
    		$body 		= $request->getPost('body');
    		
    		if (!$reciever || !$subject || !$body) {
    			$error = true;
    		}
    		else
    		{
    			$recievers = array();
    			
    			if (substr($reciever, 0, 4) == 'user')
    			{
    				$recievers[] = substr($reciever, 5);
    			} 
    			elseif (substr($reciever, 0, 5) == 'group')
    			{
    				$idGroup = substr($reciever, 6);
    				$userGroup = new UserGroup();
    				$rows = $userGroup->fetchAll($userGroup->select()->where('id_group = ?', $idGroup)->where('active = 1'));
    				foreach ($rows as $i) {
						$recievers[] = $i->id_user;    					
    				}
    				
    			}
    			elseif ($reciever == 'all')
    			{
    				foreach ($userRows as $i) {
    					$recievers[] = $i->id_user;    					
    				}
    			}
    			
    			elseif ($reciever == 'all-admins')
    			{
    				foreach ($userRows as $i) {
    					if ($i->super_admin) 
    						$recievers[] = $i->id_user;    					
    				}
    			}
    			
    			elseif ($reciever == 'all-non-admins')
    			{
    				foreach ($userRows as $i) {
    					if (!$i->super_admin)
    						$recievers[] = $i->id_user;    					
    				}
    			}

    			
    			$data['body'] = $body;
    			$data['subject'] = $subject;
    			$data['is_bin'] = 0;
    			$data['is_read'] = 0;
    			$data['datetime'] = new Zend_Db_Expr('NOW()');
    			$data['id_sender'] = $ID;
    			
    			$table = new Messages(); 
    			
    			foreach ($recievers as $i) {
    				if ($data['id_sender'] != $ID) {
						$data['id_reciever'] = $i;
    					$table->insert($data);    					
    				}
    			}
    			
    			$sent = true;
    			
    		}
    	}    		
    	
    	$this->view->error = $error;
    	$this->view->sent = $sent;
    	
    	$this->view->reciever = $reciever;
    	$this->view->subject = $subject;
    	$this->view->body = $body;
    	
    }
}
