<?php

  // Build on top of framework controller
  AngieApplication::useController('fw_object_contexts_admin', ENVIRONMENT_FRAMEWORK);

  /**
   * Object contexts controller
   * 
   * @package activeCollab.modules.discussions
   * @subpackage controllers
   */
  class ObjectContextsAdminController extends FwObjectContextsAdminController {
    
    /**
     * Rebuild task entries
     */
    function rebuild_invoicing() {
      if($this->request->isAsyncCall() && $this->request->isSubmitted()) {
        try {
          DB::beginWork('Updating invoicing contexts @ ' . __CLASS__);
          
          $invoices = DB::execute('SELECT id FROM ' . TABLE_PREFIX . 'invoices');
          $quotes = DB::execute('SELECT id FROM ' . TABLE_PREFIX . 'quotes');
          
          if($invoices || $quotes) {
            $batch = DB::batchInsert(TABLE_PREFIX . 'object_contexts', array('parent_type', 'parent_id', 'context'));
            
            if($invoices) {
              foreach($invoices as $invoice) {
                $batch->insert('Invoice', $invoice['id'], "invoices:invoices/$invoice[id]");
              } // foreach
            } // if
            
            if($quotes) {
              foreach($quotes as $quote) {
                $batch->insert('Quote', $quote['id'], "quotes:quotes/$quote[id]");
              } // foreach
            } // if
            
            $batch->done();
          } // if
          
          DB::commit('Invoicing contexts updated @ ' . __CLASS__);
          
          $this->response->ok();
        } catch(Exception $e) {
          DB::rollback('Failed to update invoicing contexts @ ' . __CLASS__);
          $this->response->exception($e);
        } // try
      } else {
        $this->response->badRequest();
      } // if
    } // rebuild_invoicing
    
  }