<?php

class KataoProduct extends BaseKataoProduct {
    public function __construct() {
        $this->setMargin(wpConfig::getDefaultProductMargin() / 100);
    }

    public function save($con = null) {
        if ('' == $this->getUrlIdentifier()) {
            $this->setUrlIdentifier(Catalyz::normalizeUrlIdentifier($this->getName()));
        }

        if ('' == $this->getAccountingCodePurchase()) {
            $this->setAccountingCodePurchase(wpConfig::getAccountingCodePrefixPurchase() . $this->getKataoProductFamily()->getKataoProductCategory()->getAccountingCodeSuffix());
        }
        if ('' == $this->getAccountingCodeSell()) {
            $this->setAccountingCodeSell(wpConfig::getAccountingCodePrefixSell() . $this->getKataoProductFamily()->getKataoProductCategory()->getAccountingCodeSuffix());
        }

        if (!$this->isNew() && ($this->isColumnModified(KataoProductPeer::UNIT_PRICE_EURO) || $this->isColumnModified(KataoProductPeer::MARGIN) || $this->isColumnModified(KataoProductPeer::TVA_RATE))) {
            $this->notifyProductPriceModification();
        }

        parent::save($con);
    }

    public function delete($con = null) {
        parent::delete($con);
        if (is_file(sfConfig::get('sf_web_dir') . $this->getPicture())) {
            unlink(sfConfig::get('sf_web_dir') . $this->getPicture());
        }
    }

    public function getTotalPriceWithoutTaxes() {
        return round($this->getUnitPriceEuro() * (1 + $this->getMargin()), 2);
    }

    public function getTotalPriceWithTaxes() {
        return round($this->getUnitPriceEuro() * (1 + $this->getMargin()) * (1 + $this->getTvaRate()), 2);
    }

    public function isCartable() {
        $return = true;
        $return &= in_array($this->getId(), sfContext::getInstance()->getUser()->getCartableProducts());
        $return &= sfContext::getInstance()->getUser()->getActivePeriod()->getOrderEndedAt('Y-m-d') >= date('Y-m-d');
        return $return;
    }

    public function getCompletedPackages($katao_period_id, $katao_node_id, $with_adjusted_quantity = false) {
        return $this->getMinOrderNumber()?floor($this->getOrderedProductQuantity($katao_period_id, $katao_node_id, $with_adjusted_quantity) / $this->getMinOrderNumber()):0;
    }

    public function getLastIncompletePackageQuantity($katao_period_id, $katao_node_id, $with_adjusted_quantity = false) {
        $ordered_product_quantity = $this->getOrderedProductQuantity($katao_period_id, $katao_node_id, $with_adjusted_quantity);
        $min_order_number = $this->getMinOrderNumber();
        return $min_order_number?($ordered_product_quantity - $min_order_number * floor($ordered_product_quantity / $min_order_number)):0;
    }

    protected function getOrderedProductQuantity($katao_period_id, $katao_node_id, $with_adjusted_quantity = false) {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoCartProductPeer::KATAO_PRODUCT_ID);
        if ($with_adjusted_quantity) {
            $criteria->addAsColumn('quantity', sprintf('SUM(%s)', KataoCartProductPeer::QUANTITY_ADJUSTED));
        } else {
            $criteria->addAsColumn('quantity', sprintf('SUM(%s)', KataoCartProductPeer::QUANTITY));
        }
        $criteria->addJoin(KataoCartPeer::ID, KataoCartProductPeer::KATAO_CART_ID);
        $criteria->add(KataoCartPeer::STATUS, array(KataoCart::STATUS_IN_PROGRESS, KataoCart::STATUS_VALIDATED), Criteria::IN);
        $criteria->add(KataoCartPeer::KATAO_PERIOD_ID, $katao_period_id);
        $criteria->add(KataoCartPeer::KATAO_NODE_ID, $katao_node_id);
        $criteria->add(KataoCartProductPeer::KATAO_PRODUCT_ID, $this->getId());
        $criteria->addGroupByColumn(KataoCartProductPeer::KATAO_PRODUCT_ID);

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

