<?php

  /**
   * InvoiceItems class
   *
   * @package activeCollab.modules.invoicing
   * @subpackage models
   */
  class InvoiceItems extends BaseInvoiceItems {

    /**
     * Return items by invoice
     *
     * @param Invoice $invoice
     * @return array
     */
    function findByInvoice($invoice) {
      return InvoiceItems::find(array(
        'conditions' => array('invoice_id = ?', $invoice->getId()),
        'order' => 'position'
      ));
    } // findByInvoice
    
    /**
     * Return number of items that user $rate tax rate
     *
     * @param TaxRate $tax_rate
     * @return integer
     */
    function countByTaxRate($tax_rate) {
      return InvoiceItems::count(array('tax_rate_id = ?', $tax_rate->getId()));
    } // countByTaxRate

    /**
     * Delete all items for a invoice
     *
     * @param Invoice $invoice
     * @return null
     */
    function deleteByInvoice($invoice) {
      DB::beginWork();
      
      $execute = DB::execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_related_records WHERE invoice_id = ?', $invoice->getId());
      if ($execute && !is_error($execute)) {
        $delete = InvoiceItems::delete(array('invoice_id = ?', $invoice->getId()));
        if ($delete && !is_error($delete)) {
          DB::commit();
        } else {
          DB::rollback();
        } // if
        return $delete;
      } else {
        DB::rollback();
        return $execute;
      } // if
    } // deleteByInvoice
    
    /**
     * Delete all items for by an invoice and ids
     *
     * @param Invoice $invoice
     * @param $ids
     * 
     * @return null
     */
    function deleteByInvoiceAndIds($invoice, $ids) {
      
      if(is_foreachable($ids)) {
        $records = DB::execute('SELECT parent_id, parent_type FROM ' . TABLE_PREFIX . 'invoice_related_records WHERE invoice_id = ? AND item_id IN (?)', $invoice->getId(), $ids);
        if(is_foreachable($records)) {
          foreach($records as $record) {
            $obj_id = $record['parent_id'];
            $obj = new $record['parent_type']($obj_id);
            $obj->setBillableStatus(BILLABLE_STATUS_BILLABLE);
            $obj->save();
          }//foreach
        }//if
        
        $execute = DB::execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_related_records WHERE invoice_id = ? AND item_id IN (?)', $invoice->getId(), $ids);
        $delete = InvoiceItems::delete(array('invoice_id = ? AND id IN (?)', $invoice->getId(), $ids));
        return $delete;
        
      }//if

      return true;
    } // deleteByInvoiceAndIds

  } // class
