<?php

/**
 * Subclass for representing a row from the 'katao_order_product' table.
 *
 * @package lib.model
 */
class KataoOrderProduct extends BaseKataoOrderProduct {
    public function getProductPriceWithoutTaxes() {
        return round($this->getProductPriceEuro() * (1 + $this->getProductMargin()), 2);
    }

    public function getProductPriceWithTaxes() {
        return round($this->getProductPriceEuro() * (1 + $this->getProductMargin()) * (1 + $this->getProductTvaRate()), 2);
    }

    public function getMembersWithoutProduct() {
        $return = KataoMemberPeer::getAll(false, false, $this->getKataoOrder()->getKataoNodeId());

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoUserPeer::ID);
        $criteria->addJoin(KataoUserPeer::ID, KataoCartPeer::KATAO_USER_ID);
        $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);
        $criteria->addJoin(KataoCartPeer::ID, KataoCartProductPeer::KATAO_CART_ID);
        $criteria->add(KataoCartProductPeer::KATAO_ORDER_PRODUCT_ID, $this->getId());

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

        return $return;
    }

    /**
     * KataoOrderProduct::addProductToUser()
     *
     * @param int $katao_user_id
     * @param int $quantity
     * @return
     */
    public function addProductToUser($katao_user_id, $quantity) {
        if (null != $katao_user = KataoUserPeer::retrieveByPK($katao_user_id)) {
            $katao_order = $this->getKataoOrder();

            $katao_cart = $katao_user->getCart($katao_order->getKataoPeriodId(), $katao_order->getKataoNodeId());
            $katao_cart->setStatus(KataoCart::STATUS_VALIDATED);
            $katao_cart->save();

            $katao_cart_product = new KataoCartProduct();
            $katao_cart_product->setKataoCart($katao_cart);
            $katao_cart_product->setKataoProductId($this->getKataoProductId());
            $katao_cart_product->setProductReference($this->getProductReference());
            $katao_cart_product->setProductName($this->getProductName());
            $katao_cart_product->setProductPriceEuro($this->getProductPriceEuro());
            $katao_cart_product->setProductMargin($this->getProductMargin());
            $katao_cart_product->setProductTvaRate($this->getProductTvaRate());
            $katao_cart_product->setQuantity(0);
            $katao_cart_product->setKataoOrderProduct($this);
            $katao_cart_product->setQuantityAdjusted($quantity);
            $katao_cart_product->setHasBeenAdjusted(true);
            $katao_cart_product->save();
        }
    }
}