<?php

/**
 * katao actions.
 *
 * @package www.katao.fr
 * @subpackage katao
 * @author Your name here
 * @version SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class kataoActions extends sfActions {
		public function preExecute() {
			$request = /*(sfContext)*/sfContext::getInstance()->getRequest();
			$user = /*(myUser)*/sfContext::getInstance()->getUser();

			if ($request->hasParameter('secureHash')) {
				$secureHash = $request->getParameter('secureHash');
				$tokens = explode('_', $secureHash);

				if (count($tokens) == 2 && $tokens[0] == md5(sfConfig::get('app_solviolette_secure_hash').date('dmY'))) {
					$c = new Criteria();
					$c->add(KataoUserPeer::EMAIL, "md5(katao_user.email) = \"".$tokens[1]."\"", Criteria::CUSTOM); // risk of SQL injection!!
					$user = /*(KataoUser)*/ KataoUserPeer::doSelectOne($c);

					$this->forward404Unless($user);

					if ($user != null) {
						$loginHandler = new kataoLoginHandler();
						$loginHandler->Login($user->getLogin(), $user->getPassword(), false);
					}
				}
			}
		}

    public function executeIndex($request) {
        $ContentTree = ContentTree::instance();
        $ContentTree->build();
        header('Location: ' . $ContentTree->getRoot()->getUrl());
        exit;
    }

    public function executeLogin($request) {
        $ContentTree = ContentTree::instance();
        $ContentTree->build();

        $loginHandler = Catalyz::getLoginHandler();
        if ($loginHandler->Login($request->getParameter('login'), $request->getParameter('password'), false)) {
            header('Location: ' . $ContentTree->getRoot()->getUrl());
        } else {
            header('Location: ' . $ContentTree->getRoot()->getUrl() . '?do=login&error=1');
        }
        exit;
    }

    public function executeChangeNode($request) {
        $this->getUser()->setActiveNode(KataoNodePeer::retrieveByPK($request->getParameter('node_id')));
        return $this->redirect($request->getReferer());
    }

    public function executeChangeDisplayOnlyActiveProducts($request) {
        $this->getUser()->setDisplayOnlyActiveProducts((int)$request->getParameter('display'));
        return $this->redirect($request->getReferer());
    }

    public function executeSuppliers($request) {
        $this->initializeCatalyzVariables();
        // $mailer = new wpMail();
        // $recipients = new Swift_RecipientList();
        // $recipients->addTo('katao+unsubscribe@googlegroups.com');
        // $mailer->send(new Swift_Message(), $recipients, 'jroussel-test2@waterproof.fr');
        // $mailer->disconnect();
    }

    public function executeSuppliersPopup($request) {
        $this->setLayout(null);
    }

    public function executeSupplierDetails($request) {
        $this->katao_supplier = KataoSupplierPeer::retrieveByUrlIdentifier($request->getParameter('supplier'));
        $this->forward404Unless($this->katao_supplier);
        $this->forward404If(!$this->katao_supplier->isVisible());

        $this->initializeCatalyzVariables();
    }

    public function executeSupplierProducts($request) {
        $this->katao_supplier = KataoSupplierPeer::retrieveByUrlIdentifier($request->getParameter('supplier'));
        $this->forward404Unless($this->katao_supplier);
        $this->forward404If(!$this->katao_supplier->isVisible());

        $this->initializeCatalyzVariables();
    }

    public function executeStore($request) {
        $this->katao_product_category = KataoProductCategoryPeer::retrieveByUrlIdentifier($request->getParameter('category'));
        $this->katao_product_family = KataoProductFamilyPeer::retrieveByUrlIdentifier($request->getParameter('family'));
        $this->katao_product = KataoProductPeer::retrieveByUrlIdentifier($request->getParameter('product'));

        if (!is_null($this->katao_product)) {
            $this->forward404If(!in_array($this->katao_product->getId(), $this->getUser()->getAvailableProducts()));
        }

        $this->initializeCatalyzVariables();
    }

    public function executeCart($request) {
        $this->initializeCatalyzVariables();
    }

    public function executeCartToPdf($request) {
        $katao_cart = $this->getUser()->getInstance()->getCart();

        $content = $katao_cart->generatePDF();

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="' . $katao_cart->getNumber() . '.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

    public function executeCartAddProduct($request) {
        $katao_product = KataoProductPeer::retrieveByUrlIdentifier($request->getParameter('product'));
        $this->forward404Unless($katao_product);
        $this->forward404If(!$katao_product->isCartable());

        if (0 < (int)$request->getParameter('quantity')) {
            $this->getUser()->getInstance()->addProductToCart($katao_product->getId(), $request->getParameter('quantity', 1));
        } else {
            $this->getUser()->getInstance()->removeProductFromCart($katao_product->getId());
        }
        $this->getUser()->getInstance()->unvalidateCart();
        return $this->redirect('@katao_cart');
    }

    public function executeCartRemoveProduct($request) {
        $katao_product = KataoProductPeer::retrieveByUrlIdentifier($request->getParameter('product'));
        $this->forward404Unless($katao_product);

        $this->getUser()->getInstance()->removeProductFromCart($katao_product->getId());
        $this->getUser()->getInstance()->unvalidateCart();
        return $this->redirect('@katao_cart');
    }

    public function executeCartValidate($request) {
        $katao_user = $this->getUser()->getInstance();
        if ($katao_user->getCart()->sumProducts() < $katao_user->getKataoMember()->getCurrentAmountEuro()) {
            $katao_user->validateCart();
        }

        return $this->redirect('@katao_cart');
    }

    public function executeNewsletter($request) {
        if ('' != $email = $request->getParameter('email')) {
            Utils::subscribeToMailingList($email);
        }
        return $this->redirect($request->getReferer());
    }

    public function executeProfile($request) {
				$this->katao_user =/*(KataoUser)*/ $this->getUser()->getInstance();
    		$this->forward404Unless($this->katao_user);

        if ($this->katao_user->isBothMemberAndSupplier()) {
            $this->form = new KataoMemberSupplierProfileForm($this->katao_user);
            $this->setTemplate('profileMemberSupplier');
        } elseif ($this->katao_user->isMember()) {
            $this->form = new KataoMemberProfileForm($this->katao_user->getKataoMember());
            $this->history_euro = $this->katao_user->getHistoryEuro();
            $this->history_sol = $this->katao_user->getHistorySol();
            $this->setTemplate('profileMember');
        } elseif ($this->katao_user->isSupplier()) {
            $this->form = new KataoSupplierProfileForm($this->katao_user->getKataoSupplier());
            $this->history_order = $this->katao_user->getHistoryOrder();
            $this->setTemplate('profileSupplier');
        }

        $this->initializeCatalyzVariables();
    }

    public function executeProfileUpdate($request) {
        $this->forward404Unless($request->isMethod('post'));

        $form_type = '';
        $this->katao_user =/*(KataoUser)*/ $this->getUser()->getInstance();
        if ($this->katao_user->isBothMemberAndSupplier()) {
            $this->form = new KataoMemberSupplierProfileForm($this->katao_user);
        } elseif ($this->katao_user->isMember()) {
            $this->form = new KataoMemberProfileForm($this->katao_user->getKataoMember());
            $form_type = 'katao_member';
        } elseif ($this->katao_user->isSupplier()) {
            $this->form = new KataoSupplierProfileForm($this->katao_user->getKataoSupplier());
            $form_type = 'katao_supplier';
        }

        $this->form->bind($request->getParameter($form_type));
        if ($this->form->isValid()) {
            $katao_member = $this->form->save();
            $this->getUser()->setInstance(KataoUserPeer::retrieveByPK($this->katao_user->getId()));

            $this->redirect($request->getReferer());
        }

        if ($this->katao_user->isBothMemberAndSupplier()) {
            $this->setTemplate('profileMemberSupplier');
        } elseif ($this->katao_user->isMember()) {
            $this->history_euro = $this->katao_user->getHistoryEuro();
            $this->history_sol = $this->katao_user->getHistorySol();
            $this->setTemplate('profileMember');
        } elseif ($this->katao_user->isSupplier()) {
            $this->history_order = $this->katao_user->getHistoryOrder();
            $this->setTemplate('profileSupplier');
        }

        $this->initializeCatalyzVariables();
    }

    public function executeSubscribe($request) {
        $this->initializeCatalyzVariables();

        $this->form = new KataoSubscribeForm();
        if ($request->isMethod('post') && '' == $request->getParameter('no_spam')) {
            $this->form->bind($request->getParameter('katao_member'));
            if ($this->form->isValid()) {
                $katao_member =/*(KataoMember)*/ $this->form->save();
                $katao_user = $katao_member->getFirstKataoUser();
                $katao_user_delegate = $katao_member->getKataoNode()->getKataoUser();
                $katao_member_delegate = $katao_user_delegate->getKataoMember();

                try {
                    $mailer = new wpMail();
                    $mailer->send(new Swift_Message('Confirmation d\'inscription', sprintf('%s,

Suite à votre demande, nous vous confirmons votre inscription à la prochaine réunion d\'accueil de Katato.
Nous vous previendrons du lieu, de la date et de l\'heure de cette réunion dans un prochain courriel.

En attendant, n\'hésitez pas à contacter le délégué le plus proche de chez vous:

%s %s
%s
%s / %s
%s', $katao_member->getFirstName(), $katao_member_delegate->getFirstName(), $katao_member_delegate->getLastName(), $katao_user_delegate->getFullAdress(), $katao_user_delegate->getPhone(), $katao_user_delegate->getEmail(), Utils::getKataoEmailFooter())), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));
                    $mailer->disconnect();
                }
                catch (Exception $e) {
                    $mailer->disconnect();
                    $this->getRequest()->setError('email', 'Adresse email invalide');
                    $return = false;
                }

                if ('' != $katao_user->getEmail()) {
                    Utils::subscribeToMailingList($katao_user->getEmail());
                }

                $this->setTemplate('subscribeConfirmation');
            }
        }
    }

    public function executeForgotPassword($request) {
        $this->initializeCatalyzVariables();
    }

    public function validateForgotPasswordUpdate() {
        $return = true;

        $email = $this->getRequestParameter('email');
        if ('' == $email) {
            $this->getRequest()->setError('email', 'Merci de saisir une adresse email');
            $return = false;
        } elseif (null == $katao_user = KataoUserPeer::retrieveByEmail($email)) {
            $this->getRequest()->setError('email', 'Adresse email inconnue');
            $return = false;
        } else {
            try {
                $mailer = new wpMail();
                $mailer->send(new Swift_Message('Votre login et votre mot de passe', sprintf('%s,

Suite à ta demande, tu trouveras ci-joint ton login et ton mot de passe :

Login : %s
Mot de passe : %s
%s', $katao_user->getFullName(), $katao_user->getLogin(), $katao_user->getPassword(), Utils::getKataoEmailFooter())), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));
                $mailer->disconnect();
            }
            catch (Exception $e) {
                $mailer->disconnect();
                $this->getRequest()->setError('email', 'Adresse email invalide');
                $return = false;
            }
        }

        return $return;
    }

    public function handleErrorForgotPasswordUpdate() {
        return $this->forward('katao', 'forgotPassword');
    }

    public function executeForgotPasswordUpdate($request) {
        $this->initializeCatalyzVariables();
        $this->setTemplate('forgotPasswordConfirmation');
    }

    protected function initializeCatalyzVariables() {
        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTreeNode = $this->ContentTree->getRoot();
        $this->node = $this->ContentTreeNode->getNode();
        $this->page = $this->ContentTreeNode->getPage();
    }

    public function executeSearch($request) {
        $this->search = $request->getParameter('search');

        $this->initializeCatalyzVariables();
    }

    public function executeNotFound($request) {
        $this->getResponse()->setHttpHeader('HTTP/1.1', '404 Not Found');

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();

        $this->ContentTree->initializeCurrentNodeByPath(str_replace(sprintf('%s/%s', sfConfig::get('app_site_url'), $this->getUser()->getCulture()), '', $request->getReferer()));
        $this->node = $this->ContentTree->getCurrentNode();
        if (is_null($this->node)) {
            $this->ContentTree->initializeCurrentNodeByPath('');
            $this->node = $this->ContentTree->getCurrentNode();
        }

        $handle = fopen(sfConfig::get('sf_log_dir') . '/404-error.log', 'a+');
        if ($handle) {
            fwrite($handle, sprintf('%s[%s] Page <%s%s> not found. Coming from <%s>', "\n", date('Y-m-d H:i:s'), sfConfig::get('app_site_url'), !empty($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'', $request->getReferer()));
            fclose($handle);
        }
    }

    public function executeExportMemberInvoiceToPdf($request) {
        $katao_user =/*(KataoUser)*/ $this->getUser()->getInstance();
        $this->forward404If(!$katao_user->isMember());

        $this->forward404Unless($katao_invoice = KataoInvoicePeer::retrieveByPk($request->getParameter('id')), 'Facture #' . $request->getParameter('id') . ' inconnue.');
        $this->forward404If($katao_invoice->getKataoMemberId() != $katao_user->getKataoMemberId());

        $content = $katao_invoice->generatePDF();

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="' . $katao_invoice->getNumber() . '.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

    public function executeExportSupplierOrderToPdf($request) {
        $katao_user =/*(KataoUser)*/ $this->getUser()->getInstance();
        $this->forward404If(!$katao_user->isSupplier());

        $this->forward404Unless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
        $this->forward404If($katao_order->getKataoSupplierId() != $katao_user->getKataoSupplierId());

        $content = $katao_order->generatePDF();

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="' . $katao_order->getNumber() . '.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

    public function executeProfileGMap($request) {
        $this->katao_user =/*(KataoUser)*/ $this->getUser()->getInstance();
        if ($this->katao_user->isBothMemberAndSupplier()) {
        } elseif ($this->katao_user->isMember()) {
            $this->katao_member_or_supplier = $this->katao_user;
        } elseif ($this->katao_user->isSupplier()) {
            $this->katao_member_or_supplier = $this->katao_user->getKataoSupplier();
        }

        if ($request->isMethod('post')) {
            $this->katao_member_or_supplier->setGmapLng($request->getParameter('gmap_lng'));
            $this->katao_member_or_supplier->setGmapLat($request->getParameter('gmap_lat'));
            $this->katao_member_or_supplier->save();

            return $this->redirect('@katao_profile');
        }

        $this->initializeCatalyzVariables();
    }

    public function executeAdjustments($request) {
        $this->initializeCatalyzVariables();

        $this->default_category_id = $request->getParameter('category_id');
        $this->default_supplier_id = $request->getParameter('supplier_id');
    }

    public function executeSubscribeSolViolette($request) {
        if ('sol-violette' != sfConfig::get('sf_environment')) {
            $this->redirect('@katao_subscribe');
        }

        $this->initializeCatalyzVariables();

        $this->form = new SolVioletteSubscribeForm();
        if ($request->isMethod('post') && '' == $request->getParameter('no_spam')) {
            $this->form->bind($request->getParameter('katao_member'));
            if ($this->form->isValid()) {
                $values = $this->form->getValues();
                sfContext::getInstance()->getUser()->setAttribute('adhesion_user_values', $values);

                $katao_member =/*(KataoMember)*/ $this->form->save();
                $this->invoiceId = $katao_member->getId();

                /*

              //  $katao_user = $katao_member->getFirstKataoUser();
//                $katao_user_delegate = $katao_member->getKataoNode()->getKataoUser();
//                $katao_member_delegate = $katao_user_delegate->getKataoMember();

                //try {
//                    $mailer = new wpMail();
//                    $mailer->send(new Swift_Message('Confirmation d\'inscription', sprintf('%s,
//
//Suite à votre demande, nous vous confirmons votre inscription à la prochaine réunion d\'accueil de Katato.
//Nous vous previendrons du lieu, de la date et de l\'heure de cette réunion dans un prochain courriel.
//
//En attendant, n\'hésitez pas à contacter le délégué le plus proche de chez vous:
//
//%s %s
//%s
//%s / %s
//%s', $katao_member->getFirstName(), $katao_member_delegate->getFirstName(), $katao_member_delegate->getLastName(), $katao_user_delegate->getFullAdress(), $katao_user_delegate->getPhone(), $katao_user_delegate->getEmail(), Utils::getKataoEmailFooter())), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));
//                    $mailer->disconnect();
//                }
//                catch (Exception $e) {
//                    $mailer->disconnect();
//                    $this->getRequest()->setError('email', 'Adresse email invalide');
//                    $return = false;
//                }

                //if ('' != $katao_user->getEmail()) {
//                    Utils::subscribeToMailingList($katao_user->getEmail());
//                }
*/

                if (!isset($values['user_payment_mode']) || (!empty($values['user_payment_mode']) && in_array($values['user_payment_mode'], array(KataoMemberDeposit::PAYMENT_MODE_CHECK, KataoMemberDeposit::PAYMENT_MODE_CASH))) || ('exonere' == $values['user_adhesion'] && empty($values['user_amount']))) {
                    // cheque, especes ou rien a payer -> message general
                    $this->setTemplate('solSubscribeOtherPayment') ;
                } else {
                    if ($values['user_adhesion'] != 'todo') {
                        if (!empty($values['user_amount'])) {
                            // mettre en session le montant
                            $this->montant = $values['user_amount'];
                            sfContext::getInstance()->getUser()->setAttribute('sol_violette_amount', $values['user_amount']);
                            sfContext::getInstance()->getUser()->setAttribute('sol_violette_adhesion', true);
                            $this->setTemplate('saas') ;
                        } else {
                            $this->setTemplate('sass') ;
                        }
                    } else {
                        if (!empty($values['user_amount'])) {
                            // mettre en session le montant
                            $this->montant = $values['user_amount'];
                            sfContext::getInstance()->getUser()->setAttribute('sol_violette_amount', $values['user_amount']);
                            sfContext::getInstance()->getUser()->setAttribute('sol_violette_adhesion', false);
                            $this->setTemplate('aas') ;
                        } else {
                            $this->setTemplate('ass') ;
                        }
                    }
                }
            }
        }
    }

    public function executeSubscribeSolVioletteCancel($request) {
        $this->initializeCatalyzVariables();
    }

    public function executeSubscribeSolVioletteThanks($request) {
        $this->initializeCatalyzVariables();
    }

    public function executeSubscribeSolVioletteConfirm($request) {
        file_put_contents(sfConfig::get('sf_web_dir') . '/paypal_' . time() . '.log', print_r($_REQUEST, true));

        session_id($_REQUEST['custom']);

        $this->initializeCatalyzVariables();
        $katao_member =/*(KataoMember)*/ KataoMemberPeer::retrieveByPK($_REQUEST['invoice']);
        switch ($_REQUEST['item_number']) {
            case KataoUser::SUBSCRIBE_WITHOUT_SOLS:
                // rien à faire - ne devrait pas passer ici
                break;
            case KataoUser::SUBSCRIBE_WITH_SOLS:
                $depot = KataoMemberDepositPeer::addPaypalDepot($katao_member->getId(), ceil(1.05 * $_REQUEST['mc_gross']), 'Conversion d\'euros en sols');
                break;
            case KataoUser::ADD_SOLS:
                $depot = KataoMemberDepositPeer::addPaypalDepot($katao_member->getId(), ceil(1.05 * $_REQUEST['mc_gross']), 'Conversion d\'euros en sols');
                break;
            case KataoUser::SUBSCRIBE_ADHESION_WITH_SOLS:
                $katao_member->setIsMember(true);
                $katao_member->save();

                $depot = KataoMemberDepositPeer::addPaypalDepot($katao_member->getId(), sfConfig::get('app_solviolette_adhesion_amount'), 'Adhésion SOL');
                $depot = KataoMemberDepositPeer::addPaypalDepot($katao_member->getId(), ceil(1.05 * ($_REQUEST['mc_gross'] - sfConfig::get('app_solviolette_adhesion_amount'))), 'Conversion d\'euros en sols');
                break;
            case KataoUser::SUBSCRIBE_ADHESION_WITHOUT_SOLS:
                $katao_member->setIsMember(true);
                $katao_member->save();

                $depot = KataoMemberDepositPeer::addPaypalDepot($katao_member->getId(), sfConfig::get('app_solviolette_adhesion_amount'), 'Adhésion SOL');
                break;
            default:
                throw new Exception('Unknown payment operation type: ' . $_REQUEST['item_number']);;
        } // switch
    }

    public function executeSolVioletteCharger($request) {
        $this->montant = $valeur_de_retour['montant'];
        $this->montant = 50;

        $this->initializeCatalyzVariables();
        $katao_user =/*(KataoUser)*/ sfContext::getInstance()->getUser()->getAttribute('katao_user_instance');

        $depot = KataoMemberDepositPeer::addPaypalDepot($katao_user->getKataoMemberId(), $this->montant, 'L\'utilisateur charge son compte');
    }

    public function executeAdhesionToPdf($request) {
        $values = sfContext::getInstance()->getUser()->getAttribute('adhesion_user_values');

        $path = solViolette::generatePdf($values);
        $content = file_get_contents($path);

        $response = $this->getResponse();
        $response->setContentType('application/pdf');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="DemandeCarteSol.pdf"');
        $response->setHttpHeader('Content-Length', strlen($content));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent($content);
        return sfView::NONE;
    }

		public function executeSolVioletteTransfer(sfWebRequest $request){
			$this->initializeCatalyzVariables();

			$this->results = FALSE;
			$this->form = new SolVioletteTransferForm();
			if ($request->isMethod('post')) {
				$this->form->bind($request->getParameter('transfer'));
				if ($this->form->isValid()) {
					$query = $this->form->getValue('search');

					$tokens = array();
					$query_nb = FALSE;
					if (preg_match_all("/[0-9]/",$query,$tokens)) {
						$query_nb = $tokens[0];
					}

					//region not suppliers
					$criteria = new Criteria();
					$criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID, Criteria::LEFT_JOIN);
					$criteria->add(KataoUserPeer::KATAO_SUPPLIER_ID, NULL, Criteria::ISNULL);


					if ($query_nb) {
						$criterion1 = $criteria->getNewCriterion(KataoMemberPeer::LAST_NAME, '%'.$query.'%', Criteria::LIKE);
						$criterion2 = $criteria->getNewCriterion(KataoUserPeer::PHONE, '%'.implode('%', $query_nb).'%', Criteria::LIKE);
						$criterion1->addOr($criterion2);

						$criterion3 = $criteria->getNewCriterion(KataoMemberPeer::CARD_NUMBER_SOL, implode('', $query_nb), Criteria::EQUAL);
						$criterion2->addOr($criterion3);
						$criteria->add($criterion1);
					}else{
						$criteria->add(KataoMemberPeer::LAST_NAME, '%'.$query.'%', Criteria::LIKE);
					}

					$criteria->setDistinct();
					$not_suppliers =  KataoMemberPeer::doSelect($criteria);
					//endregion

					//region supplier
					$criteria = new Criteria();
					$criteria->addJoin(KataoMemberPeer::ID, KataoSupplierPeer::MEMBER_ID, Criteria::LEFT_JOIN);
					$criteria->add(KataoMemberPeer::ID, NULL, Criteria::ISNOTNULL);
					//					$criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID, Criteria::INNER_JOIN);

					$criterion1 = $criteria->getNewCriterion(KataoMemberPeer::LAST_NAME, '%'.$query.'%', Criteria::LIKE);
					$criterion2 = $criteria->getNewCriterion(KataoSupplierPeer::NAME, '%'.$query.'%', Criteria::LIKE);
					$criterion1->addOr($criterion2);

					if ($query_nb) {
						$criterion3 = $criteria->getNewCriterion(KataoSupplierPeer::PHONE, '%'.implode('%', $query_nb).'%', Criteria::LIKE);
						$criterion2->addOr($criterion3);

						$criterion4 = $criteria->getNewCriterion(KataoMemberPeer::CARD_NUMBER_SOL, implode('', $query_nb), Criteria::EQUAL);
						$criterion3->addOr($criterion4);
					}

					$criteria->add($criterion1);

					$criteria->setDistinct();
					$suppliers =  KataoMemberPeer::doSelect($criteria);
					//endregion

					$this->results = array();
					foreach (array($suppliers, $not_suppliers) as $tab){
						foreach ($tab as /*(KataoMember)*/$member){
							$this->results[$member->getFullName()] = $member;
						}
					}
					//endregion

					if (!empty($this->results)) {
						if (count($this->results) == 1) {
							$user = /*(KataoMember)*/array_shift($this->results);
							$this->getRequest()->setParameter('id', $user->getId());
							$this->forward('katao', 'solVioletteTransferStep1');
						}
					}
				}
			}

			return sfView::SUCCESS;
		}

		public function executeSolVioletteTransferStep1($request){
			$this->initializeCatalyzVariables();

			$this->KataoMember = KataoMemberPeer::retrieveByPK($request->getParameter('id'));

			$this->user = /*(KataoUser)*/sfContext::getInstance()->getUser()->getAttribute('katao_user_instance');
			$user_member = $this->user->getKataoMember();

			$current_solde = $user_member->getCurrentAmountSol();

			$this->form = new SolVioletteTransferStep1Form(array('id' => $this->KataoMember->getId()), array('current_solde' => $current_solde));

			if ($request->isMethod('post') && $request->getParameter('form_submit') == 'Effectuer le virement') {
				$this->form->bind($request->getParameter('transfer'));
				if ($this->form->isValid()) {
					$this->amount = $this->form->getValue('amount');
					$this->confirmForm = new SolVioletteTransferStep2Form(array('id' => $this->KataoMember->getId(), 'amount' => $this->amount));
					$this->setTemplate('solVioletteTransferStep2');
				}
			}

			return sfView::SUCCESS;
		}

		public function executeSolVioletteTransferConfirm(sfWebRequest $request){
			$this->initializeCatalyzVariables();

			$this->form = new SolVioletteTransferStep2Form();
			$this->form->bind($request->getParameter('confirm'));
			if ($this->form->isValid()) {
				$message = $this->form->getValue('message');

				$this->amount = $this->form->getValue('amount');
				$this->to_user = sfContext::getInstance()->getUser()->getAttribute('katao_user_instance')->getKataoMember()->transferTo($this->form->getValue('id'), $this->amount);

				if (trim($message) != '') {
					$this->sendEmail($this->to_user, $message, $this->amount);
				}
			}

			return sfView::SUCCESS;
		}

		private function sendEmail(KataoMember $to_user_member, $message, $amount){
			$from_user = /*(KataoUser)*/sfContext::getInstance()->getUser()->getAttribute('katao_user_instance');
			$from_user_member = /*(KataoMember)*/ $from_user->getKataoMember();

			$criteria = new criteria();
			$criteria->add(KataoUserPeer::KATAO_MEMBER_ID, $to_user_member->getId());
			$to_user = KataoUserPeer::doSelectOne($criteria);

			$email_content = $this->getPartial('katao/solVioletteTransferEmail', array('to_user' => $to_user, 'from_user' => $from_user, 'amount' => $amount, 'commentaire' => $message));

			try
			{
				$mailer = new Swift(new Swift_Connection_NativeMail());
				$swift_message = new Swift_Message('Un dépot a été réalisé', $email_content, 'text/html');

				$recipients = new Swift_RecipientList();
				$recipients->add($to_user->getEmail(), $to_user_member->getFullName());
				$recipients->addCc($from_user->getEmail(), $from_user_member->getFullName());
				$swift_message->setReplyTo($from_user->getEmail(), $from_user_member->getFullName());

				$mailer->send($swift_message, $recipients , sfConfig::get('app_mail_from'));
				$mailer->disconnect();
			}
			catch (Exception $e)
			{
				$mailer->disconnect();
			 	return FALSE;
			}

			return TRUE;
		}
}