<?php

  /**
   * RecurringProfiles class
   *
   * @package activeCollab.modules.invoicing
   * @subpackage models
   */
  class RecurringProfiles extends BaseRecurringProfiles {
    
    /**
     * Returns true if $user can create new recurring profiles
     * 
     * @param IUser $user
     * @return boolean
     */
    static function canAdd(IUser $user) {
      return Invoices::canAdd($user);
    } // canAdd
    
    /**
     * Returns true if $user can manage recurring invoices
     * 
     * @param IUser $user
     * @return boolean
     */
    static function canManage(IUser $user) {
      return Invoices::canAdd($user);
    } // canManage
  
    // ---------------------------------------------------
    //  Finders
    // ---------------------------------------------------
    /**
     * Find skipped recurring profiles 
     * 
     * @return DBResult
     */
    static function findSkipped() {
      $today = new DateValue();
      return self::find(array(
        'conditions' => array("next_trigger_on < ? AND state = ?", $today, STATE_VISIBLE)
      ));
    } //findSkipped
    
    
    
    /**
     * Find recurring profiles to use for creating invoices
     * 
     * @return DBResult
     */
    static function findMatchingForDay() {
      $today = new DateValue();
      return self::find(array(
        'conditions' => array("(start_on = ? OR next_trigger_on = ?) AND state = ? AND (last_triggered_on != ? OR last_triggered_on IS NULL)", $today, $today, STATE_VISIBLE, $today)
      ));
    } //findMetchingForDay
    
    /**
     * Find profiles by ids
     * 
     * @param array $ids
     * @param integer $min_state
     * @param integer $min_visibility
     * @return mixed
     */
    static function findByIds($ids, $min_state = STATE_VISIBLE, $min_visibility = VISIBILITY_NORMAL) {
      return Recurringprofiles::find(array(
        'conditions' => array('id IN (?) AND state >= ? AND visibility >= ?', $ids, $min_state, $min_visibility) 
      ));
    } // findByIds
    
    /**
     * Find recurring profiles for objects list
     * 
     * @param integer $min_state
     * @param integer $min_visibility
     * @return array
     */
    static function findForObjectsList($min_state = STATE_VISIBLE) {
    	$recurring_profile_url = Router::assemble('recurring_profile', array('recurring_profile_id' => '--RECURRINGPROFILEID--'));
      $profiles = DB::execute('SELECT id, company_id, name, state, next_trigger_on FROM ' . TABLE_PREFIX . 'recurring_profiles WHERE state >= ?', $min_state);

      $result = array();
      if (is_foreachable($profiles)) {
        foreach ($profiles as $profile) {
          $result[] = array(
            'id'				=> $profile['id'],
            'name'			=> $profile['name'],
            'client_id'	=> $profile['company_id'],
            'permalink' => str_replace('--RECURRINGPROFILEID--', $profile['id'], $recurring_profile_url),
            'is_archived' => $profile['state'] == STATE_ARCHIVED ? '1' : '0',
            'is_skipped' => (strtotime(new DateValue()) > strtotime(new DateValue($profile['next_trigger_on'])) && $profile['state'] == STATE_VISIBLE) ? true : false
          );
        } // foreach
      } // if

      return $result;
    } // findForObjectsList
    
    /**
     * Find recurring profiles for phone list view
     * 
     * @param integer $min_state
     * @return array
     */
    function findForPhoneList($min_state = STATE_VISIBLE) {
      $recurring_profiles_table = TABLE_PREFIX . 'recurring_profiles';
      $companies_table = TABLE_PREFIX . 'companies';
      $recurring_profiles = DB::execute("SELECT $recurring_profiles_table.id, $companies_table.name AS company_name, $recurring_profiles_table.name FROM $recurring_profiles_table, $companies_table WHERE $recurring_profiles_table.company_id = $companies_table.id AND $recurring_profiles_table.state >= $min_state ORDER BY company_name, $recurring_profiles_table.id");
      
			$view_recurring_profile_url_template = Router::assemble('recurring_profile', array('recurring_profile_id' => '--RECURRINGPROFILEID--'));
      
			$result = array(); 
			
      if(is_foreachable($recurring_profiles)) {
      	foreach ($recurring_profiles as $recurring_profile) {
					$result[$recurring_profile['company_name']][] = array(
						'name' => $recurring_profile['name'],
						'permalink' => str_replace('--RECURRINGPROFILEID--', $recurring_profile['id'], $view_recurring_profile_url_template)
					);
      	} // foreach
      } // if
    	
      return $result;
    } // findForPhoneList
    
    /**
     * Find recurring profiles for printing by grouping and filtering criteria
     * 
     * @param string $group_by
     * @return DBResult
     */
    public function findForPrint($group_by = null) { 	
      
      if (!in_array($group_by, array('client_id', 'status'))) {
      	$group_by = null;
      } elseif ($group_by == 'client_id') {
        $group_by = 'company_id';
      }//if
      
      // do find tasks
      $profiles = self::find(array(
      	'order' => $group_by ? $group_by : 'id DESC' 
      ));
    	
    	return $profiles;
    } // findForPrint
    
  }