<?php

  /**
   * Create invoices from recurring profiles
   * 
   * @package current.modules.invoicing
   * @subpackage models
   */
  class RecurringInvoice {
  
    /**
     * Go throught all profiles for today and create invoices
     */
    static function createFromRecurringProfile() {
      $recurring_profiles = RecurringProfiles::findMatchingForDay();
    
      //create invoice
      if(is_foreachable($recurring_profiles)) {
        foreach ($recurring_profiles as $key => $recurring_profile) {
          //create invoice
          self::createInvoice($recurring_profile);
        }//foreach
      }//if
    }//createFromRecurringProfile
    
    /**
     * Create invoice from recurring profile
     * 
     * @param RecurringProfile $recurring_profile
     * @param boolean $set_next_trigger_on
     * @return RecurringProfile
     */
    static function createInvoice(RecurringProfile $recurring_profile) {
      $new_invoice = new Invoice();
      $invoice_data = array(
        'based_on_type'  => get_class($recurring_profile),
        'based_on_id'	=> $recurring_profile->getId(),      
        'company_id' => $recurring_profile->getCompanyId(),
        'project_id' => $recurring_profile->getProjectId(),
        'note' => $recurring_profile->getNote(),
        'language_id'	=> $recurring_profile->getLanguageId(),
        'currency_id'	=> $recurring_profile->getCurrencyId(),
        'company_address' => $recurring_profile->getCompanyAddress(),
        'comment' => $recurring_profile->getOurComment(),
        'created_on' => $recurring_profile->getNextTriggerOn(),
        'allow_payments' => $recurring_profile->getAllowPayments(),
      	
      );
      
      
      if(is_foreachable($recurring_profile->getItems())) {
        $invoice_data['items'] = array();
        foreach($recurring_profile->getItems() as $item) {
          $invoice_data['items'][] = array(
            'description' => $item->getDescription(),
            'unit_cost' => $item->getUnitCost(),
            'quantity' => $item->getQuantity(),
            'tax_rate_id' => $item->getTaxRateId(),
            'position' => $item->getPosition(),
            'total' => $item->getTotal(),
            'subtotal' => $item->getSubtotal()
          );
        } // foreach
      }//if
      
      $new_invoice->setAttributes($invoice_data);
      
      if($recurring_profile->getAutoIssue()) {
        $new_invoice->setNumber($new_invoice->generateInvoiceId());
        Invoices::incrementDateInvoiceCounters();  
        $new_invoice->setStatus(INVOICE_STATUS_ISSUED, $recurring_profile->getCreatedBy());
        $new_invoice->setIssuedToId($recurring_profile->getRecipientId());
        
        if($recurring_profile->getInvoiceDueAfter() || $recurring_profile->getInvoiceDueAfter() === 0) {
          $add_days = '+' . $recurring_profile->getInvoiceDueAfter() . ' days';
          $new_invoice->setDueOn(new DateValue($add_days));
        } else {
          $new_invoice->setDueOn(new DateValue('+7 days'));
        }//if
        
      } else {
        $new_invoice->setStatus(INVOICE_STATUS_DRAFT, $recurring_profile->getCreatedBy());
      }//if
      
      $new_invoice->save();
      
      $new_invoice->addItems($invoice_data['items']);
      
      if($recurring_profile->getAutoIssue()) {
        $send_to = array();
        $recipient = $recurring_profile->getRecipient();
        if($recipient instanceof IUser) {
           $send_to[] = $recipient; // Notify recipient
        }//if
        
        if(is_foreachable($send_to)) {
          $filename_name = 'invoice_' . $new_invoice->getId() . '.pdf';
          $filename = WORK_PATH . '/' . $filename_name;
          
          InvoicePDFGenerator::save($new_invoice, $filename);
          
          ApplicationMailer::notifier()->notifyUsers($send_to, $new_invoice, 'invoicing/issued', null, array(
            'attachments' => array($filename), 
          ));
          
          //@unlink($filename);
        }//if
        
        // Send email notification to the financial managers
        ApplicationMailer::notifier()->notifyFinancialManagers($new_invoice, 'invoicing/invoice_generated_via_recurring_profile', array('recurring_profile' => $recurring_profile), array('method' => ApplicationMailer::SEND_INSTANTNLY));
      } else {
        ApplicationMailer::notifier()->notifyFinancialManagers($new_invoice, 'invoicing/draft_invoice_created_via_recurring_profile', array('profile' => $recurring_profile), array('method' => ApplicationMailer::SEND_INSTANTNLY));
      } // if
      
      //increase triggered number value, set next trigger date and arhive this profile if is finished
      $recurring_profile->increaseTriggeredNumber();
      $recurring_profile->setLastTriggeredOn(new DateValue());
     
      $recurring_profile->setNextTriggerOnDate($recurring_profile->getFrequency());
     
      
      if($recurring_profile->getTriggeredNumber() == $recurring_profile->getOccurrences()) {
        $recurring_profile->setState(STATE_ARCHIVED);
        
        // Notify financial managers that recurring profile is archived
        ApplicationMailer::notifier()->notifyFinancialManagers($recurring_profile, 'invoicing/recurring_profile_archived', null, array('method' => ApplicationMailer::SEND_INSTANTNLY));
      }//if
      
      return $recurring_profile->save();
    }//createInvoice
    
  }