<?php

class KataoUser extends BaseKataoUser {
    const STATUS_PENDING = 1;
    const STATUS_ACTIVE = 2;
    const STATUS_DISABLED = 3;

    const SUBSCRIBE_WITH_SOLS = 1;
    const SUBSCRIBE_WITHOUT_SOLS = 2;
    const SUBSCRIBE_ADHESION_WITH_SOLS = 3;
    const SUBSCRIBE_ADHESION_WITHOUT_SOLS = 4;
    const ADD_SOLS = 5;

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

    public function save($con = null) {
        $this->initGmapCoordinates();
        parent::save($con);
    }

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

    public function getFullName() {
        $return = '';
        if (null != $katao_member = $this->getKataoMember()) {
            $return = $katao_member->getFullName();
        }
        if (null != $katao_supplier = $this->getKataoSupplier()) {
            if ('' != $return) {
                $return .= sprintf('(%s)', $katao_supplier->getName());
            } else {
                $return = $katao_supplier->getName();
            }
        }
        return $return;
    }

    public function getCompleteAdress() {
        $result = '';
        if ($this->getAddress1()) {
            $result .= ' ' . $this->getAddress1() ;
        }
        if ($this->getAddress2()) {
            $result .= ' ' . $this->getAddress2() ;
        }
        $result .= ' ' . $this->getZip() ;
        $result .= ' ' . $this->getCity() ;
        return $result;
    }

    public function getFullAdress() {
        $return = $this->getAddress1();
        if ('' != $this->getAddress2()) {
            $return .= "\n" . $this->getAddress2();
        }
        $return .= "\n";
        $return .= $this->getZip() ;
        $return .= ' ' . $this->getCity() ;
        return $return;
    }

    /**
     * KataoUser::getCredentials()
     *
     * @return array
     */
    public function getCredentials() {
        $return = array();
        if (null != $katao_member = $this->getKataoMember()) {
            $return[] = 'member';
            if ($katao_member->getIsReferer()) {
                $return[] = 'referer';
            }
            if ($katao_member->getIsDelegate()) {
                $return[] = 'delegate';
            }
        }
        if ($this->getKataoSupplierId()) {
            $return[] = 'supplier';
        }
        if ($this->getIsSeo()) {
            $return[] = 'seo';
        }
        if ($this->getIsAdmin()) {
            $return[] = 'admin';
            $return[] = 'administrator';
            $return[] = 'webmaster';
        }
        return $return;
    }

    /**
     * KataoUser::getCart()
     *
     * @param int $katao_period_id
     * @param int $katao_node_id
     * @return KataoCart
     */
    public function getCart($katao_period_id = false, $katao_node_id = false, $ignore_status = false) {
        $sf_user = sfContext::getInstance()->getUser();
        return KataoCartPeer::retrieveByUserAndPeriodAndNode($this->getId(), 
            $katao_period_id?$katao_period_id:$sf_user->getActivePeriod()->getId(), 
            $katao_node_id?$katao_node_id:$sf_user->getActiveNode()->getId(), $ignore_status);
    }

    /**
     * KataoUser::addProductToCart()
     *
     * @param integer $product_id
     * @param integer $quantity
     * @return
     */
    public function addProductToCart($product_id, $quantity = 1) {
        $katao_cart_product = KataoCartProductPeer::retrieveByCartAndProduct($this->getCart()->getId(), $product_id);
        if (null != $katao_product = KataoProductPeer::retrieveByPK($product_id)) {
            $katao_cart_product->setProductReference($katao_product->getReference());
            $katao_cart_product->setProductName($katao_product->getName());
            $katao_cart_product->setProductPriceEuro($katao_product->getUnitPriceEuro());
            $katao_cart_product->setProductMargin($katao_product->getMargin());
            $katao_cart_product->setProductTvaRate($katao_product->getTvaRate());
        }
        $katao_cart_product->setQuantity($quantity);
        $katao_cart_product->save();
    }