        return $return;
    }

    /**
     * KataoProduct::getUrlDetails()
     *
     * @param string $katao_product_category
     * @param string $katao_product_family
     * @return string
     */
    public function getUrlDetails($katao_product_category = '', $katao_product_family = '') {
        if ('' == $katao_product_category || '' == $katao_product_family) {
            $criteria = new Criteria();
            $criteria->addSelectColumn(KataoProductFamilyPeer::URL_IDENTIFIER);
            $criteria->addSelectColumn(KataoProductCategoryPeer::URL_IDENTIFIER);
            $criteria->addJoin(KataoProductPeer::KATAO_PRODUCT_FAMILY_ID, KataoProductFamilyPeer::ID);
            $criteria->addJoin(KataoProductFamilyPeer::KATAO_PRODUCT_CATEGORY_ID, KataoProductCategoryPeer::ID);
            $criteria->add(KataoProductPeer::URL_IDENTIFIER, $this->getUrlIdentifier());
            $criteria->setLimit(1);

            $rs = KataoProductPeer::doSelectRS($criteria);
            if ($rs->next()) {
                $katao_product_category = $rs->getString(2);
                $katao_product_family = $rs->getString(1);
            }
        }
        return url_for('@katao_boutique_produit?category=' . $katao_product_category . '&family=' . $katao_product_family . '&product=' . $this->getUrlIdentifier());
    }

    public function getCategoryLink($with_link = false) {
        $return = '';

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoProductCategoryPeer::ID);
        $criteria->addSelectColumn(KataoProductCategoryPeer::NAME);
        $criteria->addJoin(KataoProductPeer::KATAO_PRODUCT_FAMILY_ID, KataoProductFamilyPeer::ID);
        $criteria->addJoin(KataoProductFamilyPeer::KATAO_PRODUCT_CATEGORY_ID, KataoProductCategoryPeer::ID);
        $criteria->add(KataoProductPeer::ID, $this->getId());
        $criteria->setLimit(1);

        $rs = KataoProductCategoryPeer::doSelectRS($criteria);
        if ($rs->next()) {
            if ($with_link) {
                $return = link_to($rs->getString(2), '@katao_product_category_show?id=' . $rs->getInt(1));
            } else {
                $return = $rs->getString(2);
            }
        }

        return $return;
    }

    public function getFamilyLink($with_link = false) {
        $return = '';

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoProductFamilyPeer::ID);
        $criteria->addSelectColumn(KataoProductFamilyPeer::NAME);
        $criteria->addJoin(KataoProductPeer::KATAO_PRODUCT_FAMILY_ID, KataoProductFamilyPeer::ID);
        $criteria->add(KataoProductPeer::ID, $this->getId());
        $criteria->setLimit(1);

        $rs = KataoProductFamilyPeer::doSelectRS($criteria);
        if ($rs->next()) {
            if ($with_link) {
                $return = link_to($rs->getString(2), '@katao_product_family_show?id=' . $rs->getInt(1));
            } else {
                $return = $rs->getString(2);
            }
        }

        return $return;
    }

    public function getSupplierName() {
        $result = '';
        if (null != $katao_supplier = $this->getKataoSupplier()) {
            $result = $katao_supplier->getName();
        }
        return $result;
    }
    public function getSupplierLink($with_link = false) {
        $result = '';
        if (null != $katao_supplier = $this->getKataoSupplier()) {
            if ($with_link) {
                $result = link_to($katao_supplier->getName(), '@katao_supplier_show?id=' . $katao_supplier->getId());
            } else {
                $result = link_to($katao_supplier->getName(), sprintf('%sles-partenaires/%s', sfConfig::get('app_katao_frontend_url'), $katao_supplier->getUrlIdentifier()), array('target' => '_blank'));
            }
        }
        return $result;
    }

    public function getOrderDetails($katao_period_id, $katao_node_id, $with_adjusted_quantity = false) {
        $completed_packages = $this->getCompletedPackages($katao_period_id, $katao_node_id, $with_adjusted_quantity);
        $last_incomplete_package = $this->getLastIncompletePackageQuantity($katao_period_id, $katao_node_id, $with_adjusted_quantity);
        return sprintf('%d (%d / %d)%s', $completed_packages, $last_incomplete_package, $this->getMinOrderNumber(), ($completed_packages || $last_incomplete_package)?sprintf(' %s', image_tag($last_incomplete_package?'actions/bullet_red.png':'actions/bullet_green.png', array('alt' => $last_incomplete_package?'Colis incomplet':'Colis complet', 'align' => 'top'))):'');
    }

    public function getUnitPriceEuroStr() {
        return Utils::formatCurrencyEuro($this->getUnitPriceEuro());
    }

    public function getIsArchivedStr() {
        return $this->getIsArchived()?'Oui':'Non';
    }

    public function getAuthorizeDecimalStr() {
        return $this->getAuthorizeDecimal()?'Oui':'Non';
    }

    public function getRealPicture() {
        return $this->hasPicture()?$this->getPicture():(wpConfig::hasDefaultProductPicture()?wpConfig::getDefaultProductPicture():'img04.gif');
    }

    public function hasPicture() {
        return '' != $this->getPicture() && is_file(sfConfig::get('sf_web_dir') . $this->getPicture());
    }

    public function getTotalPriceWithTaxesStr() {
        return Utils::formatCurrencyEuro($this->getTotalPriceWithTaxes());
    }

    public function getMarginStr() {
        return sprintf('%s%%', 100 * $this->getMargin());
    }
    public function getTvaRateStr() {
        return sprintf('%s%%', 100 * $this->getTvaRate());
    }

    public function notifyProductPriceModification() {
        return true;
        // désactivation temporaire suite au ticket #001525 (supprimer l'envois des modifs de prix au clients)
        $criteria = new Criteria();
        $criteria->add(KataoCartProductPeer::KATAO_PRODUCT_ID, $this->getId());
        $criteria->add(KataoCartPeer::STATUS, array(KataoCart::STATUS_IN_PROGRESS, KataoCart::STATUS_VALIDATED), Criteria::IN);
        $criteria->addJoin(KataoCartProductPeer::KATAO_CART_ID, KataoCartPeer::ID);
        $criteria->setDistinct();

        $katao_carts = KataoCartPeer::doSelectJoinKataoUser($criteria);
        if (0 < count($katao_carts)) {
            // referer
            $katao_user_referer = null;
            if (null != $katao_member_referer = $this->getKataoSupplier()->getKataoMemberRelatedByRefererId()) {
                $katao_user_referer = $katao_member_referer->getFirstKataoUser();
            }
            // seo
            $katao_user_seo = null;
            if (null != $katao_member_seo = wpConfig::getInstance()->getKataoMember()) {
                $katao_user_seo = $katao_member_seo->getFirstKataoUser();
            }

            $mailer = new wpMail();
            foreach ($katao_carts as/*(KataoCart)*/ $katao_cart) {
                try {
                    // member
                    $katao_user = $katao_cart->getKataoUser();
                    $katao_member = $katao_user->getKataoMember();
                    $mailer->send(new Swift_Message('KATAO : modification d\'un produit de votre panier', sprintf('Bonjour %s,

Le produit "%s" (réf. %s, prix unit. %s) vient d\'être modifié.
Votre panier a automatiquement été invalidé.

Cliquez sur le lien ci-dessous pour accèder à votre panier :
%smon-panier

A bientôt,
L\'équipe KATAO', $katao_user->getFullName(), $this->getName(), $this->getReference(), Utils::formatCurrencyEuro($this->getTotalPriceWithTaxes()), sfConfig::get('app_katao_frontend_url'))), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));

                    $recipients = new Swift_RecipientList();
                    if (!is_null($katao_user_referer)) {
                        $recipients->addTo($katao_user_referer->getEmail(), $katao_user_referer->getFullName());
                    }
                    if (!is_null($katao_user_seo)) {
                        $recipients->addTo($katao_user_seo->getEmail(), $katao_user_seo->getFullName());
                    }
                    // delegate
                    if (null != $katao_user_delegate = $katao_member->getKataoNode()->getKataoUser()) {
                        $recipients->addTo($katao_user_delegate->getEmail(), $katao_user_delegate->getFullName());
                    }
                    $mailer->send(new Swift_Message(sprintf('KATAO : modification d\'un produit du panier de %s', $katao_user->getFullName()), sprintf('Bonjour,

Le produit "%s" (réf. %s, prix unit. %s) vient d\'être modifié.
Le panier de cet adhérent a automatiquement été invalidé.

Cliquez sur le lien ci-dessous pour visualiser les demandes :
%sgestion-des-demandes

A bientôt,
L\'équipe KATAO', $this->getName(), $this->getReference(), Utils::formatCurrencyEuro($this->getTotalPriceWithTaxes()), sfConfig::get('app_katao_backend_url'))), $recipients, sfConfig::get('app_mail_from'));
                    // unvalidate cart
                    $katao_cart->setStatus(KataoCart::STATUS_IN_PROGRESS);
                    $katao_cart->save();
                }
                catch (Exception $e) {
                    $mailer->disconnect();
                }
            }
            $mailer->disconnect();
        }
    }

    public function getMaxSolAmountStr() {
        return Utils::formatCurrencySol($this->getMaxSolAmount());
    }

    public function isDeletable() {
        return (0 == $this->countKataoCartProducts()) && (0 == $this->countKataoOrderProducts()) && (0 == $this->countKataoInvoiceProducts());
    }

    /**
     * KataoProduct::getTotalReceivedQuantity()
     *
     * @param int $katao_period_id
     * @param int $katao_node_id
     * @return int
     */
    public function getTotalReceivedQuantity($katao_period_id, $katao_node_id) {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoOrderProductPeer::QUANTITY_RECEIVED);
        $criteria->addJoin(KataoOrderProductPeer::KATAO_ORDER_ID, KataoOrderPeer::ID);
        $criteria->add(KataoOrderProductPeer::KATAO_PRODUCT_ID, $this->getId());
        $criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $katao_period_id);
        $criteria->add(KataoOrderPeer::KATAO_NODE_ID, $katao_node_id);

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

        return $return;
    }

    /**
     * KataoProduct::getTotalDeliveredQuantity()
     *
     * @param int $katao_period_id
     * @param int $katao_node_id
     * @return int
     */
    public function getTotalDeliveredQuantity($katao_invoice_id = false, $katao_period_id, $katao_node_id) {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoiceProductPeer::QUANTITY_DELIVERED);
        $criteria->addJoin(KataoInvoiceProductPeer::KATAO_INVOICE_ID, KataoInvoicePeer::ID);
        $criteria->add(KataoInvoiceProductPeer::KATAO_PRODUCT_ID, $this->getId());
        if ($katao_invoice_id) {
            $criteria->add(KataoInvoicePeer::ID, $katao_invoice_id, Criteria::NOT_EQUAL);
        }
        $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $katao_period_id);
        $criteria->add(KataoInvoicePeer::KATAO_NODE_ID, $katao_node_id);

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

        return $return;
    }

    public function getUnitPriceEuroCalculated() {
        $total_ttc = $this->getTotalPriceWithTaxes();
        return $total_ttc / (1 + $this->getMargin()) / (1 + $this->getTvaRate());
    }
}