<?php

  /**
   * Invoice based on task helper implementation
   * 
   * @package activeCollab.modules.tracking
   * @subpackage models
   */
  class IInvoiceBasedOnTaskImplementation extends IInvoiceBasedOnImplementation {
    
    /**
     * Create new invoice instance based on parent object
     * 
     * @param mixed $settings
     * @return Invoice
     */
    function create($settings = null, IUser $user = null) {
      if ($this->object->tracking()->hasBillable($user, true)) {
        $invoice = new Invoice();
        
        $invoice->setBasedOnType(get_class($this->object));
        $invoice->setBasedOnId($this->object->getId());
        $invoice->setDueOn(new DateValue());
        $invoice->setStatus(INVOICE_STATUS_DRAFT);
        $invoice->setProjectId($this->object->getProject()->getId());
              
        $timerecords = $this->object->tracking()->getTimeRecords($user, BILLABLE_STATUS_BILLABLE);
        if($timerecords instanceof MySQLDBResult) {
          $timerecords = $timerecords->toArray();
        } else {
          $timerecords = array();
        }//if
        
        $expenses = $this->object->tracking()->getExpenses($user, BILLABLE_STATUS_BILLABLE);
        if($expenses instanceof MySQLDBResult) {
          $expenses = $expenses->toArray();
        } else {
          $expenses = array();
        }//if
       
        $invoice->setComment($settings['comment']);
        $invoice->setNote($settings['note']);
        $invoice->setCompanyId($settings['company_id']);
        $invoice->setCompanyAddress($settings['company_address']);
        $invoice->setCurrencyId($this->object->getProject()->getCurrency()->getId());
        
        //set payments options
        $invoice->setAllowPayments($settings['payments_type']);
        
        $items = $this->createItemsForInvoice($timerecords, $expenses, $this->object->getProject(), $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 Task doesn't have billable time records nor expenses.");
      }
    } // create
    
  }//IInvoiceBasedOnProjectImplementation