<?php

/**
 * Subclass for representing a row from the 'katao_member' table.
 *
 * @package lib.model
 */
class KataoMember extends BaseKataoMember {
    public function save($con = null)
    {
        $this->initAccountingCode();
        parent::save($con);
    }

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

    /**
     * KataoMember::getKataoNode()
     *
     * @param Connection $con
     * @return KataoNode
     * @throws PropelException
     */
    public function getKataoNode($con = null)
    {
        return $this->getKataoNodeRelatedByKataoNodeId();
    }

    public function getFullName()
    {
        // return mb_convert_case($this->getFirstName(), MB_CASE_TITLE, "UTF-8") . ' ' . strtoupper($this->getLastName());
        return $this->getFirstName() . ' ' . strtoupper($this->getLastName());
    }

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

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

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

    /**
     * KataoMember::getFirstKataoUser()
     *
     * @return KataoUser
     */
    public function getFirstKataoUser()
    {
        $katao_users = $this->getKataoUsers();
        return array_shift($katao_users);
    }

    public function initAccountingCode()
    {
        if ('' == $this->getAccountingCode()) {
            $index = 0;
            $accounting_code = sprintf('411%s', strtoupper(substr($this->getLastName(), 0, 3)));
            $accounting_code_sol = sprintf('412%s', strtoupper(substr($this->getLastName(), 0, 3)));
            while (0 < KataoMemberPeer::countByAccountingCode($accounting_code)) {
                $index++;
                $accounting_code = sprintf('411%s%d', strtoupper(substr($this->getLastName(), 0, 2)), $index);
                $accounting_code_sol = sprintf('412%s%d', strtoupper(substr($this->getLastName(), 0, 2)), $index);
            }
            $this->setAccountingCode($accounting_code);
            $this->setAccountingCodeSol($accounting_code_sol);
        }
    }

    public function getNodeLink($with_link = false)
    {
        $result = '';
        if (null != $katao_node = $this->getKataoNode()) {
            if ($with_link) {
                $result = link_to($katao_node->getCity(), '@katao_node_show?id=' . $katao_node->getId());
            } else {
                $result = $katao_node->getCity();
            }
        }
        return $result;
    }

    public function getStatusStr()
    {
        return $this->getFirstKataoUser()->getStatusStr();
    }

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

        $begin = $this->getCreatedAt(null);

        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(KataoMemberNodePeer::CREATED_AT);
        $katao_member_nodes = $this->getKataoMemberNodesJoinKataoNode($criteria);

        if (0 < count($katao_member_nodes)) {
            foreach ($katao_member_nodes as/*(KataoMemberNode)*/ $katao_member_node) {
                $end = $katao_member_node->getCreatedAt(null);
                $return[$end] = array('begin' => CatalyzDate::formatShort($begin), 'end' => CatalyzDate::formatShort($end), 'node' => $katao_member_node->getKataoNode()->getCity());
                $begin = $end;
            }
        }
        $return[time()] = array('begin' => CatalyzDate::formatShort($begin), 'end' => '<i>noeud actuel</i>', 'node' => $this->getKataoNode()->getCity());

        ksort($return);

