<?php
class MessagesController extends AppController 
{
    public $name = 'Messages';
    public $uses = array('Message', 'MessageComment', 'User', 'Profile');
    public $components = array('Activity', 'Notification');
    
    public function beforeFilter() 
    {
        parent::beforeFilter();
    }
    
    public function isAuthorized($user) 
    {
        //If member hasn't filled in profile redirect to Edit Profile
        if (!$this->User->access($this->Auth->user('id'))) {
            $this->Session->setFlash(__('You must first complete your profile.'), 
                'default', array('class' => 'alert alert-danger'));
            return $this->redirect(array('controller' => 'users', 'action' => 'edit', $this->Auth->user('id')));
        }
        
        //All members have access to these actions
        if (in_array($this->action, array('index', 'add'))) {
            return true;
        }
        
        //If item is for administrators only, only administrators have access to these actions. Else all members have access to these actions
        if (in_array($this->action, array('view'))) {
            $itemId = (int) $this->request->params['pass'][0];
            if ($this->Auth->user('role') == 'user') {
                $conditions = array(
                    'Message.id' => $itemId,
                    'Message.admin' => '0',
                    'Message.deleted' => 0
                ); 
            } else {
                $conditions = array(
                    'Message.id' => $itemId,
                    'Message.deleted' => 0
                ); 
            }
            $item = $this->Message->find('first', array(
                'conditions' => $conditions
            ));
            if (!empty($item)) {
                return true;
            }
        }
        
        //All members have access to these actions if the item is their own
        if (in_array($this->action, array('edit', 'delete'))) {
            $itemId = (int) $this->request->params['pass'][0];
            if ($this->Message->isOwnedBy($itemId, $user['id'])) {
                return true;
            }
        }
        
        if ($this->action === 'comment') {
            //All members have access to this action if the comment is their own
            if (!empty($this->request->data['MessageComment']['id'])) {
                // Update comment
                $itemId = (int) $this->request->data['MessageComment']['id'];
                if ($this->MessageComment->isOwnedBy($itemId, $user['id'])) {
                    return true;
                }
            } else {
                //All members have access to this action
                return true;
            }
        }
        
        //All members have access to these actions if the comment is their own
        if ($this->action === 'comment_delete') {
            $itemId = (int) $this->request->params['pass'][0];
            if ($this->MessageComment->isOwnedBy($itemId, $user['id'])) {
                return true;
            }
        }
    
        return parent::isAuthorized($user);
    }

    public function index() 
    {
        $this->Message->Behaviors->load('Containable');
        
        //Get all messages based on member role (administrator/user)
        if ($this->Auth->user('role') == 'user') {
            $conditions = array(
                'Message.admin' => '0',
                'Message.deleted' => 0
            ); 
        } else {
            $conditions = array(
                'Message.deleted' => 0
            ); 
        }
        if (Configure::read('CFG.users_follow')) {
            $user = $this->User->find('first', array(
                    'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
                )
            );            
            $user_id = $user['UserFollow'];
            $user_id[] = $this->Auth->user('id');
            
            $conditions['AND'] = array(
                'Message.user_id' => $user_id,
            );
        }
        $items = $this->Message->find('all', array(
            'conditions' => $conditions,
            'order' => array('Message.created DESC'),
            'contain' => array(
                'User' => array(
                    'Profile',
                ),
                'MessageComment' => array(
                    'User' => array(
                        'Profile',
                    ),
                ),
            ),
            'recursive' => 1
            )
        );
                
        App::uses('Pagination', 'Lib');
        $paginate = new Pagination($items, 12);
        if (isset($this->request->query['p']) && empty($paginate->data)) {
            return $this->redirect(array('action' => 'index'));
        }
        
        $this->set('items', $paginate);
        $this->set('title_for_layout', __('Messages'));
    }
    
    public function view($id = null) 
    {
        if (empty($id)) {
            return $this->redirect(array('action' => 'index'));
        }
        
        $this->Message->Behaviors->load('Containable');
        $item = $this->Message->find('first', array(
                'conditions' => array('Message.id' => $id, 'Message.deleted' => 0),
                'contain' => array(
                    'User' => array(
                        'Profile',
                    ),
                    'MessageComment' => array(
                        'User' => array(
                            'Profile',
                        ),
                    ),
                ),
            )
        );
        if (!$item) {
            return $this->redirect(array('action' => 'index'));
        }
        $this->set('item', $item);
        $this->set('title_for_layout', $item['Message']['title']);
    }
    
