<?php

/**
 * kataoSupplierInvoice actions.
 *
 * @package www.katao.fr
 * @subpackage kataoSupplierInvoice
 * @author Your name here
 * @version SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class kataoSupplierInvoiceActions extends wpActions {
    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoSupplierInvoicePeer::KATAO_PERIOD_ID, KataoPeriodPeer::ID);

        $sort_method = $this->getCriteriaSortMethod();
        switch ($this->sort = $this->getRequestParameter('sort', 'date')) {
            case 'reference':
                $criteria->$sort_method(KataoSupplierInvoicePeer::REFERENCE);
                break;
            case 'status':
                $criteria->$sort_method(KataoSupplierInvoicePeer::STATUS);
                break;
            case 'supplier':
                $criteria->$sort_method(KataoSupplierInvoicePeer::SUPPLIER_NAME);
                break;
            case 'total':
                $criteria->$sort_method(KataoSupplierInvoicePeer::TOTAL_TVA);
                break;
            case 'period':
                $criteria->$sort_method(KataoPeriodPeer::NAME);
                break;
            default:
                $criteria->$sort_method(KataoSupplierInvoicePeer::INVOICE_DATE);
        }

        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_supplier_invoice_filter_status')) {
            $criteria->add(KataoSupplierInvoicePeer::STATUS, $this->filter_status);
        }
        if ('' != $this->filter_supplier = $this->getUser()->getAttribute('katao_supplier_invoice_filter_supplier')) {
            $criteria->add(KataoSupplierInvoicePeer::KATAO_SUPPLIER_ID, $this->filter_supplier);
        }
        if ('' != $this->filter_period = $this->getUser()->getAttribute('katao_supplier_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId())) {
            $criteria->add(KataoSupplierInvoicePeer::KATAO_PERIOD_ID, $this->filter_period);
        }

        $pager = new sfPropelPager('KataoSupplierInvoice', sfConfig::get('app_pager'));
        $pager->setCriteria($criteria);
        $pager->setPage($this->getRequestParameter('page', 1));
        $pager->init();
        $this->pager = $pager;

        $this->katao_supplier_invoiceList = $pager->getResults();
    }

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_status', $request->getParameter('filter_status'));
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_supplier', $request->getParameter('filter_supplier'));
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_period', $request->getParameter('filter_period'));
        return $this->redirect('kataoSupplierInvoice/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_status', '');
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_supplier', '');
        $this->getUser()->setAttribute('katao_supplier_invoice_filter_period', KataoPeriodPeer::getActivePeriod()->getId());
        return $this->redirect('kataoSupplierInvoice/index');
    }

    public function executeCreate($request) {
        $this->katao_supplier_invoice = new KataoSupplierInvoice();
        $this->katao_supplier_invoice_orders = array();

        $this->setTemplate('edit');
    }

    public function executeEdit($request) {
        $this->katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_supplier_invoice, 'Facture #' . $request->getParameter('id') . ' inconnue.');
    }

    public function executeUpdate($request) {
        $this->katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPk($request->getParameter('id'));
        if (is_null($this->katao_supplier_invoice)) {
            $this->katao_supplier_invoice = new KataoSupplierInvoice();
        }

        try {
            $con = Propel::getConnection();
            $con->begin();

            $this->katao_supplier_invoice->setKataoPeriodId($request->getParameter('period'));
            $this->katao_supplier_invoice->setKataoSupplierId($request->getParameter('supplier'));
            $this->katao_supplier_invoice->setReference($request->getParameter('reference'));

            list($d, $m, $y) = sfContext::getInstance()->getI18N()->getDateForCulture($request->getParameter('invoice_date'), 'fr');
            $this->katao_supplier_invoice->setInvoiceDate("$y-$m-$d");

            list($d, $m, $y) = sfContext::getInstance()->getI18N()->getDateForCulture($request->getParameter('due_date'), 'fr');
            $this->katao_supplier_invoice->setDueDate("$y-$m-$d");

            $this->katao_supplier_invoice->setComment($request->getParameter('comment'));

            if ($this->katao_supplier_invoice->isNew()) {
                // save supplier/katao data if new invoice
                $katao_supplier =/*(KataoSupplier)*/ $this->katao_supplier_invoice->getKataoSupplier();
                $this->katao_supplier_invoice->setSupplierName($katao_supplier->getName());
                $this->katao_supplier_invoice->setSupplierEmail($katao_supplier->getEmail());
                $this->katao_supplier_invoice->setSupplierAddress1($katao_supplier->getAddress1());
                $this->katao_supplier_invoice->setSupplierAddress2($katao_supplier->getAddress2());
                $this->katao_supplier_invoice->setSupplierZip($katao_supplier->getZip());
                $this->katao_supplier_invoice->setSupplierCity($katao_supplier->getCity());
                $this->katao_supplier_invoice->setKataoName(wpConfig::getName());
                $this->katao_supplier_invoice->setKataoAddress(wpConfig::getAddress());
                $this->katao_supplier_invoice->setKataoSiretNumber(wpConfig::getSiretNumber());
                $this->katao_supplier_invoice->setKataoRcsNumber(wpConfig::getRCSNumber());
                $this->katao_supplier_invoice->setKataoCapital(wpConfig::getCapital());
            }

            $tva_rates = array('0.2' => 1, '0.055' => 2, '0' => 0);
            $without_taxes_by_tva_rate = $request->getParameter('without_taxes_by_tva_rate[]');
            $discount_by_tva_rate = $request->getParameter('discount_by_tva_rate[]');
            $total_by_tva_rate = $request->getParameter('total_by_tva_rate[]');
            foreach ($tva_rates as $tva_rate_value => $tva_rate_const) {
                $setTauxBasesHt = sprintf('setTaux%dBasesHt', $tva_rate_const);
                $this->katao_supplier_invoice->$setTauxBasesHt(!empty($without_taxes_by_tva_rate[$tva_rate_const])?$without_taxes_by_tva_rate[$tva_rate_const]:0);

                $setTauxDiscountHt = sprintf('setTaux%dDiscountHt', $tva_rate_const);
                $this->katao_supplier_invoice->$setTauxDiscountHt(!empty($discount_by_tva_rate[$tva_rate_const])?$discount_by_tva_rate[$tva_rate_const]:0);

                $setTauxAmount = sprintf('setTaux%dAmount', $tva_rate_const);
                $this->katao_supplier_invoice->$setTauxAmount(!empty($total_by_tva_rate[$tva_rate_const])?$total_by_tva_rate[$tva_rate_const]:0);
            }

            $this->katao_supplier_invoice->setTotalHt($request->getParameter('without_taxes_total'));
            $this->katao_supplier_invoice->setTotalTva($request->getParameter('tva_total'));

            $this->katao_supplier_invoice->setFeesShippingHt($request->getParameter('fees_shipping_ht'));
            $this->katao_supplier_invoice->setFeesShippingRate($request->getParameter('fees_shipping_rate'));
            $this->katao_supplier_invoice->setFeesShippingTva($request->getParameter('fees_shipping_tva'));
            $this->katao_supplier_invoice->setFeesBillingHt($request->getParameter('fees_billing_ht'));
            $this->katao_supplier_invoice->setFeesBillingRate($request->getParameter('fees_billing_rate'));
            $this->katao_supplier_invoice->setFeesBillingTva($request->getParameter('fees_billing_tva'));

            $this->katao_supplier_invoice->save($con);

            if (!$this->katao_supplier_invoice->isNew()) {
                // delete existing relations between invoice and orders
                $criteria = new Criteria();
                $criteria->add(KataoSupplierInvoiceOrderPeer::KATAO_SUPPLIER_INVOICE_ID, $this->katao_supplier_invoice->getId());
                KataoSupplierInvoiceOrderPeer::doDelete($criteria, $con);
                // delete existing relations between invoice and products
                $criteria = new Criteria();
                $criteria->add(KataoSupplierInvoiceProductPeer::KATAO_SUPPLIER_INVOICE_ID, $this->katao_supplier_invoice->getId());
                KataoSupplierInvoiceProductPeer::doDelete($criteria, $con);
            }
            // save new relations between invoice and orders
            $orders = $request->getParameter('orders[]');
            if ($orders && is_array($orders) && 0 < count($orders)) {
                foreach ($orders as $katao_order_id) {
                    $katao_supplier_invoice_order = new KataoSupplierInvoiceOrder();
                    $katao_supplier_invoice_order->setKataoSupplierInvoice($this->katao_supplier_invoice);
                    $katao_supplier_invoice_order->setKataoOrderId($katao_order_id);
                    $katao_supplier_invoice_order->save($con);
                }
            }
            // save new relations between invoice and products
            // and update product price
            $product_quantity = $request->getParameter('product_quantity[]');
            $product_price_unit = $request->getParameter('product_price_unit[]');
            $product_price_total = $request->getParameter('product_price_total[]');
            foreach ($product_quantity as $katao_product_id => $quantity) {
                if (null != $katao_product = KataoProductPeer::retrieveByPK($katao_product_id, $con)) {
                    $katao_supplier_invoice_product = new KataoSupplierInvoiceProduct();
                    $katao_supplier_invoice_product->setKataoSupplierInvoice($this->katao_supplier_invoice);
                    $katao_supplier_invoice_product->setKataoProductId($katao_product_id);
                    $katao_supplier_invoice_product->setProductReference($katao_product->getReference());
                    $katao_supplier_invoice_product->setProductName($katao_product->getName());
                    $katao_supplier_invoice_product->setProductPriceEuro(!empty($product_price_unit[$katao_product_id])?$product_price_unit[$katao_product_id]:$katao_product->getUnitPriceEuro());
                    $katao_supplier_invoice_product->setProductMargin($katao_product->getMargin());
                    $katao_supplier_invoice_product->setProductTvaRate($katao_product->getTvaRate());
                    $katao_supplier_invoice_product->setQuantity($quantity);
                    $katao_supplier_invoice_product->setProductPriceTotal(!empty($product_price_total[$katao_product_id])?$product_price_total[$katao_product_id]:($quantity * $katao_product->getUnitPriceEuro() * (1 + $katao_product->getMargin()) * (1 + $katao_product->getTvaRate())));
                    $katao_supplier_invoice_product->save($con);

                    $katao_product->setUnitPriceEuro($katao_supplier_invoice_product->getProductPriceEuro());
                    $katao_product->save($con);
                }
            }

            $con->commit();
        }
        catch (Exception $e) {
            $con->rollback();
        }

        wpFlashMessages::addConfirmation('Facture "' . $this->katao_supplier_invoice->getReference() . '" sauvée avec succès.');
        $this->redirect('kataoSupplierInvoice/index');
    }

    public function executePay($request) {
        $this->redirectWithErrorUnless($this->katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');
        $this->redirectWithErrorIf(KataoSupplierInvoice::STATUS_RECEIVED != $this->katao_supplier_invoice->getStatus());

        if ($request->isMethod('post')) {
            $this->katao_supplier_invoice->setStatus(KataoSupplierInvoice::STATUS_PAID);

            $this->katao_supplier_invoice->setPaymentAmountEuro($request->getParameter('payment_amount_euro'));
            $this->katao_supplier_invoice->setPaymentAmountSol($request->getParameter('payment_amount_sol'));

            list($d, $m, $y) = sfContext::getInstance()->getI18N()->getDateForCulture($request->getParameter('payment_date'), 'fr');
            $this->katao_supplier_invoice->setPaymentDate("$y-$m-$d");

            $this->katao_supplier_invoice->setPaymentMode($request->getParameter('payment_mode'));
            if (KataoSupplierInvoice::PAYMENT_MODE_CREDIT_CARD != $this->katao_supplier_invoice->getPaymentMode()) {
                $this->katao_supplier_invoice->setPaymentDetails($request->getParameter('payment_details'));
            }

            $this->katao_supplier_invoice->save();

            wpFlashMessages::addConfirmation('Facture fournisseur "' . $this->katao_supplier_invoice->getReference() . '" payée avec succès.');
            $this->redirect('kataoSupplierInvoice/index');
        }
        // $this->katao_supplier_invoice->initPaymentAmounts();
    }

    public function executeExportPdf($request) {
        $this->redirectWithErrorUnless($katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        $content = $katao_supplier_invoice->generatePDF();

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="' . $katao_supplier_invoice->getReference() . '.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

    public function executeExportPDFAll($request) {
        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(KataoSupplierInvoicePeer::ID);
        return $this->exportSupplierInvoicesToPDF(KataoSupplierInvoicePeer::doSelect($criteria));
    }

    public function executeExportPDFSelected($request) {
        if (!wpPersistenceManager::isEmpty('katao_supplier_invoice')) {
            $criteria = new Criteria();
            $criteria->add(KataoSupplierInvoicePeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_supplier_invoice')), Criteria::IN);
            $criteria->addAscendingOrderByColumn(KataoSupplierInvoicePeer::ID);
            return $this->exportSupplierInvoicesToPDF(KataoSupplierInvoicePeer::doSelect($criteria));
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une facture.');
            $this->redirect('kataoSupplierInvoice/index');
        }
    }

    protected function exportSupplierInvoicesToPDF($katao_supplier_invoices) {
        $file = tempnam('tmp', 'zip');
        $archive = new ZipArchive();
        $archive->open($file, ZipArchive::OVERWRITE);

        foreach ($katao_supplier_invoices as/*(KataoSupplierInvoice)*/ $katao_supplier_invoice) {
            $archive->addFromString($katao_supplier_invoice->getReference() . '.pdf', $katao_supplier_invoice->generatePDF());
        }

        $archive->close();

        $response = $this->getResponse();
        $response->setContentType('application/zip');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="KATAO_Factures_Fournisseurs_' . date('Y-m-d') . '.zip"');
        $response->setHttpHeader('Content-Length', filesize($file));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent(file_get_contents($file));
        return sfView::NONE;
    }

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');

        $katao_supplier_invoice->delete();

        wpFlashMessages::addConfirmation('Facture "' . $katao_supplier_invoice->getReference() . '" supprimée avec succès.');
        $this->redirect('kataoSupplierInvoice/index');
    }

    public function executeDeleteMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_supplier_invoice')) {
            $criteria = new Criteria();
            $criteria->add(KataoSupplierInvoicePeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_supplier_invoice')), Criteria::IN);
            KataoSupplierInvoicePeer::doDelete($criteria);

            wpPersistenceManager::cleanSelection('katao_supplier_invoice');
            wpFlashMessages::addConfirmation('Les factures sélectionnées ont été supprimées avec succès.');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une facture.');
        }

        $this->redirect('kataoSupplierInvoice/index');
    }

    public function executeUpdateOrdersList($request) {
        $katao_supplier_invoice_orders = KataoSupplierInvoiceOrderPeer::getAllByKataoSupplierInvoiceId($request->getParameter('id'));

        $return = '';
        $katao_orders = KataoOrderPeer::getPossibleOrdersForSupplierInvoice($request->getParameter('period'), $request->getParameter('supplier'));
        if (0 < count($katao_orders)) {
            foreach ($katao_orders as/*(KataoOrder)*/ $katao_order) {
                $return .= sprintf('
<div>
	<input type="checkbox" name="orders[]" value="%d" id="orders_%d" class="supplier-invoice-order" onclick="updateProductsList();"%s />
	<label for="orders_%d">%s <i>pour %s</i></label>
</div>', $katao_order->getId(), $katao_order->getId(), !empty($katao_supplier_invoice_orders[$katao_order->getId()])?' checked="checked"':'', $katao_order->getId(), $katao_order->getNumber(), $katao_order->getKataoNode()->getCity());
            }
        } else {
            $return = '<i>Merci de choisir une période et un fournisseur</i>';
        }

        return $this->renderText($return);
    }

    public function executeUpdateProductsList($request) {
        $return = '<br /><i>Merci de sélectionner des commandes</i>';

        $tva_rates = array('0.2' => 1, '0.055' => 2, '0' => 0);
        $total_by_tva_rate = array('0.2' => 0, '0.055' => 0, '0' => 0);
        $discount_by_tva_rate = $total_by_tva_rate;

        $products = array();
        if (null != $katao_supplier_invoice = KataoSupplierInvoicePeer::retrieveByPK($request->getParameter('id'))) {
            foreach ($katao_supplier_invoice->getKataoSupplierInvoiceProducts() as/*(KataoSupplierInvoiceProduct)*/ $katao_supplier_invoice_product) {
                $quantity = $katao_supplier_invoice_product->getQuantity();
                $price = $katao_supplier_invoice_product->getProductPriceEuro();
                $sub_total = $katao_supplier_invoice_product->getProductPriceTotal();

                $total_by_tva_rate[(string)$katao_supplier_invoice_product->getProductTvaRate()] += $quantity * $price;

                $products[$katao_supplier_invoice_product->getKataoProductId()]['name'] = $katao_supplier_invoice_product->getProductName();
                $products[$katao_supplier_invoice_product->getKataoProductId()]['price'] = $price;
                $products[$katao_supplier_invoice_product->getKataoProductId()]['tva'] = $katao_supplier_invoice_product->getProductTvaRate();
                $products[$katao_supplier_invoice_product->getKataoProductId()]['quantity'] = $quantity;
                $products[$katao_supplier_invoice_product->getKataoProductId()]['sub_total'] = $sub_total;
            }
            $fees_shipping_ht = $katao_supplier_invoice->getFeesShippingHt();
            $fees_shipping_rate = $katao_supplier_invoice->getFeesShippingRate();
            $fees_shipping_tva = $katao_supplier_invoice->getFeesShippingTva();
            $fees_billing_ht = $katao_supplier_invoice->getFeesBillingHt();
            $fees_billing_rate = $katao_supplier_invoice->getFeesBillingRate();
            $fees_billing_tva = $katao_supplier_invoice->getFeesBillingTva();
        } else {
            if ('' != $orders = $request->getParameter('orders')) {
                $order_ids = explode(',', $orders);
                if (0 < count($order_ids)) {
                    foreach (KataoOrderPeer::retrieveByPKs($order_ids) as/*(KataoOrder)*/ $katao_order) {
                        foreach ($katao_order->getKataoOrderProducts() as/*(KataoOrderProduct)*/ $katao_order_product) {
                            $quantity = $katao_order_product->getHasBeenDelivered()?$katao_order_product->getQuantityDelivered():$katao_order_product->getQuantity();
                            $price = $katao_order_product->getProductPriceEuro();
                            $sub_total = $quantity * $price;

                            $total_by_tva_rate[(string)$katao_order_product->getProductTvaRate()] += $quantity * $katao_order_product->getProductPriceEuro();

                            $products[$katao_order_product->getKataoProductId()]['name'] = $katao_order_product->getProductName();
                            $products[$katao_order_product->getKataoProductId()]['price'] = $price;
                            $products[$katao_order_product->getKataoProductId()]['tva'] = $katao_order_product->getProductTvaRate();

                            if (!isset($products[$katao_order_product->getKataoProductId()]['quantity'])) {
                                $products[$katao_order_product->getKataoProductId()]['quantity'] = 0;
                            }
                            $products[$katao_order_product->getKataoProductId()]['quantity'] += $quantity;

                            if (!isset($products[$katao_order_product->getKataoProductId()]['sub_total'])) {
                                $products[$katao_order_product->getKataoProductId()]['sub_total'] = 0;
                            }
                            $products[$katao_order_product->getKataoProductId()]['sub_total'] += $sub_total;
                        }
                    }
                }
            }
            $fees_shipping_ht = 0;
            $fees_shipping_rate = '0';
            $fees_shipping_tva = 0;
            $fees_billing_ht = 0;
            $fees_billing_rate = '0';
            $fees_billing_tva = 0;
        }

        $total = 0;
        if (0 < count($products)) {
            $return = '
<table class="admin-sub-list">
<tr>
<th>Désignation</th>
<th nowrap="nowrap" width="1%" style="text-align:center!important">Quantité</th>
<th nowrap="nowrap" width="1%" style="text-align:right!important">P.U. HT</th>
<th nowrap="nowrap" width="1%" style="text-align:right!important">Montant HT</th>
<th nowrap="nowrap" width="1%" style="text-align:center!important">TVA</th>
</tr>';

            foreach ($products as $product_id => $product_data) {
                $return .= '
<tr>
	<td>' . $product_data['name'] . '</td>
	<td nowrap="nowrap" style="text-align:center!important"><input type="text" name="product_quantity[' . $product_id . ']" value="' . $product_data['quantity'] . '" id="product_quantity_' . $product_id . '" class="product-quantity-' . $tva_rates[(string)$product_data['tva']] . '" onchange="updateProductTotalPrice(' . $product_id . ');" style="width: 45px; text-align: center" /></td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="product_price_unit[' . $product_id . ']" value="' . round($product_data['price'], 2) . '" id="product_price_unit_' . $product_id . '" class="product-price-unit-' . $tva_rates[(string)$product_data['tva']] . '" onchange="updateProductTotalPrice(' . $product_id . ');" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="product_price_total[' . $product_id . ']" value="' . round($product_data['sub_total'], 2) . '" id="product_price_total_' . $product_id . '" class="product-price-total-' . $tva_rates[(string)$product_data['tva']] . '" onchange="updateTotalPrices();" style="width: 60px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important">' . (100 * $product_data['tva']) . '%</td>
</tr>';
            }

            $return .= '
</table>


<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
	<td>

<u>TVA (montant, remises) :</u>

<table class="admin-sub-list" style="width:1%!important">
<tr>
 	<th nowrap="nowrap" width="1%">Taux</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">Bases HT</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">Remises HT</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">Montant</th>
</tr>';
            $with_taxes_total = 0;
            $without_taxes_total = 0;
            $tva_total = 0;
            foreach ($total_by_tva_rate as $tva_rate => $tva_rate_total) {
                $tva_rate_discount = !empty($discount_by_tva_rate[$tva_rate])?$discount_by_tva_rate[$tva_rate]:0;
                if (!is_null($katao_supplier_invoice)) {
                    $getTauxBasesHt = sprintf('getTaux%dBasesHt', $tva_rates[(string)$tva_rate]);
                    $tva_rate_total = $katao_supplier_invoice->$getTauxBasesHt();

                    $getTauxDiscountHt = sprintf('getTaux%dDiscountHt', $tva_rates[(string)$tva_rate]);
                    $tva_rate_discount = $katao_supplier_invoice->$getTauxDiscountHt();

                    $getTauxAmount = sprintf('getTaux%dAmount', $tva_rates[(string)$tva_rate]);
                    $total_by_tva_rate2 = $katao_supplier_invoice->$getTauxAmount();
                } else {
                    $total_by_tva_rate2 = round($tva_rate_total * $tva_rate, 2);
                }

                $without_taxes_total += $tva_rate_total;
                $tva_total += round(($tva_rate_total - $tva_rate_discount) * $tva_rate, 2);

                $return .= '
<tr>
	<td nowrap="nowrap" style="text-align:right!important">' . (100 * $tva_rate) . '%</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="without_taxes_by_tva_rate[' . $tva_rates[(string)$tva_rate] . ']" value="' . $tva_rate_total . '" id="without_taxes_by_tva_rate_' . $tva_rates[(string)$tva_rate] . '" onchange="updateTotalPricesTTC();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="discount_by_tva_rate[' . $tva_rates[(string)$tva_rate] . ']" value="' . $tva_rate_discount . '" id="discount_by_tva_rate_' . $tva_rates[(string)$tva_rate] . '" onchange="updateTotalPricesTTC();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="total_by_tva_rate[' . $tva_rates[(string)$tva_rate] . ']" value="' . $total_by_tva_rate2 . '" id="total_by_tva_rate_' . $tva_rates[(string)$tva_rate] . '" onchange="updateTotalTVA();" style="width: 45px; text-align: right" />&nbsp;€</td>
</tr>';
            }

            if (!is_null($katao_supplier_invoice)) {
                $without_taxes_total = $katao_supplier_invoice->getTotalHt();
                $tva_total = $katao_supplier_invoice->getTotalTva();
            }

            $return .= '
</table>

	</td>
	<td>

<u>Frais divers :</u>

<table class="admin-sub-list" style="width:1%!important">
<tr>
 	<th nowrap="nowrap" width="1%">Frais</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">HT</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">Taux</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">TVA</th>
</tr>
<tr>
	<td>Port</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="fees_shipping_ht" id="fees_shipping_ht" value="' . $fees_shipping_ht . '" onchange="updateFeesTVA();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><select name="fees_shipping_rate" id="fees_shipping_rate" onchange="updateFeesTVA();">';
            foreach (array('0' => '0%', '0.055' => '5.5%', '0.2' => '20%') as $value => $label) {
                $return .= '<option value="' . $value . '"' . sprintf('%s', ($value == $fees_shipping_rate)?' selected="selected"':'') . '>' . $label . '</option>';
            }
            $return .= '</select></td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="fees_shipping_tva" id="fees_shipping_tva" value="' . $fees_shipping_tva . '" onchange="updateTotalTVA();" style="width: 45px; text-align: right" />&nbsp;€</td>
</tr>
<tr>
	<td>Facturation</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="fees_billing_ht" id="fees_billing_ht" value="' . $fees_billing_ht . '" onchange="updateFeesTVA();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><select name="fees_billing_rate" id="fees_billing_rate" onchange="updateFeesTVA();">';
            foreach (array('0' => '0%', '0.055' => '5.5%', '0.2' => '20%') as $value => $label) {
                $return .= '<option value="' . $value . '"' . sprintf('%s', ($value == $fees_billing_rate)?' selected="selected"':'') . '>' . $label . '</option>';
            }
            $return .= '</select></td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="fees_billing_tva" id="fees_billing_tva" value="' . $fees_billing_tva . '" onchange="updateTotalTVA();" style="width: 45px; text-align: right" />&nbsp;€</td>
</tr>
</table>

	</td>
	<td>

<u>Totaux :</u>

<table class="admin-sub-list" style="width:1%!important">
<tr>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">HT</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">TVA</th>
 	<th nowrap="nowrap" width="1%" style="text-align:right!important">TTC</th>
</tr>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="without_taxes_total" id="without_taxes_total" value="' . $without_taxes_total . '" onchange="updateTotalTTC();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td nowrap="nowrap" style="text-align:right!important"><input type="text" name="tva_total" id="tva_total" value="' . $tva_total . '" onchange="updateTotalTTC();" style="width: 45px; text-align: right" />&nbsp;€</td>
	<td><span id="ttc_total">' . ($without_taxes_total + $tva_total) . '</span>&nbsp;€</td>
</tr>
</table>

	</td>
</tr>
</table>';
        }

        return $this->renderText($return);
    }
}
