<?php

/**
 * Subclass for representing a row from the 'katao_invoice' table.
 *
 * @package lib.model
 */
class KataoInvoice extends BaseKataoInvoice {
    const STATUS_GENERATED = 1;
    const STATUS_DELIVERED = 2;
    const STATUS_VALIDATED = 3;
    const STATUS_SENT = 4;

    public function __toString() {
        return $this->getNumber();
    }

    public function getNumber() {
        return sprintf('FA%04d', $this->getId());
    }

    /**
     * KataoInvoice::countProducts()
     *
     * @return integer
     */
    public function countProducts() {
        return $this->countKataoCartProducts();
    }

    /**
     * KataoInvoice::sumProducts()
     *
     * @return float
     */
    public function sumProducts() {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoiceProductPeer::KATAO_INVOICE_ID);
        $criteria->addAsColumn('sum_products', sprintf('SUM(ROUND(%s * (1 + %s) * (1 + %s), 2) * %s)', KataoInvoiceProductPeer::PRODUCT_PRICE_EURO, KataoInvoiceProductPeer::PRODUCT_MARGIN, KataoInvoiceProductPeer::PRODUCT_TVA_RATE, KataoInvoiceProductPeer::QUANTITY_DELIVERED));
        $criteria->add(KataoInvoiceProductPeer::KATAO_INVOICE_ID, $this->getId());
        $criteria->addGroupByColumn(KataoInvoiceProductPeer::KATAO_INVOICE_ID);

        $rs = KataoInvoiceProductPeer::doSelectRS($criteria);
        if ($rs->next()) {
            $return = $rs->getFloat(2);
        }

        return $return;
    }
    public function sumProductsStr() {
        return Utils::formatCurrencyEuro($this->sumProducts());
    }

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

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

    public function getMemberName() {
        return $this->getKataoMember()->getFullName();
    }
    public function getMemberLink() {
        $result = '';
        if (null != $katao_member = $this->getKataoMember()) {
            $result = link_to($katao_member->getFullName(), '@katao_member_show?id=' . $katao_member->getId());
        }
        return $result;
    }

    public function getNodeLink($with_link = false) {
        if ($with_link) {
            return link_to($this->getKataoNode()->getCity(), '@katao_node_show?id=' . $this->getKataoNodeId());
        }
        return $this->getKataoNode()->getCity();
    }

    public function getPeriodLink($with_link = false) {
        if ($with_link) {
            return link_to($this->getKataoPeriod()->getName(), '@katao_node_show?id=' . $this->getKataoPeriodId());
        }
        return $this->getKataoPeriod()->getName();
    }

    public function generatePDF() {
        $katao_member = $this->getKataoMember();

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

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

        $page = $pdf->addPageHeaderInvoice(1, $this, $katao_member);
        $y = 109;

        $total_by_tva_rate = array(1 => 0, 2 => 0);

    	$criteria = new Criteria();
    	$criteria->addAscendingOrderByColumn(KataoInvoiceProductPeer::PRODUCT_NAME);
        foreach ($this->getKataoInvoiceProductsJoinKataoProduct($criteria) as/*(KataoInvoiceProduct)*/ $katao_invoice_product) {
            if ($y > 244) {
                $page = $pdf->addPageHeaderInvoice($page, $this, $katao_member);
                $y = 109;
            }

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

            $amount = $katao_invoice_product->getQuantityDelivered() * $katao_invoice_product->getProductPriceWithTaxes();
            if ($tva_rate) {
                $total_by_tva_rate[$tva_rate] += $amount;
            }

            $designation = utf8_decode($katao_invoice_product->getProductName());
            $designation .= "\n" . 'Dont ' . $katao_invoice_product->getSolAmount() . ' ' . wpConfig::getAdditionalCurrencyName();

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

        $pdf->addCadreTVAs();

        $tot_prods = array();
        foreach ($total_by_tva_rate as $tva_rate => $amount) {
            $tot_prods[] = array ("px_unit" => round($amount / (1 + $tva_rates_map[$tva_rate]), 2), "qte" => 1, "tva" => $tva_rate);
        }
        $tab_tva = array("1" => 20,
            "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 = 20 %
            "portHT" => 0, // montant des frais de ports HT
            "portTVA" => 20, // valeur de la TVA a appliquer sur le montant HT
            "AccompteExige" => 1,
            "accompte" => 0, // montant de l'acompte (TTC)
            "accompte_percent" => 100, // pourcentage d'acompte (TTC)
            "Remarque" => "");

        $pdf->addTVAs($params, $tab_tva, $tot_prods);
        $pdf->addCadreEurosFrancs();
        return $pdf->Output('', 'S');
    }

    public function getOtherProducts() {
        $products = array();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoiceProductPeer::KATAO_PRODUCT_ID);
        $criteria->add(KataoInvoiceProductPeer::KATAO_INVOICE_ID, $this->getId());

        $rs = KataoProductPeer::doSelectRS($criteria);
        while ($rs->next()) {
            $products[$rs->getInt(1)] = true;
        }

        $return = array();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoProductPeer::ID);
        $criteria->addSelectColumn(KataoProductPeer::NAME);
        $criteria->addJoin(KataoProductPeer::ID, KataoOrderProductPeer::KATAO_PRODUCT_ID);
        $criteria->addJoin(KataoOrderProductPeer::KATAO_ORDER_ID, KataoOrderPeer::ID);
        $criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $this->getKataoPeriodId());
        $criteria->add(KataoOrderPeer::KATAO_NODE_ID, $this->getKataoNodeId());
        if (0 < count($products)) {
            $criteria->add(KataoProductPeer::ID, array_keys($products), Criteria::NOT_IN);
        }
        $criteria->addAscendingOrderByColumn(KataoProductPeer::NAME);

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

        return $return;
    }

    public function getKataoInvoiceProductsOrderByProduct() {
        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(KataoInvoiceProductPeer::PRODUCT_NAME);
        return $this->getKataoInvoiceProducts($criteria);
    }
}
