<?php

  // Extends profile controller
  AngieApplication::useController('users', SYSTEM_MODULE);
  
  /**
   * User calendar controller
   *
   * @package activeCollab.modules.calendar
   * @subpackage controllers
   */
  class ProfileCalendarController extends UsersController {
    
    /**
     * Active module
     *
     * @var string
     */
    protected $active_module = CALENDAR_MODULE;
  
    /**
     * Prepare controller
     */
    function __before() {
      parent::__before();
      
      if(!can_access_profile_calendar($this->logged_user, $this->active_user)) {
        $this->response->forbidden();
      } // if
      
      if($this->active_user->isNew()) {
        $this->response->notFound();
      } // if
      
      $this->wireframe->breadcrumbs->add('profile_calendar', lang('Calendar'), Calendar::getProfileCalendarUrl($this->active_user));
    } // __construct
    
    /**
     * Index
     */
    function index() {
      require_once CALENDAR_MODULE_PATH . '/models/generators/ProfileCalendarGenerator.class.php';

      if (($this->logged_user->isProjectManager() || ($this->logged_user->getId() == $this->active_user->getId())) && $this->logged_user->isFeedUser()) {
      	$this->wireframe->actions->add('iCalfeed', lang('iCalendar Feed'), Router::assemble('profile_calendar_ical_subscribe', array(
      		'company_id' => $this->active_user->getCompanyId(),
      		'user_id'		 => $this->active_user->getId(),
      	)),
      	array (
      		'onclick' => new FlyoutCallback()
      	));
      } // if

      if($this->request->get('month') && $this->request->get('year')) {
      	$date = DateTimeValue::make(0, 0, 0, $this->request->get('month'), 1, $this->request->get('year'));
      } else {
        $date = new DateTimeValue(time() + get_user_gmt_offset());
      } // if
      
      $first_weekday = ConfigOptions::getValueFor('time_first_week_day', $this->logged_user);
      $work_days = ConfigOptions::getValueFor('time_workdays', $this->logged_user);

      $generator = new ProfileCalendarGenerator($date->getMonth(), $date->getYear(), $first_weekday, $work_days);
			$generator->setUser($this->active_user);
			$generator->setData(Calendar::getUserData($this->active_user, $date->getMonth(), $date->getYear(), true));

      $this->smarty->assign(array(
      	'date'		 => $date,
        'calendar' => $generator,
      ));
    } // index
    
    /**
     * Show events for a given day
     */
    function day() {
      if($this->request->get('year') && $this->request->get('month') && $this->request->get('day')) {
        $day = new DateValue($this->request->get('year') . '-' . $this->request->get('month') . '-' . $this->request->get('day'));
      } else {
        $day = DateValue::now();
      } // if
      
      $this->wireframe->breadcrumbs->add('profile_calendar_day', $day->getYear() . ' / ' . $day->getMonth(), Calendar::getProfileMonthUrl($this->active_user, $day->getYear(), $day->getMonth()));
      $objects = ProjectObjects::groupByProject(Calendar::getUserDayData($this->active_user, $day));
            
      $this->smarty->assign(array(
        'day' => $day,
        'groupped_objects' => $objects,
      ));
    } // day
    
    /**
     * Render iCalendar feed
     */
    function ical() {
      if (($this->logged_user->isProjectManager() || ($this->logged_user->getId() == $this->active_user->getId())) && $this->logged_user->isFeedUser()) {
        $objects_table = TABLE_PREFIX . 'project_objects';
        $assignments_table = TABLE_PREFIX . 'assignments';
        $tables = "$objects_table LEFT JOIN $assignments_table ON ($objects_table.id = $assignments_table.parent_id)";
        $conditions = DB::prepare("(($assignments_table.user_id = ?) OR ($objects_table.assignee_id = ?))", array($this->active_user->getId(), $this->active_user->getId()));

        $objects = ProjectObjects::findBySQL("SELECT DISTINCT $objects_table.* FROM $tables WHERE $conditions ORDER BY type, due_on");
        render_icalendar(
          lang(":user's calendar", array('user' => $this->active_user->getDisplayName())),
          $objects
        );
        die();
      } else {
        $this->response->forbidden();
      }
    } // ical
    
    /**
     * Show iCalendar subscribe page
     */
    function ical_subscribe() {
      if (($this->logged_user->isProjectManager() || ($this->logged_user->getId() == $this->active_user->getId())) && $this->logged_user->isFeedUser()) {
        $this->wireframe->hidePrintButton();
        $feed_token = $this->logged_user->getFeedToken();

        $ical_url = Router::assemble('profile_calendar_ical', array(
          'company_id' => $this->active_user->getCompanyId(),
          'user_id' => $this->active_user->getId(),
          'auth_api_token' => $feed_token
        ));

        $ical_subscribe_url = str_replace(array('http://', 'https://'), array('webcal://', 'webcal://'), $ical_url);

        $this->smarty->assign(array(
          'ical_url' => $ical_url,
          'ical_subscribe_url' => $ical_subscribe_url
        ));
      } else {
        $this->response->forbidden();
      }
    } // ical_subscribe
    
  }