<?php

/**
 * kataoMember actions.
 *
 * @package www.katao.fr
 * @subpackage kataoMember
 * @author Your name here
 * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class kataoMemberActions extends wpActions {
    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoMemberPeer::KATAO_NODE_ID, KataoNodePeer::ID);
        $criteria->addJoin(KataoMemberPeer::ID, KataoUserPeer::KATAO_MEMBER_ID);

        $sort_method = $this->getCriteriaSortMethod();
        switch ($this->sort = $this->getRequestParameter('sort', 'name')) {
            case 'node':
                $criteria->$sort_method(KataoNodePeer::CITY);
                break;
            case 'referer':
                $criteria->$sort_method(KataoMemberPeer::IS_REFERER);
                break;
            case 'delegate':
                $criteria->$sort_method(KataoMemberPeer::IS_DELEGATE);
                break;
            case 'anonymous':
                $criteria->$sort_method(KataoMemberPeer::IS_ANONYMOUS);
                break;
            case 'amount':
                $criteria->$sort_method(KataoMemberPeer::CURRENT_AMOUNT);
                break;
            case 'status':
                $criteria->$sort_method(KataoUserPeer::STATUS);
                break;
            default:
                $criteria->$sort_method(KataoMemberPeer::LAST_NAME);
                $criteria->$sort_method(KataoMemberPeer::FIRST_NAME);
        }

        if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_member_filter_node')) {
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->filter_node);
        }
        if ('' != $this->filter_referer = $this->getUser()->getAttribute('katao_member_filter_referer')) {
            $criteria->add(KataoMemberPeer::IS_REFERER, (CONST_YES == $this->filter_referer)?true:false);
        }
        if ('' != $this->filter_delegate = $this->getUser()->getAttribute('katao_member_filter_delegate')) {
            $criteria->add(KataoMemberPeer::IS_DELEGATE, (CONST_YES == $this->filter_delegate)?true:false);
        }
        if ('' != $this->filter_anonymous = $this->getUser()->getAttribute('katao_member_filter_anonymous')) {
            $criteria->add(KataoMemberPeer::IS_ANONYMOUS, (CONST_YES == $this->filter_anonymous)?true:false);
        }
        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_member_filter_status')) {
            $criteria->add(KataoUserPeer::STATUS, $this->filter_status);
        }
        if ('' != $this->filter_member = $this->getUser()->getAttribute('katao_member_filter_member')) {
            $criteria->add(KataoMemberPeer::IS_MEMBER, (CONST_YES == $this->filter_member)?true:false);
        }

        if ('' != $this->search = $this->getUser()->getAttribute('katao_member_search')) {
            $search_like = sprintf('%%%s%%', $this->search);
            $criterion = $criteria->getNewCriterion(KataoMemberPeer::FIRST_NAME, $search_like, Criteria::LIKE);
            $criterion->addOr($criteria->getNewCriterion(KataoMemberPeer::LAST_NAME, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoMemberPeer::ACCOUNTING_CODE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::EMAIL, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ADDRESS1, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ADDRESS2, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ZIP, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::CITY, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::PHONE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::FAX, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::LOGIN, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoMemberPeer::CARD_NUMBER_SOL, $search_like, Criteria::LIKE));
            $criteria->addAnd($criterion);
        }

        $criteria->setDistinct();

        $pager = new sfPropelPager('KataoMember', sfConfig::get('app_pager'));
        $pager->setPeerMethod('doSelectJoinKataoNodeRelatedByKataoNodeId');
        $pager->setCriteria($criteria);
        $pager->setPage($this->getRequestParameter('page', 1));
        $pager->init();
        $this->pager = $pager;

        $this->katao_memberList = $pager->getResults();

        $this->is_just_delegate = $this->getUser()->isJustDelegate();

        $this->current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
//        $this->current_user_node_id = $this->getUser()->getAttribute('katao_node_instance')->getId();
    }

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_member_filter_node', $request->getParameter('filter_node'));
        $this->getUser()->setAttribute('katao_member_filter_referer', $request->getParameter('filter_referer'));
        $this->getUser()->setAttribute('katao_member_filter_delegate', $request->getParameter('filter_delegate'));
        $this->getUser()->setAttribute('katao_member_filter_anonymous', $request->getParameter('filter_anonymous'));
        $this->getUser()->setAttribute('katao_member_filter_status', $request->getParameter('filter_status'));
        $this->getUser()->setAttribute('katao_member_filter_member', $request->getParameter('filter_member'));
        return $this->redirect('kataoMember/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_member_filter_node', '');
        $this->getUser()->setAttribute('katao_member_filter_referer', '');
        $this->getUser()->setAttribute('katao_member_filter_delegate', '');
        $this->getUser()->setAttribute('katao_member_filter_anonymous', '');
        $this->getUser()->setAttribute('katao_member_filter_status', '');
        $this->getUser()->setAttribute('katao_member_filter_member', '');
        return $this->redirect('kataoMember/index');
    }

    public function executeSearch($request) {
        $this->getUser()->setAttribute('katao_member_search', $request->getParameter('search'));
        return $this->redirect('kataoMember/index');
    }

    public function executeSearchReset($request) {
        $this->getUser()->setAttribute('katao_member_search', '');
        return $this->redirect('kataoMember/index');
    }

    public function executeShow($request) {
        $this->katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_member, 'Adhérent #' . $request->getParameter('id') . ' inconnu.');

	    $katao_user =/*(KataoUser)*/ $this->katao_member->getFirstKataoUser();

		$this->history_euro = $katao_user->getHistoryEuro(true);
        $this->history_sol = $katao_user->getHistorySol(true);

    	// Historique des adhésions
        $this->memberid = $request->getParameter('id');
        $this->userid   = KataoUserPeer::retrieveByKataoMemberId($this->memberid)->getId();

    	$this->list_objet = KataoMemberAdhesionPeer::getAdhesionList($this->userid);
    }

    public function executeCreate() {
        $this->form = new KataoMemberForm();

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

    public function executeEdit($request) {
        $katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id'));

        if (!is_null($katao_member)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
            $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member->getKataoNodeId());
        }

        $this->form = new KataoMemberForm($katao_member);
    }

    public function executeUpdate($request) {
        $this->redirectWithErrorUnless($request->isMethod('post'));

        $katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id'));


        if (!is_null($katao_member)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
            $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member->getKataoNodeId());
        }

        $this->form = new KataoMemberForm($katao_member);

        $this->form->bind($request->getParameter('katao_member'));
		if ($this->form->isValid()) {
            $katao_member = $this->form->save();

            wpFlashMessages::addConfirmation('Adhérent "' . $katao_member->getFullName() . '" sauvé avec succès.');
            $this->redirect('kataoMember/index');
        }

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

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id')), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');

        $is_just_delegate = $this->getUser()->isJustDelegate();
        $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
        $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $katao_member->getKataoNodeId());

        $this->redirectWithErrorIf(!$katao_member->isDeletable());

        $katao_member->delete();

        wpFlashMessages::addConfirmation('Adhérent "' . $katao_member->getFullName() . '" supprimé avec succès.');
        $this->redirect('kataoMember/index');
    }

    public function executeDeleteMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_member')) {
            foreach (KataoMemberPeer::retrieveByPKs(array_keys(wpPersistenceManager::getSelectedItems('katao_member'))) as/*(KataoMember)*/ $katao_member) {
                if ($katao_member->isDeletable()) {
                    $katao_member->delete();
                }
            }

            wpPersistenceManager::cleanSelection('katao_member');
            wpFlashMessages::addConfirmation('Les adhérents sélectionnés ont été supprimés avec succès.');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un adhérent.');
        }

        $this->redirect('kataoMember/index');
    }

    public function executeChangeNextNodeMultiple(sfWebRequest $request) {
        $this->redirectWithErrorUnless($this->getUser()->isJustDelegate());

        if (!wpPersistenceManager::isEmpty('katao_member')) {
            if ($request->isMethod('post')) {
                $criteria_update = new Criteria();
                $criteria_update->add(KataoMemberPeer::NEXT_KATAO_NODE_ID, $request->getParameter('next_katao_node_id'));
                $criteria_where = new Criteria();
                $criteria_where->add(KataoMemberPeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_member')), Criteria::IN);
                BasePeer::doUpdate($criteria_where, $criteria_update, Propel::getConnection());

                wpPersistenceManager::cleanSelection('katao_member');
                wpFlashMessages::addConfirmation('Les adhérents sélectionnés ont été changés de noeud avec succès.');
                $this->redirect('kataoMember/index');
            }
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un adhérent.');
            $this->redirect('kataoMember/index');
        }
    }

    public function executeSendLogin(sfWebRequest $request) {
        $this->redirectWithErrorUnless($katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id')), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');
        $this->redirectWithErrorUnless($katao_user = $katao_member->getFirstKataoUser(), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');

        $email = $katao_user->getEmail();
        if ('' == $email) {
            wpFlashMessages::addError('L\'adhérent "' . $katao_member->getFullName() . '" n\'a pas d\'adresse email.');
        } else {
            try {
                $mailer = new wpMail();
                $mailer->send(new Swift_Message('Votre login et votre mot de passe', sprintf('%s,

Tu trouveras ci-joint ton login et ton mot de passe :

Login : %s
Mot de passe : %s
%s', $katao_member->getFirstName(), $katao_user->getLogin(), $katao_user->getPassword(), Utils::getKataoEmailFooter())), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));
                $mailer->disconnect();

                wpFlashMessages::addConfirmation('Les informations de connexion on été envoyées avec succès à l\'adhérent "' . $katao_member->getFullName() . '".');
            }
            catch (Exception $e) {
                $mailer->disconnect();
                wpFlashMessages::addError('L\'adhérent "' . $katao_member->getFullName() . '" n\'a pas d\'adresse email.');
            }
        }

        $this->redirect('kataoMember/index');
    }

    public function executeUpdateGmapCoordinates($request) {
        $this->redirectWithErrorUnless($this->katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id')), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');
        $this->redirectWithErrorUnless($this->katao_user = $this->katao_member->getFirstKataoUser(), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');

        if (!is_null($this->katao_member)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $current_user_node_id = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
            $this->redirectWithErrorIf($is_just_delegate && $current_user_node_id != $this->katao_member->getKataoNodeId());
        }

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

            wpFlashMessages::addConfirmation('L\'adhérent "' . $this->katao_member->getFullName() . '" a été positionné sur la carte avec succès.');
            $this->redirect('kataoMember/index');
        }
    }

    public function executeExportZyvon($request) {
        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoMemberPeer::LAST_NAME);
        $criteria->addSelectColumn(KataoMemberPeer::FIRST_NAME);
        $criteria->addSelectColumn(KataoUserPeer::EMAIL);
        $criteria->addJoin(KataoMemberPeer::ID, KataoUserPeer::KATAO_MEMBER_ID);
        if ($this->getUser()->isJustDelegate()) {
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
        }
        $criteria->add(KataoUserPeer::EMAIL, '', Criteria::NOT_EQUAL);
        $criteria->add(KataoUserPeer::EMAIL, null, Criteria::NOT_EQUAL);
        $criteria->add(KataoUserPeer::STATUS, KataoUser::STATUS_ACTIVE);
        $criteria->addAscendingOrderByColumn(KataoMemberPeer::LAST_NAME);
        $criteria->addAscendingOrderByColumn(KataoMemberPeer::FIRST_NAME);

        if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_member_filter_node')) {
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->filter_node);
        }
        if ('' != $this->filter_referer = $this->getUser()->getAttribute('katao_member_filter_referer')) {
            $criteria->add(KataoMemberPeer::IS_REFERER, (CONST_YES == $this->filter_referer)?true:false);
        }
        if ('' != $this->filter_delegate = $this->getUser()->getAttribute('katao_member_filter_delegate')) {
            $criteria->add(KataoMemberPeer::IS_DELEGATE, (CONST_YES == $this->filter_delegate)?true:false);
        }
        if ('' != $this->filter_anonymous = $this->getUser()->getAttribute('katao_member_filter_anonymous')) {
            $criteria->add(KataoMemberPeer::IS_ANONYMOUS, (CONST_YES == $this->filter_anonymous)?true:false);
        }
        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_member_filter_status')) {
            $criteria->add(KataoUserPeer::STATUS, $this->filter_status);
        }
        if ('' != $this->filter_member = $this->getUser()->getAttribute('katao_member_filter_member')) {
            $criteria->add(KataoUserPeer::IS_MEMBER, (CONST_YES == $this->filter_member)?true:false);
        }

        if ('' != $this->search = $this->getUser()->getAttribute('katao_member_search')) {
            $search_like = sprintf('%%%s%%', $this->search);
            $criterion = $criteria->getNewCriterion(KataoMemberPeer::FIRST_NAME, $search_like, Criteria::LIKE);
            $criterion->addOr($criteria->getNewCriterion(KataoMemberPeer::LAST_NAME, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoMemberPeer::ACCOUNTING_CODE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::EMAIL, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ADDRESS1, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ADDRESS2, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::ZIP, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::CITY, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::PHONE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::FAX, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoUserPeer::LOGIN, $search_like, Criteria::LIKE));
            $criteria->addAnd($criterion);
        }

        $criteria->setDistinct();

        $rs = KataoMemberPeer::doSelectRS($criteria);

        $content = array();
        while ($rs->next()) {
            $content[] = sprintf('"%s %s" <%s>', $rs->getString(1), $rs->getString(2), $rs->getString(3));
        }
        $content = implode(';', $content);

        $response = $this->getResponse();
        $response->setContentType('text/plain');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="Zyvon.txt"');
        $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 executePrintSolCard($request) {
        $criteria = new Criteria();
        $criteria->add(KataoUserPeer::KATAO_MEMBER_ID,$request->getParameter('id'));
        $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID,KataoMemberPeer::ID,Criteria::LEFT_JOIN);            $katao_users = KataoUserPeer::doSelectJoinAllExceptKataoSupplier($criteria);

		$katao_user = array();
        if ( count($katao_users)>0  ) {
            $katao_user = array_shift($katao_users);
        }

        $path = solViolette::generatePdf($katao_user,'kataoMember/pdf');
        $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 executeMailing($request){
		$this->form = new KataomemberMailingForm();

		if($this->form->isValid()){

		}
	}

	public function executeAdhesionDelete($request)
	{
		// gestion-des-adherentes/delete/userid/ahdesionid
		$this->forward404Unless($adhesion = KataoMemberAdhesionPeer::retrieveByPk($request->getParameter('id')));
		$this->userid = $request->getParameter('userid');

		$this->memberid = KataoUserPeer::retrieveMemberById($this->userid)->getKataoMemberId();

		$c = new Criteria();
		$c->add(KataoMemberAdhesionPeer::ID, $request->getParameter('id'));
		$c->add(KataoMemberAdhesionPeer::KATAO_USER_ID, $this->userid);

		$adhesion = KataoMemberAdhesionPeer::doSelectOne($c);
		$adhesion->delete();

		wpFlashMessages::addConfirmation('Adhésion du "' . $adhesion->getYear('Y') . '" supprimé avec succès.');

		$this->redirect('@katao_member_show?id='.$this->memberid);
		//$this->redirect('@katao_member_adhesion/id?='.$this->getParameter('id'));
	}

	public function executeAdhesionCreate($request){
		$this->form = new KataoMemberAdhesionForm();

		$this->userid = $request->getParameter('userid');
        $this->memberid = KataoUserPeer::retrieveMemberById($this->userid)->getId();

        $this->form->setDefault('katao_user_id', $this->userid);

		if($request->isMethod('post'))
		{
			$this->form->bind($request->getParameter('form_subscription'));

			if($this->form->isValid())
			{
				$save = $this->form->save();

            	wpFlashMessages::addConfirmation('Adhésion ajouté avec succès.');
				$this->redirect('@katao_member_show?id='.$this->memberid);
			}
		}

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

	public function executeAdhesionEdit($request){
		$adhesion = KataoMemberAdhesionPeer::retrieveByPk($request->getParameter('id'));

		$this->form = new KataoMemberAdhesionForm($adhesion);

		$this->id = $request->getParameter('id');
		$this->userid = $request->getParameter('userid');

		$this->memberid = KataoUserPeer::retrieveMemberById($this->userid)->getKataoMemberId();

		if($request->isMethod('post'))
		{
			$this->form->bind($request->getParameter('form_subscription'));

			if($this->form->isValid())
			{
				$adhesion = $this->form->save();

				wpFlashMessages::addConfirmation('Adhésion modifié avec succès.');
				$this->redirect('@katao_member_show?id='.$this->memberid);
			}
		}

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

	public function executeAdhesionShowAll($request){
		$con = Propel::getConnection();
		$sql = "SELECT count(*)as cnt,  DATE_FORMAT(year, '%Y') as year, SUM(amount) as amount FROM `katao_member_adhesion` group by  year";
		$this->adhesion_list = $con->executeQuery($sql);
	}

	public function executeSentRelance($request) {

		sfLoader::loadHelpers('Partial');

		$this->redirectWithErrorUnless($katao_member = KataoMemberPeer::retrieveByPk($request->getParameter('id')), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');
		$this->redirectWithErrorUnless($katao_user = $katao_member->getFirstKataoUser(), 'Adhérent #' . $request->getParameter('id') . ' inconnu.');

		$email = $katao_user->getEmail();
		if ('' == $email) {
			wpFlashMessages::addError('L\'adhérent "' . $katao_member->getFullName() . '" n\'a pas d\'adresse email.');
		} else {
			try {
				$mailer = new wpMail();
				$mailer->send(new Swift_Message('Relance', get_partial('katao/relanceEmail'), 'text/html' ), new Swift_Address($katao_user->getEmail(), $katao_user->getFullName()), sfConfig::get('app_mail_from'));
				$mailer->disconnect();

				wpFlashMessages::addConfirmation('Relance envoyée avec succès à l\'adhérent "' . $katao_member->getFullName() . '".');
			}
			catch (Exception $e) {
				$mailer->disconnect();
				wpFlashMessages::addError('L\'adhérent "' . $katao_member->getFullName() . '" n\'a pas d\'adresse email.');
			}
		}



		$this->redirect('@katao_member_show?id='.$request->getParameter('id'));
	}
}