<?php

  /**
   * Invoice based on project helper implementation
   * 
   * @package activeCollab.modules.tracking
   * @subpackage models
   */
  class IInvoiceBasedOnProjectImplementation extends IInvoiceBasedOnImplementation {
    
    /**
     * Create new invoice instance based on parent object
     * 
     * @param mixed $settings
     * @return Invoice
     */
    function create($settings = null, IUser $user = null) {
      
      $object = new TrackingReport();
      $object->filterByProjects(array($this->object->getId()));
      $object->setGroupBy(TrackingReport::DONT_GROUP);
      $object->setSumByUser(false);
      
      $report_results = $object->run($user);
      if(is_foreachable($report_results)) {
        $invoice = new Invoice();
        
        $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
      
        $invoice->setComment($settings['comment']);
        $invoice->setNote($settings['note']);
        $invoice->setProjectId($this->object->getId());
        $invoice->setCompanyId($settings['company_id']);
        $invoice->setCompanyAddress($settings['company_address']);
        $invoice->setCurrencyId($this->object->getCurrency()->getId());
          
        //set payments options
        $invoice->setAllowPayments($settings['payments_type']);
          
        $items = $this->createItemsForInvoice($timerecords, $expenses, $this->object, $settings, $user);
          
        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;
      
      } else {
        throw new Error('This Project doesn\'t have billable time records nor expenses.');
      } // if
    } // create
     
  }