    public function add() 
    {
        //If data submitted save data
        if ($this->request->is('post')) {
            $this->request->data['Message']['user_id'] = $this->Auth->user('id');
            if ((isset($this->request->data['Message']['admin'])) && ($this->Auth->user('role') == 'user')) {
                //security check
                $this->request->data['Message']['admin'] = 0;
            }
            if ($this->Message->save($this->request->data)) {
                $this->Activity->log($this->Message->id, 'Message', 'add');
                
                // Notification
                if (isset($this->request->data['Message']['notify']) && $this->request->data['Message']['notify']) {           
                    $view_vars = array(
                        'title' => $this->request->data['Message']['title'],
                        'url' => Configure::read('CFG.site_url') . '/messages/view/' . $this->Message->id,
                    );
                    $this->Notification->push(
                        'item_add',
                        null,
                        $view_vars,
                        (isset($this->request->data['Message']['admin']) ? true : false)
                    );
                }
                
                $this->Session->setFlash(__('Message successfully saved'), 
                    'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('An error has occurred'), 
                'default', array('class' => 'alert alert-danger'));
        }
        $this->set('title_for_layout', __('Add Message'));
    }
    
    public function edit($id = null) 
    {
        if (empty($id)) {
            return $this->redirect(array('action' => 'index'));
        }
        
        //If data submitted save data
        if ($this->request->is('post')) {
            $this->request->data['Message']['id'] = $id;
            if ((isset($this->request->data['Message']['admin'])) && ($this->Auth->user('role') == 'user')) {
                //security check
                $this->request->data['Message']['admin'] = 0;
            }
            if ($this->Message->save($this->request->data)) {
                $this->Activity->log($this->Message->id, 'Message', 'edit');
                
                $this->Session->setFlash(__('Message successfully saved'), 
                    'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'view', $id));
            }
            $this->Session->setFlash(__('An error has occurred'), 
                'default', array('class' => 'alert alert-danger'));
            return $this->redirect(array('action' => 'index'));
        }
        
        //Find message to edit
        $this->Message->Behaviors->load('Containable');
        $item = $this->Message->find('first', array(
                'conditions' => array('Message.id' => $id, 'Message.deleted' => 0),
                'contain' => array(
                    'User' => array(
                        'Profile',
                    ),
                    'MessageComment' => array(
                        'User' => array(
                            'Profile',
                        ),
                    ),
                ),
            )
        );
        $this->set('item', $item);
        $this->set('title_for_layout', __('Edit Message'));
    }
    
    public function delete($id = null) 
    {
        $this->layout = false;
        $this->render = false;
        
        //Check if item exists; Else redirect to index
        if (!$id) {
            return $this->redirect(array('action' => 'index'));
        }
        $item = $this->Message->find('first', array(
                'conditions' => array('Message.id' => $id, 'Message.deleted' => 0),
            )
        );
        if (!$item) {
            return $this->redirect(array('action' => 'index'));
        }
        
        //Set deleted field to 1 for message
        $this->request->data['Message']['id'] = $id;
        $this->request->data['Message']['deleted'] = 1;
        if ($this->Message->save($this->request->data)) {
            $this->Activity->log($this->Message->id, 'Message', 'delete');
            
            $this->Session->setFlash(__('Message successfully deleted'), 
                'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('An error has occurred'), 
            'default', array('class' => 'alert alert-danger'));
        return $this->redirect(array('action' => 'index'));
    }
    
    public function comment($id = null) 
    {
        $this->layout = false;
        $this->render = false;
        
        if (empty($id)) {
            return $this->redirect(array('action' => 'index'));
        }
        
        //If data submitted save data
        if ($this->request->is('post')) {
            if (!empty($this->request->data['MessageComment']['id'])) {
                // Update comment
                $action = 'edit';
                $item_comment = $this->MessageComment->find('first', array(
                        'conditions' => array(
                            'MessageComment.id' => $this->request->data['MessageComment']['id'], 
                            'MessageComment.deleted' => 0
                        ),
                    )
                );
                if ((empty($item_comment)) || ($this->Auth->user('role') != 'admin')) {
                    // Comment is not created by logged in user and logged in user is not an admin => abort
                    return $this->redirect(array('action' => 'index'));
                }
            } else {
                // Add comment
                $action = 'add';
                $this->request->data['MessageComment']['message_id'] = $id;
                $this->request->data['MessageComment']['user_id'] = $this->Auth->user('id');
            }
            if ($this->MessageComment->save($this->request->data)) {
                $this->Activity->log($this->MessageComment->id, 'MessageComment', $action);
                
                $this->Session->setFlash(__('Reply successfully saved'), 
                    'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'view', $id));
            }
            
        }
        $this->Session->setFlash(__('An error has occurred'), 
            'default', array('class' => 'alert alert-danger'));
        return $this->redirect(array('action' => 'index'));
    }
    
    public function comment_delete($id = null) 
    {
        $this->layout = false;
        $this->render = false;
        
        //Check if comment exists; Else redirect to index
        if (!$id) {
            return $this->redirect(array('action' => 'index'));
        }
        $item_comment = $this->MessageComment->find('first', array(
                'conditions' => array('MessageComment.id' => $id)
            )
        );
        if (!$item_comment) {
            return $this->redirect(array('action' => 'index'));
        }
        
        //Set deleted field to 1 for comment
        $this->request->data['MessageComment']['id'] = $id;
        $this->request->data['MessageComment']['deleted'] = 1;
        if ($this->MessageComment->save($this->request->data)) {
            $this->Activity->log($this->MessageComment->id, 'MessageComment', 'delete');
            
            $this->Session->setFlash(__('Reply successfully deleted'), 
                'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'view', $item_comment['MessageComment']['message_id']));
        }
        $this->Session->setFlash(__('An error has occurred'), 
            'default', array('class' => 'alert alert-danger'));
        return $this->redirect(array('action' => 'index'));
    }
}