    /**
     * KataoUser::removeProductFromCart()
     *
     * @param integer $product_id
     * @return
     */
    public function removeProductFromCart($product_id) {
        KataoCartProductPeer::deleteByCartAndProduct($this->getCart()->getId(), $product_id);
    }

    public function validateCart() {
        $this->updateCartStatus(KataoCart::STATUS_VALIDATED);
    }

    public function unvalidateCart() {
        $this->updateCartStatus(KataoCart::STATUS_IN_PROGRESS);
    }

    protected function updateCartStatus($status) {
        $katao_cart = $this->getCart();
        $katao_cart->setStatus($status);
        $katao_cart->save();
    }

    public function getHistoryEuro($is_admin = false) {
        $return = array();

        sfLoader::loadHelpers(array('Tag', 'Url'));

        if ($this->isMember()) {
            $katao_member = $this->getKataoMember();
            $initial_amount_euro = $katao_member->getInitialAmountEuro();

            $account = $initial_amount_euro;

            $criteria = new Criteria();
            $criteria->add(KataoMemberDepositPeer::CURRENCY, KataoMemberDeposit::CURRENCY_EURO);
            $criteria->add(KataoMemberDepositPeer::STATUS, KataoMemberDeposit::STATUS_EXPIRED, Criteria::NOT_EQUAL);
            foreach ($katao_member->getKataoMemberDeposits($criteria) as/*(KataoMemberDeposit)*/ $katao_member_deposit) {
                $return[$katao_member_deposit->getCreatedAt(null)] = array('type' => 'deposit', 'date' => $katao_member_deposit->getCreatedAt(null), 'summary' => $katao_member_deposit->getPaymentModeStr(), 'amount' => $katao_member_deposit->getAmount(), 'account' => 0);
            }

            $criteria = new Criteria();
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
            foreach ($katao_member->getKataoInvoices($criteria) as/*(KataoInvoice)*/ $katao_invoice) {
                $amount = $katao_invoice->sumProducts();
                $amount -= $katao_invoice->getSolAmount() / CONST_EURO_TO_SOL;
                $return[$katao_invoice->getCreatedAt(null)] = array('type' => 'invoice', 'date' => $katao_invoice->getCreatedAt(null), 'summary' => 'Facture ' . link_to($katao_invoice->getNumber(), $is_admin?('@katao_invoice_pdf?id=' . $katao_invoice->getId()):('@katao_member_invoice?id=' . $katao_invoice->getId()), array('title' => 'Télécharger la facture en PDF')), 'amount' => $amount, 'account' => 0);
            }

            ksort($return);
            foreach ($return as $index => $data) {
                if (in_array($data['type'], array('invoice'))) {
                    $account -= $data['amount'];
                } elseif (in_array($data['type'], array('deposit'))) {
                    $account += $data['amount'];
                }
                $return[$index]['account'] = $account;
            }
            krsort($return);

            $return[] = array('type' => 'initial',
                'date' => $katao_member->getCreatedAt('U'),
                'summary' => 'Solde initial',
                'amount' => 0,
                'account' => $initial_amount_euro
                );
        }

        return $return;
    }

