<?php

  // Build on top of framework controller
  AngieApplication::useController('fw_backend', ENVIRONMENT_FRAMEWORK);
  
  /**
   * Default controller for things that are behind login screen
   * 
   * @package activeCollab.modules.system
   * @subpackage controllers
   */
  class BackendController extends FwBackendController {
    
    /**
     * Active home screen
     *
     * @var Homescreen
     */
    protected $active_homescreen;
    
    /**
     * Active home screen tab
     *
     * @var HomescreenTab
     */
    protected $active_homescreen_tab;
    
    /**
     * Execute before any other action
     */
    function __before() {
      parent::__before();
      
      $this->wireframe->setCurrentMenuItem('homepage');
    } // __before
  
    /**
     * Show dashboard overview
     */
    function index() {
      if($this->request->isApiCall()) {
        $this->response->notFound(); // Don't show anything
      } // if

      // Phone homescreen
      if($this->request->isPhone()) {
        $homescreen_items = new NamedList(array(
          'people' => array(
            'text' => lang('People'),
        		'url' => Router::assemble('people'),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/people.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ), 
          'projects' => array(
            'text' => lang('Projects'),
        		'url' => Router::assemble('projects'),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/projects.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ), 
          'assignments' => array(
            'text' => lang('Assignments'),
        		'url' => Router::assemble('my_tasks'),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/assignments.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ), 
          'favorites' => array(
            'text' => lang('Favorites'),
        		'url' => $this->logged_user->getFavoritesUrl(),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/favorites.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ),
          'activities' => array(
            'text' => lang('Activities'),
        		'url' => Router::assemble('backend_activity_log'),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/recently.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ),
          'profile' => array(
            'text' => lang('Profile'),
        		'url' => $this->logged_user->getViewUrl(),
        		'icon' => AngieApplication::getImageUrl('icons/homescreen/profile.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
          ),
        ));
        
        EventsManager::trigger('on_phone_homescreen', array(&$homescreen_items, &$this->logged_user));
        
        $this->response->assign('homescreen_items', $homescreen_items);
        
        if(AngieApplication::isModuleLoaded('tracking')) {
        	$projects = Projects::findForQuickTracking($this->logged_user);
	        
	        if(is_foreachable($projects)) {
	        	$this->wireframe->actions->add('log_time', lang('Log Time'), '#', array(
		          'icon' => AngieApplication::getImageUrl('icons/navbar/add-time.png', TRACKING_MODULE, AngieApplication::INTERFACE_PHONE)
		        ));
		        
		        $this->wireframe->actions->add('log_expenses', lang('Log Expense'), '#', array(
		          'icon' => AngieApplication::getImageUrl('icons/navbar/add-expense.png', TRACKING_MODULE, AngieApplication::INTERFACE_PHONE)
		        ));
	        } // if
	        
	        $this->response->assign('quick_tracking_data', array(
	        	'projects' => $projects,
	    			'time_records_add_url' => Router::assemble('project_tracking_time_records_add', array('project_slug' => '--PROJECT-SLUG--')),
	    			'expenses_add_url' => Router::assemble('project_tracking_expenses_add', array('project_slug' => '--PROJECT-SLUG--'))
	        ));
        } // if
        
        $this->wireframe->actions->add('quick_add', lang('Quick Add'), Router::assemble('quick_add'), array(
          'icon' => AngieApplication::getImageUrl('icons/navbar/add.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
        ));
        
        if(AngieApplication::isModuleLoaded('status') && ($this->logged_user->isAdministrator() || $this->logged_user->getSystemPermission('can_use_status_updates'))) {
        	$this->wireframe->actions->add('update_status', lang('Update Status'), Router::assemble('status_updates_add'), array(
	          'icon' => AngieApplication::getImageUrl('icons/navbar/comments.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE)
	        ));
        } // if
        
        $this->wireframe->actions->add('logout', lang('Logout'), Router::assemble('logout'), array(
    			'icon' => AngieApplication::getImageUrl('layout/buttons/logout.png', SYSTEM_MODULE, AngieApplication::INTERFACE_PHONE),
          'primary' => true
        ));
        
        $this->response->assign('logout_url', Router::assemble('logout'));
        
      // Tablet homescreen
      } elseif($this->request->isTablet()) {
        throw new NotImplementedError(__METHOD__);
        
      // Regular web interface
      } else {
        $this->wireframe->tabs->clear();
        
        // Rebuild indexes
        if($this->logged_user->isAdministrator() && ConfigOptions::getValue('require_index_rebuild', false)) {
          $this->wireframe->tabs->add('require_index_rebuild', lang('Rebuild Indexes'), Router::assemble('homepage'), null, true);
          
          $this->setView(array(
            'module' => ENVIRONMENT_FRAMEWORK, 
            'controller' => null, 
            'view' => '_require_index_rebuild', 
          ));
          
        // Dashboard
        } else {
          $active_homescreen = $this->logged_user->homescreen()->get();
        
          if($active_homescreen instanceof Homescreen) {
            foreach($active_homescreen->getTabs() as $homescreen_tab) {
              $this->wireframe->tabs->add('homescreen_tab_' . $homescreen_tab->getId(), $homescreen_tab->getName(), $homescreen_tab->getHomescreenTabUrl());
            } // foreach
            
            $this->response->assign('active_homescreen', $active_homescreen);
            
            if($this->logged_user->homescreen()->canHaveOwn()) {
              $this->wireframe->tabs->addIcon('configure_homescreen', lang('Configure Home Screen'), $this->logged_user->homescreen()->getManageUrl(), AngieApplication::getImageUrl('icons/12x12/configure.png', HOMESCREENS_FRAMEWORK, AngieApplication::INTERFACE_DEFAULT));
            } // if
          } else {
            $this->response->notFound();
          } // if
          
          $homescreen_tab_id = $this->request->getId('homescreen_tab_id');
          $active_homescreen_tab = $homescreen_tab_id ? HomescreenTabs::findById($homescreen_tab_id) : null;
          
          if($active_homescreen_tab instanceof HomescreenTab) {
            if($active_homescreen_tab->getHomescreenId() != $active_homescreen->getId()) {
              $this->response->badRequest();
            } // if
          } else {
            $active_homescreen_tab = first($active_homescreen->getTabs());
          } // if
            
          if($active_homescreen_tab instanceof HomescreenTab) {
            $this->wireframe->tabs->setCurrentTab('homescreen_tab_' . $active_homescreen_tab->getId());
            
            $this->response->assign('active_homescreen_tab', $active_homescreen_tab);
          } else {
            $this->response->notFound();
          } // if
        } // if
      } // if
    } // index
    
    /**
     * Show recent activities page (mobile devices only)
     */
    function my_tasks() {
      if($this->request->isMobileDevice()) {
      	try {
      		$this->wireframe->breadcrumbs->add('my_tasks', lang('Assignments'), Router::assemble('my_tasks'));
	      	
	      	$filter = new AssignmentFilter();
	        $filter->setAttributes(array(
	        	'user_filter' => 'logged_user',
	        	'completed_on_filter' => 'is_not_set',
	        	'project_filter' => 'active',
	        	'group_by' => 'project'
	        ));
	        
	        $assignments = $filter->run($this->logged_user);
	        
	      	$this->response->assign(array(
	      		'assignments' => $assignments,
	      		'project_slugs' => Projects::getIdSlugMap(),
	      		'urls' => array(
	      			'task_url' => AngieApplication::isModuleLoaded('tasks') ? Router::assemble('project_task', array('project_slug' => '--PROJECT-SLUG--', 'task_id' => '--TASK-ID--')) : '',
	    				'todo_url' => AngieApplication::isModuleLoaded('todo') ? Router::assemble('project_todo_list', array('project_slug' => '--PROJECT-SLUG--', 'todo_list_id' => '--TODO-LIST-ID--')) : '', 
	      		)
	      	));
      	} catch(AssignmentFilterConditionsError $e) {
      		$this->response->assign('assignments', null);
      	} catch(Exception $e) {
      		$this->response->exception($e);
      	} // try
      } else {
        $this->response->badRequest();
      } // if
    } // my_tasks
    
    /**
     * Render global iCalendar feed
     */
    function ical() {
      if ($this->logged_user->isFeedUser()) {
        $filter = $this->logged_user->projects()->getVisibleTypesFilter(Project::STATUS_ACTIVE, get_completable_project_object_types());
        if($filter) {
          $objects = ProjectObjects::find(array(
            'conditions' => array($filter . ' AND completed_on IS NULL AND state >= ? AND visibility >= ?', STATE_VISIBLE, $this->logged_user->getMinVisibility()),
            'order' => 'priority DESC',
          ));
          render_icalendar(lang('Global Calendar'), $objects, true);
          die();
        } else {
          $this->response->notFound();
        } // if
      } else {
        $this->response->forbidden();
      } //if
    } // ical
    
    /**
     * Show iCalendar subscribe page
     */
    function ical_subscribe() {
      if ($this->logged_user->isFeedUser()) {
        $this->wireframe->hidePrintButton();
        $feed_token  = $this->logged_user->getFeedToken();

        $ical_url = Router::assemble('ical',array('auth_api_token' => $feed_token));
        $ical_subscribe_url = str_replace(array('http://', 'https://'), array('webcal://', 'webcal://'), $ical_url);

        $this->response->assign(array(
          'ical_url' => $ical_url,
          'ical_subscribe_url' => $ical_subscribe_url
        ));
      } else {
        $this->response->forbidden();
      } // if
    } // ical_subscribe
    
    /**
     * Quick jump action
     */
    function quick_jump() {
    	if ($this->request->isAsyncCall()) {
    		
    		$cache_id = 'quick_jump_for_' . $this->logged_user->getId();
    		$items = cache_get($cache_id);
    		
    		if ($items == null) {
	    	  $projects = Projects::findForQuickJump($this->logged_user);
	    	
	      	$tabs = array();
	      	$items = array();
	      	
	      	if (is_foreachable($projects)) {    	
	  	    	foreach ($projects as $project) {
	  	    		$tabs = $project->getTabs($this->logged_user);
	  	    		    		
	  	    		if (is_foreachable($tabs)) {
	  		    		$items[$project->getId()] = array(
	  		    			'text' => $project->getName(),
	  		    			'url' => $project->getViewUrl(),
	  		    			'icon' => $project->avatar()->getUrl(IProjectAvatarImplementation::SIZE_SMALL),
	  		    			'subitems' => $tabs->toArray()
	  		    		);
	  	    		} // if
	  	    	} // foreach
	      	} // if
	      	
	      	cache_set($cache_id, $items);
    		} // if
      	
      	$this->response->respondWithMap($items);
    	} else {
    		$this->response->badRequest();
    	} // if
    } // quick_jump
    
    /**
     * Quick add action
     */
    function quick_add() {
    	if($this->request->isAsyncCall() || $this->request->isMobileDevice()) {
    	  $interface = AngieApplication::getPreferedInterface();
    	  if(empty($interface)) {
    	    $interface = AngieApplication::INTERFACE_DEFAULT;
    	  } // if
    	  
    	  $cache_id = $this->logged_user->getQuickAddCacheId($interface);
    	  
    		$return = cache_get($cache_id);
    		if($return == null) {
	    	  $return = array(
	      		'items' => new NamedList(),
	      		'subitems' => new NamedList(),
	      		'map' => array()
	      	);
	      	
	      	// create projects subitems
	      	$projects = Projects::findForQuickJump($this->logged_user);
	      	if(is_foreachable($projects)) {
	      		foreach($projects as $project) {
	      			$return['subitems']->add('project_' . $project->getId(), array (
	  		  			'text' => $project->getName(),
	  		  			'icon' => $project->avatar()->getUrl(IProjectAvatarImplementation::SIZE_SMALL),
	  						'url_replacements' => array('--PROJECT-SLUG--' => $project->getSlug()),
	  						// For mobile devices
	  						'slug' => $project->getSlug(),
	  						'icon_big' => $project->avatar()->getUrl(IProjectAvatarImplementation::SIZE_BIG)
	      			));
	      		} // foreach
	      	} // if
	      	
	      	// create companies subitems
	  	  	$companies = Companies::findForQuickAdd($this->logged_user);
	  			if(is_foreachable($companies)) {
	  				foreach($companies as $company) {
	  	    		$return['subitems']->add('company_' . $company->getId(), array (
	  			  		'text' => $company->getName(),
	  			  		'icon' => $company->avatar()->getUrl(ICompanyAvatarImplementation::SIZE_SMALL),
	  						'url_replacements' => array('--COMPANY-ID--' => $company->getId()),
	  						// For mobile devices
	  						'icon_medium' => $company->avatar()->getUrl(ICompanyAvatarImplementation::SIZE_MEDIUM)
	  	    		));
	  				} // foreach
	  			} // if
	      	
	      	EventsManager::trigger('on_quick_add', array($return['items'], $return['subitems'], &$return['map'], $this->logged_user, $projects, $companies, $interface));
	      	
	      	cache_set($cache_id, $return);
    		} // if
      	
      	// Respond to regular web browser
      	if($this->request->isWebBrowser()) {
      		$this->response->respondWithData($return);
      		
      	// Respond to phone device
      	} elseif($this->request->isPhone()) {
      		$this->wireframe->breadcrumbs->add('quick_add', lang('Quick Add'), Router::assemble('quick_add'));
      		
      		$projects = array();
      		$companies = array();
      		
      		if(is_foreachable($return['subitems'])) {
      			foreach($return['subitems'] as $key => $subitem) {
      				if(substr($key, 0, 7) == 'project') {
      					$projects[$key] = $subitem;
      				} else {
      					$companies[$key] = $subitem;
      				} // if
      			} // foreach
      		} // if
      		
      		$this->response->assign('quick_add_data', array(
      			'items' => $return['items'],
      			'map' => $return['map'],
	        	'projects' => $projects,
	        	'companies' => $companies
	        ));
      	} // if
    	} else {
    		$this->response->badRequest();
    	} // if
    } // quick_add
    
  }