<?php

  /**
   * Invoice based on quote helper implementation
   * 
   * @package activeCollab.modules.tracking
   * @subpackage models
   */
  class IInvoiceBasedOnQuoteImplementation extends IInvoiceBasedOnImplementation {
    
    /**
     * Create new invoice instance based on parent object
     * 
     * @param mixed $settings
     * @param IUser $user
     * @return Invoice
     */
    function create($settings = null, IUser $user = null) {
      $invoice = new Invoice();

      $invoice->setBasedOn($this->object);
      $invoice->setDueOn(new DateValue());
      $invoice->setStatus(INVOICE_STATUS_DRAFT);
      
      
      $items = array();
      $total_time = 0;
      
      if(is_foreachable($this->object->getItems())) {
        foreach($this->object->getItems() as $item) {
          $items[] = array(
            'description' => $item->getDescription(),
            'unit_cost'   => $item->getUnitCost(),
            'quantity'    => $item->getQuantity(),
            'tax_rate_id' => $item->getTaxRateId(),
            'total'       => $item->getTotal(),
            'subtotal'    => $item->getSubtotal()
          );
        } // foreach
      } // if
      
      $invoice->setCompanyId(array_var($settings, 'company_id'));
      $invoice->setCompanyAddress(array_var($settings, 'company_address'));
      
      $invoice->setCurrencyId($this->object->getCurrency()->getId());
      $invoice->setLanguageId($this->object->getLanguageId());
      $invoice->setNote(array_var($settings, 'note', ''));
      $invoice->setComment(array_var($settings, 'comment', ''));
      $invoice->setAllowPayments(array_var($settings, 'allow_payments', -1));
      
      if (!$this->object->isWon()) {
        DB::beginWork('Marking quote as won @ ' . __CLASS__);

        $this->object->markAsWon($user);
      
        $subscribers = $this->object->subscriptions()->get();
        if(is_foreachable($subscribers)) {
          // exclude a user who have won the quote
          foreach($subscribers as $k => $subscriber) {
            if($subscriber->getId() == $user->getId()) {
              unset($subscribers[$k]);
            } // if
          } // foreach
        } // if
      
        DB::commit('Quote marked as won @ ' . __CLASS__);
      } // if
      
      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
    
  }