    public function getHistorySol($is_admin = false) {
        $return = array();

        sfLoader::loadHelpers(array('Tag', 'Url'));

        if ($this->isMember()) {
            $katao_member = $this->getKataoMember();
            $initial_amount_sol = $katao_member->getInitialAmountSol();

            $account = $initial_amount_sol;

            $criteria = new Criteria();
            $criteria->add(KataoMemberDepositPeer::CURRENCY, KataoMemberDeposit::CURRENCY_SOL);
            $criteria->add(KataoMemberDepositPeer::STATUS, KataoMemberDeposit::STATUS_EXPIRED, Criteria::NOT_EQUAL);
            foreach ($katao_member->getKataoMemberDeposits($criteria) as/*(KataoMemberDeposit)*/ $katao_member_deposit) {
                $ts = $katao_member_deposit->getCreatedAt(null);
                while (isset($return[$ts])) {
                    $ts++;
                }
                $return[$ts] = array(
                    'type' => 'deposit',
                    'date' => $katao_member_deposit->getCreatedAt(null),
                    'summary' => $katao_member_deposit->getPaymentModeStr(),
                    'amount' => $katao_member_deposit->getAmount(),
                    'account' => 0
                    );
            }

            $criteria = new Criteria();
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
            foreach ($katao_member->getKataoInvoices($criteria) as/*(KataoInvoice)*/ $katao_invoice) {
                $ts = $katao_invoice->getCreatedAt(null);
                while (isset($return[$ts])) {
                    $ts++;
                }
                $return[$ts] = array(
                    'type' => 'invoice',
                    'date' => $katao_invoice->getCreatedAt(null),
                    'summary' => 'Facture ' . link_to($katao_invoice->getNumber(), $is_admin?('@katao_invoice_pdf?id=' . $katao_invoice->getId()):('@katao_member_invoice?id=' . $katao_invoice->getId()), array('title' => 'Télécharger la facture en PDF')),
                    'amount' => $katao_invoice->getSolAmount(),
                    'account' => 0
                    );
            }

            ksort($return);
            foreach ($return as $index => $data) {
                if (in_array($data['type'], array('invoice'))) {
                    $account -= $data['amount'];
                } elseif (in_array($data['type'], array('deposit'))) {
                    $account += $data['amount'];
                }
                $return[$index]['account'] = $account;
            }
            krsort($return);

            $return[] = array('type' => 'initial',
                'date' => $katao_member->getCreatedAt('U'),
                'summary' => 'Solde initial',
                'amount' => 0,
                'account' => $initial_amount_sol
                );
        }

        return $return;
    }

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

        if ($this->isSupplier()) {
            $katao_supplier = $this->getKataoSupplier();

            $criteria = new Criteria();
            $criteria->add(KataoOrderPeer::STATUS, KataoOrder::STATUS_SENT, Criteria::GREATER_EQUAL);
            $criteria->addAscendingOrderbyColumn(KataoOrderPeer::CREATED_AT);
            foreach ($katao_supplier->getKataoOrders($criteria) as/*(KataoOrder)*/ $katao_order) {
                $used_sol = 0;
                $used_sol_by_product = $katao_order->getUsedSolByProduct();
                foreach ($used_sol_by_product as $katao_product_id => $sol_amount) {
                    $used_sol += $sol_amount;
                }

                $return[$katao_order->getId()] = array('date' => $katao_order->getCreatedAt(null), 'number' => $katao_order->getNumber(), 'amount_euro' => $katao_order->sumProducts(), 'amount_sol' => $used_sol, 'period' => $katao_order->getKataoPeriod()->getName(), 'node' => $katao_order->getKataoNode()->getCity());
            }
        }

        return $return;
    }

    public function isBothMemberAndSupplier() {
        return $this->getKataoMemberId() && $this->getKataoSupplierId();
    }
    public function isMember() {
        return (bool)$this->getKataoMemberId();
    }
    public function isSupplier() {
        return (bool)$this->getKataoSupplierId();
    }

    public function getManagedNodeIds() {
        $return = array();
        if ($this->getIsSeo() || $this->getIsAdmin()) {
            foreach (KataoNodePeer::getAllArray() as $katao_node_id => $katao_node_city) {
                $return[$katao_node_id] = true;
            }
        } else {
            foreach ($this->getKataoNodes() as/*(KataoNode)*/ $katao_node) {
                $return[$katao_node->getId()] = true;
            }
        }

        return $return;
    }

    public function initGmapCoordinates($force = false) {
        if ($this->isNew() || $force) {
            $lat_lng = Utils::getGmapLatLng($this->getCompleteAdress(), $this->getZip() . ' ' . $this->getCity());
            $this->setGmapLat($lat_lng['lat']);
            $this->setGmapLng($lat_lng['lng']);
        }
    }
}