        return $return;
    }

    public function getCurrentAmountEuro()
    {
        return $this->getInitialAmountEuro() + $this->getCurrentAmount(KataoMemberDeposit::CURRENCY_EURO);
    }
    public function getCurrentAmountEuroStr()
    {
        return Utils::formatCurrencyEuro($this->getCurrentAmountEuro());
    }

    public function getCurrentAmountSol()
    {
        return $this->getInitialAmountSol() + $this->getCurrentAmount(KataoMemberDeposit::CURRENCY_SOL);
    }
    public function getCurrentAmountSolStr()
    {
        return Utils::formatCurrencySol($this->getCurrentAmountSol());
    }

    public function getCurrentAmountStr()
    {
        return sprintf('%s / %s', $this->getCurrentAmountEuroStr(), $this->getCurrentAmountSolStr());
    }

    public function getCurrentAmount($currency)
    {
        $return = 0;

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoMemberDepositPeer::KATAO_MEMBER_ID);
        $criteria->addAsColumn('sum_amount', sprintf('SUM(%s)', KataoMemberDepositPeer::AMOUNT));
        $criteria->add(KataoMemberDepositPeer::KATAO_MEMBER_ID, $this->getId());
        $criteria->add(KataoMemberDepositPeer::CURRENCY, $currency);
        $criteria->add(KataoMemberDepositPeer::PAYMENT_MODE, KataoMemberDeposit::PAYMENT_MODE_WITHDRAWAL, Criteria::NOT_EQUAL);
        $criteria->add(KataoMemberDepositPeer::STATUS, KataoMemberDeposit::STATUS_EXPIRED, Criteria::NOT_EQUAL);
        $criteria->addGroupByColumn(KataoMemberDepositPeer::KATAO_MEMBER_ID);

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

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoMemberDepositPeer::KATAO_MEMBER_ID);
        $criteria->addAsColumn('sum_amount', sprintf('SUM(%s)', KataoMemberDepositPeer::AMOUNT));
        $criteria->add(KataoMemberDepositPeer::KATAO_MEMBER_ID, $this->getId());
        $criteria->add(KataoMemberDepositPeer::CURRENCY, $currency);
        $criteria->add(KataoMemberDepositPeer::PAYMENT_MODE, KataoMemberDeposit::PAYMENT_MODE_WITHDRAWAL);
        $criteria->add(KataoMemberDepositPeer::STATUS, KataoMemberDeposit::STATUS_EXPIRED, Criteria::NOT_EQUAL);
        $criteria->addGroupByColumn(KataoMemberDepositPeer::KATAO_MEMBER_ID);

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

        if (KataoMemberDeposit::CURRENCY_SOL == $currency) {
            $return = (int)$return;

            $criteria = new Criteria();
            $criteria->addSelectColumn(KataoInvoicePeer::KATAO_MEMBER_ID);
            $criteria->addAsColumn('sum_products', sprintf('SUM(%s)', KataoInvoicePeer::SOL_AMOUNT));
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
            $criteria->add(KataoInvoicePeer::KATAO_MEMBER_ID, $this->getId());
            $criteria->addGroupByColumn(KataoInvoicePeer::KATAO_MEMBER_ID);

            $rs = KataoInvoicePeer::doSelectRS($criteria);
            while ($rs->next()) {
                $return -= $rs->getInt(2);
            }
        } else {
            $criteria = new Criteria();
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
            foreach ($this->getKataoInvoices($criteria) as/*(KataoInvoice)*/ $katao_invoice) {
                $return -= $katao_invoice->sumProducts();
            }

            $criteria = new Criteria();
            $criteria->addSelectColumn(KataoInvoicePeer::KATAO_MEMBER_ID);
            $criteria->addAsColumn('sum_sol', sprintf('SUM(%s)', KataoInvoicePeer::SOL_AMOUNT));
            $criteria->add(KataoInvoicePeer::STATUS, KataoInvoice::STATUS_SENT);
            $criteria->add(KataoInvoicePeer::KATAO_MEMBER_ID, $this->getId());
            $criteria->addGroupByColumn(KataoInvoicePeer::KATAO_MEMBER_ID);

            $rs = KataoInvoicePeer::doSelectRS($criteria);
            while ($rs->next()) {
                $return += $rs->getInt(2) / CONST_EURO_TO_SOL;
            }
        }

        return $return;
    }

    public function isDeletable()
    {
        // $katao_user = $this->getFirstKataoUser();
        // return (0 == $this->countKataoMemberDeposits()) && (0 == $katao_user->countKataoCarts()) && (0 == $this->countKataoInvoices()) && (0 == $katao_user->countKataoNodes()) && (0 == $this->countKataoMembersRelatedByKataoMemberId());
        return $this->countKataoMember() == 0 ? false : true;
    }

    public function countKataoMember()
    {
    //    if ($criteria === null) {
            $criteria = new Criteria();
    //    }elseif ($criteria instanceof Criteria) {
    //        $criteria = clone $criteria;
    //    }

        $criteria->add(KataoMemberPeer::ID, $this->getId());

//        return KataoMemberPeer::doCount($criteria, $distinct, $con);
        return KataoMemberPeer::doCount($criteria);
    }

    public function transferTo($to_id, $amount)
    {
        $time = time();
        $to_user = KataoMemberPeer::retrieveByPK($to_id);
        $commentaire = sprintf('Virement de %s vers %s d\'un montant de %s sols le %s', $this->getFullName(), $to_user->getFullName(), $amount, date('d/m/Y à H:i:s'));

        $con = Propel::getConnection();
        $con->begin();

        try {
            $depot = new KataoMemberDeposit();
            $depot->setKataoMemberId($to_user->getId());
            $depot->setAmount($amount);
            $depot->setComment($commentaire);
            $depot->setCurrency(KataoMemberDeposit::CURRENCY_SOL);
            $depot->setPaymentMode(KataoMemberDeposit::PAYMENT_MODE_TRANSFER_SOL);
            $depot->setStatus(KataoMemberDeposit::STATUS_VALIDATED);
            $depot->setValuedAt($time);
            $depot->save($con);

            $depot = new KataoMemberDeposit();
            $depot->setKataoMemberId($this->getId());
            $depot->setAmount(- 1 * $amount);
            $depot->setComment($commentaire);
            $depot->setCurrency(KataoMemberDeposit::CURRENCY_SOL);
            $depot->setPaymentMode(KataoMemberDeposit::PAYMENT_MODE_TRANSFER_SOL);
            $depot->setStatus(KataoMemberDeposit::STATUS_VALIDATED);
            $depot->setValuedAt($time);
            $depot->save($con);

            $con->commit();
        }
        catch (Exception $e) {
            $con->rollback();
            throw $e;
        }

        return $to_user;
    }
}