<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category   Phoenix
 * @package    Phoenix_CashOnDelivery
 * @copyright  Copyright (c) 2010 Phoenix Medien GmbH & Co. KG (http://www.phoenix-medien.de)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

class Phoenix_CashOnDelivery_Model_Invoice_Total extends Mage_Sales_Model_Order_Invoice_Total_Abstract
{
    public function collect(Mage_Sales_Model_Order_Invoice $invoice)
    {
        $order = $invoice->getOrder();

        if ($order->getPayment()->getMethodInstance()->getCode() != 'cashondelivery') {
            return $this;
        }

        if (!$order->getCodFee()) {
            return $this;
        }

        foreach ($invoice->getOrder()->getInvoiceCollection() as $previusInvoice) {
            if ($previusInvoice->getCodAmount() && !$previusInvoice->isCanceled()) {
                $includeCodTax = false;
            }
        }

        $baseCodFee = $order->getBaseCodFee();
        $baseCodFeeInvoiced = $order->getBaseCodFeeInvoiced();
        $baseInvoiceTotal = $invoice->getBaseGrandTotal();
        $codFee = $order->getCodFee();
        $codFeeInvoiced = $order->getCodFeeInvoiced();
        $invoiceTotal = $invoice->getGrandTotal();

        if (!$baseCodFee || $baseCodFeeInvoiced==$baseCodFee) {
            return $this;
        }

        $baseCodFeeToInvoice = $baseCodFee - $baseCodFeeInvoiced;
        $codFeeToInvoice = $codFee - $codFeeInvoiced;

        $baseInvoiceTotal = $baseInvoiceTotal + $baseCodFeeToInvoice;
        $invoiceTotal = $invoiceTotal + $codFeeToInvoice;

        $invoice->setBaseGrandTotal($baseInvoiceTotal);
        $invoice->setGrandTotal($invoiceTotal);

        $invoice->setBaseCodFee($baseCodFeeToInvoice);
        $invoice->setCodFee($codFeeToInvoice);

        $order->setBaseCodFeeInvoiced($baseCodFeeInvoiced+$baseCodFeeToInvoice);
        $order->setCodFeeInvoiced($codFeeInvoiced+$codFeeToInvoice);

        return $this;
    }
}