<?php

  /**
   * Invoice based on task helper implementation
   * 
   * @package activeCollab.modules.tracking
   * @subpackage models
   */
  class IInvoiceBasedOnMilestoneImplementation extends IInvoiceBasedOnImplementation {
    
    /**
     * Create new invoice instance based on parent object
     * 
     * @param mixed $settings
     * @return Invoice
     */
    function create($settings = null, IUser $user = null) {
      $timerecords = TimeRecords::findByMilestone($user, $this->object, BILLABLE_STATUS_BILLABLE);
      $expenses = Expenses::findByMilestone($user, $this->object, BILLABLE_STATUS_BILLABLE);
      
      if ($timerecords || $expenses) {
        $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());
        
        $items = array();
        $total_time = 0;
      
        $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 Milestone doesn't have billable time records nor expenses.");
      }//if
     
    } // create
    
  }//IInvoiceBasedOnProjectImplementation