<?php

/**
 * Subclass for representing a row from the 'katao_cart' table.
 *
 * @package lib.model
 */
class KataoCart extends BaseKataoCart {
    const STATUS_IN_PROGRESS = 1;
    const STATUS_VALIDATED = 2;
    const STATUS_ARCHIVED = 3;

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

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

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

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

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

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

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

    /**
     * KataoCart::sumSols()
     *
     * @return int
     */
    public function sumSols() {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoCartProductPeer::KATAO_CART_ID);
        $criteria->addAsColumn('sum_sols', sprintf('SUM(%s)', KataoProductPeer::MAX_SOL_AMOUNT));
        $criteria->addJoin(KataoCartProductPeer::KATAO_PRODUCT_ID, KataoProductPeer::ID);
        $criteria->add(KataoCartProductPeer::KATAO_CART_ID, $this->getId());
        $criteria->addGroupByColumn(KataoCartProductPeer::KATAO_CART_ID);

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

        return $return;
    }

    public function getUsedSols() {
        $return = 0;

        $katao_user = $this->getKataoUser();
        $katao_member = $katao_user->getKataoMember();

        $current_amount_sol = $katao_member->getCurrentAmountSol();
        foreach ($this->getKataoCartProductsJoinKataoProduct() as/*(KataoCartProduct)*/ $katao_cart_product) {
            $katao_product = $katao_cart_product->getKataoProduct();
            $sol_amount = $katao_cart_product->getQuantity() * $katao_product->getMaxSolAmount();

            if ($current_amount_sol >= $sol_amount) {
                $return += $sol_amount;
                $current_amount_sol = max(0, $current_amount_sol - $sol_amount);
            } else {
                $return += $current_amount_sol;
                $current_amount_sol = 0;
            }
        }

        return $return;
    }

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

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

    /**
     * KataoCart::getMember()
     *
     * @return KataoMember
     */
    public function getMember() {
        $return = $this->getKataoUser()->getKataoMember();
        if (is_null($return)) {
            throw new Exception('Adhérent inconnu pour l\'utilisateur #' . $this->getKataoUserId());
        }
        return $return;
    }
    public function getMemberName() {
        return $this->getMember()->getFullName();
    }
    public function getMemberLink() {
        $result = '';
        if (null != $katao_member = $this->getMember()) {
            if ('' != $email = $katao_member->getFirstKataoUser()->getEmail()) {
                $result = mail_to($email, $katao_member->getFullName());
            } else {
                $result = $katao_member->getFullName();
            }
        }
        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_user = $this->getKataoUser();
        $katao_member = $katao_user->getKataoMember();
        if (is_null($katao_member)) {
            throw new Exception('Adhérent inconnu pour l\'utilisateur #' . $this->getId());
        }

        $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->addPageHeaderCart(1, $this, $katao_member, $katao_user);
        $y = 109;

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

        $current_amount_sol = $katao_member->getCurrentAmountSol();

        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(KataoCartProductPeer::PRODUCT_NAME);
        foreach ($this->getKataoCartProductsJoinKataoProduct($criteria) as/*(KataoCartProduct)*/ $katao_cart_product) {
            $katao_product = $katao_cart_product->getKataoProduct();

            if ($y > 244) {
                $page = $pdf->addPageHeaderCart($page, $this, $katao_member, $katao_user);
                $y = 109;
            }

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

            $quantity_asked = $katao_cart_product->getQuantity();
            $quantity_adjusted = $katao_cart_product->gethasBeenAdjusted()?$katao_cart_product->getQuantityAdjusted():CONST_N_A;
            $quantity_delivered = !is_null($katao_cart_product->getKataoOrderProduct())?($katao_cart_product->getKataoOrderProduct()->getHasBeenDelivered()?$katao_cart_product->getQuantityDelivered():CONST_N_A):CONST_N_A;

            $quantity = $quantity_delivered;
            if (CONST_N_A === $quantity) {
                $quantity = $quantity_adjusted;
            }
            if (CONST_N_A === $quantity) {
                $quantity = $quantity_asked;
            }

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

            $designation = utf8_decode($katao_cart_product->getProductName());
            $designation .= "\n" . utf8_decode(sprintf('Com. : %s - Aju. : %s / Dél. : %s', $quantity_asked , strip_tags($quantity_adjusted), strip_tags($quantity_delivered)));

            $sol_amount = $quantity * $katao_product->getMaxSolAmount();

            $used_sol = 0;
            if ($current_amount_sol >= $sol_amount) {
                $used_sol = $sol_amount;
                $current_amount_sol = max(0, $current_amount_sol - $sol_amount);
            } else {
                $used_sol = $current_amount_sol;
                $current_amount_sol = 0;
            }

            $designation .= "\n" . utf8_decode('Part de ' . wpConfig::getAdditionalCurrencyName() . ' utilisée : ') . $used_sol;

            $line = array("REFERENCE" => $katao_cart_product->getProductReference(),
                "DESIGNATION" => $designation,
                "QUANTITE" => $quantity,
                "P.U. TTC" => Utils::formatCurrency($katao_cart_product->getProductPriceWithTaxes()),
                "MONTANT TTC" => Utils::formatCurrency($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" => 0,
            "accompte" => 0, // montant de l'acompte (TTC)
            "accompte_percent" => 0, // pourcentage d'acompte (TTC)
            "Remarque" => "");

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

    public function getKataoCartProductsOrderByProductName() {
        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(KataoCartProductPeer::PRODUCT_NAME);
        return $this->getKataoCartProducts($criteria);
    }
}
