<?php

  /**
   * Invoice based on tracking report helper implementation
   * 
   * @package activeCollab.modules.tracking
   * @subpackage models
   */
  class IInvoiceBasedOnTrackingReportImplementation extends IInvoiceBasedOnImplementation {
  
    /**
     * Create new invoice instance based on parent object
     * 
     * @param mixed $settings
     * @return Invoice
     */
    function create($settings = null, IUser $user = null) {
      
      //set dont group and sum by user to false
      $this->object->setGroupBy(TrackingReport::DONT_GROUP);
      $this->object->setSumByUser(false);
      
      $report_results = $this->object->run($user);
      if(is_foreachable($report_results)) {
        $invoice = new Invoice();
        
        //if 1 project selected in filter
        $project_ids = $this->object->getProjectIds();
        if($this->object->getProjectFilter() == TrackingReport::PROJECT_FILTER_SELECTED && count($project_ids) == 1) {
          $invoice->setProjectId($project_ids[0]);
        }//if
        
        $invoice->setBasedOnType(get_class($this->object));
        $invoice->setBasedOnId($this->object->getId());
        $invoice->setDueOn(new DateValue());
        $invoice->setStatus(INVOICE_STATUS_DRAFT);

        $timerecords = array();
        $expenses = array();
        
        foreach ($report_results[0]['records'] as $result) {
          
          if($result['billable_status'] == BILLABLE_STATUS_BILLABLE) {
            //use only billable

            $type = $result['type'];
            $item_obj = new $type($result['id']);
            
            //set unit cost depending job type
            if($item_obj instanceof TimeRecord) {
              $timerecords[] = $item_obj;
            } else {
              $expenses[] = $item_obj;
            }//if
          }//if
        }//foreach
        
        $items = $this->createItemsForInvoice($timerecords, $expenses, null, $settings, $user);
        
      }//if
      
      $invoice->setNote($settings['note']);
      $invoice->setComment($settings['comment']);
      $invoice->setCompanyId($settings['company_id']);
      $invoice->setCompanyAddress($settings['company_address']);
      
      if($settings['currency_id'] == 0) {
        $currency_id = Currencies::getDefaultId();
      } else {
        $currency_id = $settings['currency_id'];
      }//if
      $invoice->setCurrencyId($currency_id);
      
      //set payments options
      $invoice->setAllowPayments($settings['payments_type']);
      
      if(!is_foreachable($items)) {
        throw new Error('Invoice must have at least one item.');
      }//if
        
  	  //save invoice      
      $invoice->save();
      
      $this->addItemsToInvoice($items, $invoice);
   
      return $invoice;
      
    } // create
    
  }