<?php

/**
 * Subclass for representing a row from the 'katao_supplier_invoice' table.
 *
 * @package lib.model
 */
class KataoSupplierInvoice extends BaseKataoSupplierInvoice {
    const STATUS_RECEIVED = 1;
    const STATUS_PAID = 2;

    const PAYMENT_MODE_BANK_TRANSFER = 1;
    const PAYMENT_MODE_CREDIT_CARD = 2;
    const PAYMENT_MODE_CHECK = 3;

    public function getStatusStr() {
        return KataoSupplierInvoicePeer::getStatusStr($this->getStatus());
    }

    public function getPaymentModeStr() {
        return KataoSupplierInvoicePeer::getPaymentModeStr($this->getPaymentMode());
    }

    public function getInvoiceDateStr() {
        return CatalyzDate::formatShort($this->getInvoiceDate(null));
    }

    public function getOrdersStr() {
        $return = array();
        foreach ($this->getKataoSupplierInvoiceOrdersJoinKataoOrder() as/*(KataoSupplierInvoiceOrder)*/ $katao_supplier_invoice_order) {
            $return[] = $katao_supplier_invoice_order->getKataoOrder()->getNumber();
        }
        return implode(', ', $return);
    }

    public function getUsedSolByProduct() {
        $return = array();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoiceProductPeer::KATAO_PRODUCT_ID);
        $criteria->addSelectColumn(KataoInvoiceProductPeer::SOL_AMOUNT);
        $criteria->addJoin(KataoInvoicePeer::ID, KataoInvoiceProductPeer::KATAO_INVOICE_ID);
        $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->getKataoPeriodId());
        $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);

        $rs = KataoInvoiceProductPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $return[$rs->getInt(1)] = $rs->getInt(2);
        }

        return $return;
    }
    public function getUsedSolTotal() {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addAsColumn('sum_products', sprintf('SUM(%s)', KataoInvoiceProductPeer::SOL_AMOUNT));
        $criteria->addJoin(KataoInvoicePeer::ID, KataoInvoiceProductPeer::KATAO_INVOICE_ID);
        $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->getKataoPeriodId());
        $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
        $criteria->addGroupByColumn(KataoInvoicePeer::ID);

        $rs = KataoInvoiceProductPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $return += $rs->getInt(1);
        }

        return $return;
    }

    public function generatePDF() {
        $katao_supplier = $this->getKataoSupplier();

        $tva_rates = array('0.055' => '2', '0.196' => '1');

        $pdf = new PDF_Invoice('P', 'mm', 'A4');

        $page = $pdf->addPageHeaderSupplierInvoice(1, $this, $katao_supplier);
        $y = 109;

        $used_sol_by_product = $this->getUsedSolByProduct();

        $total_by_tva_rate = array(1 => 0, 2 => 0);
        foreach ($this->getKataoSupplierInvoiceProductsJoinKataoProduct() as/*(KataoSupplierInvoiceProduct)*/ $katao_supplier_invoice_product) {
            if ($y > 244) {
                $page = $pdf->addPageHeaderSupplierInvoice($page, $this, $katao_supplier);
                $y = 109;
            }

            $tva_rate = !empty($tva_rates[(string)$katao_supplier_invoice_product->getProductTvaRate()])?$tva_rates[(string)$katao_supplier_invoice_product->getProductTvaRate()]:0;

            $quantity = $katao_supplier_invoice_product->getQuantity();
            $unit_price = $katao_supplier_invoice_product->getProductPriceEuro();
            $amount = $katao_supplier_invoice_product->getProductPriceTotal();

            if ($tva_rate) {
                $total_by_tva_rate[$tva_rate] += round($quantity * $katao_supplier_invoice_product->getProductPriceEuro(), 2);
            }

            $designation = utf8_decode($katao_supplier_invoice_product->getProductName());
            if (!empty($used_sol_by_product[$katao_supplier_invoice_product->getKataoProductId()])) {
                $designation .= "\n" . 'Dont ' . $used_sol_by_product[$katao_supplier_invoice_product->getKataoProductId()] . ' ' . wpConfig::getAdditionalCurrencyName();
            }

            $line = array("REFERENCE" => $katao_supplier_invoice_product->getProductReference(),
                "DESIGNATION" => $designation,
                "QUANTITE" => $quantity,
                "P.U. TTC" => round($unit_price, 2),
                "MONTANT TTC" => round($amount, 2),
                "TVA" => $tva_rate);
            $size = $pdf->addLine($y, $line);
            $y += $size + 2;
        }

        $total_by_tva_rate[1] = $this->getTaux1BasesHt();
        $total_by_tva_rate[2] = $this->getTaux2BasesHt();

        $pdf->addCadreTVAs();

        $tot_prods = array();
        foreach ($total_by_tva_rate as $tva_rate => $amount) {
            $tot_prods[] = array ("px_unit" => $amount, "qte" => 1, "tva" => $tva_rate);
        }
        $tab_tva = array("1" => 19.6,
            "2" => 5.5);
        $params = array("RemiseGlobale" => 1,
            "remise_tva" => 0, // {la remise s'applique sur ce code TVA}
            "remise" => 0, // {montant de la remise}
            "remise_percent" => 0, // {pourcentage de remise sur ce montant de TVA}
            "FraisPort" => 0,
            "portTTC" => 0, // montant des frais de ports TTC
            // par defaut la TVA = 19.6 %
            "portHT" => 0, // montant des frais de ports HT
            "portTVA" => 19.6, // valeur de la TVA a appliquer sur le montant HT
            "AccompteExige" => 0,
            "accompte" => 0, // montant de l'acompte (TTC)
            "accompte_percent" => 0, // pourcentage d'acompte (TTC)
            "Remarque" => "");

        $pdf->addTVAs($params, $tab_tva, $tot_prods, $this);

        $pdf->addCadreEurosFrancs();
        return $pdf->Output('', 'S');
    }

    public function initPaymentAmounts() {
        $payment_amount_euro = 0;
        $payment_amount_sol = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoiceProductPeer::QUANTITY);
        $criteria->addSelectColumn(KataoInvoiceProductPeer::PRODUCT_PRICE_EURO);
        $criteria->addSelectColumn(KataoInvoiceProductPeer::PRODUCT_TVA_RATE);
        $criteria->addSelectColumn(KataoInvoiceProductPeer::SOL_AMOUNT);
        $criteria->addJoin(KataoSupplierInvoiceOrderPeer::KATAO_ORDER_ID, KataoOrderPeer::ID);
        $criteria->addJoin(KataoOrderPeer::ID, KataoOrderProductPeer::KATAO_ORDER_ID);
        $criteria->addJoin(KataoOrderProductPeer::ID, KataoCartProductPeer::KATAO_ORDER_PRODUCT_ID);
        $criteria->addJoin(KataoCartProductPeer::KATAO_CART_ID, KataoCartPeer::ID);
        $criteria->addJoin(KataoCartPeer::KATAO_USER_ID, KataoUserPeer::ID);
        $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoInvoicePeer::KATAO_MEMBER_ID);
        $criteria->addJoin(KataoInvoicePeer::ID, KataoInvoiceProductPeer::KATAO_INVOICE_ID);
        $criteria->addJoin(KataoInvoiceProductPeer::KATAO_PRODUCT_ID, KataoSupplierInvoiceProductPeer::KATAO_PRODUCT_ID);
        $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->getKataoPeriodId());
        $criteria->add(KataoSupplierInvoiceProductPeer::KATAO_SUPPLIER_INVOICE_ID, $this->getId());
        $criteria->setDistinct();

        $rs = KataoInvoiceProductPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $payment_amount_euro += $rs->getInt(1) * round($rs->getFloat(2) * (1 + $rs->getFloat(3)), 2);
            $payment_amount_sol += $rs->getInt(4);
        }

        $this->setPaymentAmountEuro($payment_amount_euro - $payment_amount_sol / CONST_EURO_TO_SOL);
        $this->setPaymentAmountSol($payment_amount_sol);
    }
}