<?php

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

        $sf_user = $this->getUser();
        if ($sf_user->isJustDelegate()) {
            $criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
            $criteria->add(KataoSupplierPeer::IS_GLOBAL, true, Criteria::NOT_EQUAL);
            $criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $sf_user->getInstance()->getKataoMember()->getKataoNodeId());
        } elseif ($sf_user->isJustReferer()) {
            $criteria->add(KataoSupplierPeer::REFERER_ID, $sf_user->getInstance()->getKataoMemberId());
        }

        $sort_method = $this->getCriteriaSortMethod();
        switch ($this->sort = $this->getRequestParameter('sort', 'name')) {
            case 'phone':
                $criteria->$sort_method(KataoSupplierPeer::PHONE);
                break;
            case 'referer':
                $criteria->$sort_method(KataoMemberPeer::LAST_NAME);
                $criteria->$sort_method(KataoMemberPeer::FIRST_NAME);
                break;
            case 'type':
                $criteria->$sort_method(KataoSupplierPeer::IS_GLOBAL);
                break;
            case 'status':
                $criteria->$sort_method(KataoUserPeer::STATUS);
                break;
            default:
                $criteria->$sort_method(KataoSupplierPeer::NAME);
        }

        if ('' != $this->filter_referer = $this->getUser()->getAttribute('katao_supplier_filter_referer')) {
            $criteria->add(KataoSupplierPeer::REFERER_ID, $this->filter_referer);
        }
        if ('' != $this->filter_is_global = $this->getUser()->getAttribute('katao_supplier_filter_is_global')) {
            $criteria->add(KataoSupplierPeer::IS_GLOBAL, (CONST_YES == $this->filter_is_global)?true:false);
        }
        if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_supplier_filter_node')) {
            $criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
            $criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $this->filter_node);
        }
        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_supplier_filter_status')) {
            $criteria->add(KataoUserPeer::STATUS, $this->filter_status);
        }

        if ('' != $this->search = $this->getUser()->getAttribute('katao_supplier_search')) {
            $search_like = sprintf('%%%s%%', $this->search);
            $criterion = $criteria->getNewCriterion(KataoSupplierPeer::NAME, $search_like, Criteria::LIKE);
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::PRESENTATION, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::EMAIL, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ADDRESS1, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ADDRESS2, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ZIP, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::CITY, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::PHONE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::FAX, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ACCOUNTING_CODE, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::SIRET_NUMBER, $search_like, Criteria::LIKE));
            $criteria->addAnd($criterion);
        }

        $criteria->setDistinct();

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

        $this->katao_supplierList = $pager->getResults();
    }

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_supplier_filter_referer', $request->getParameter('filter_referer'));
        $this->getUser()->setAttribute('katao_supplier_filter_is_global', $request->getParameter('filter_is_global'));
        $this->getUser()->setAttribute('katao_supplier_filter_node', $request->getParameter('filter_node'));
        $this->getUser()->setAttribute('katao_supplier_filter_status', $request->getParameter('filter_status'));
        return $this->redirect('kataoSupplier/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_supplier_filter_referer', '');
        $this->getUser()->setAttribute('katao_supplier_filter_is_global', '');
        $this->getUser()->setAttribute('katao_supplier_filter_node', '');
        $this->getUser()->setAttribute('katao_supplier_filter_status', '');
        return $this->redirect('kataoSupplier/index');
    }

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

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

    public function executeShow($request) {
        $this->katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_supplier, 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');
    }

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

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

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

        if (!is_null($katao_supplier)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $is_just_referer = $this->getUser()->isJustReferer();
            $this->redirectWithErrorIf($is_just_delegate && !$katao_supplier->isLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()));
            $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_supplier->getRefererId());
        }

        $this->form = new KataoSupplierForm($katao_supplier);
    }

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

        $sf_user = $this->getUser();
        if ($sf_user->isJustDelegate()) {
            if (null != $katao_supplier = KataoSupplierPeer::retrieveBySiretNumber($request->getParameter('katao_supplier[siret_number]'))) {
                if (!$katao_supplier->getIsGlobal()) {
                    $katao_user = $sf_user->getInstance();
                    $katao_member = $katao_user->getKataoMember();

                    if (KataoSupplierNodePeer::createIfNotExists($katao_supplier->getId(), $katao_member->getKataoNodeId())) {
                        wpFlashMessages::addInformation('Le fournisseur local correspondant à ce n° SIRET existait déjà. Votre noeud vient d\'y être rattaché.');
                    } else {
                        wpFlashMessages::addInformation('Le fournisseur local correspondant à ce n° SIRET existait déjà et votre noeud y était déjà rattaché.');
                    }
                    $this->redirect('kataoSupplier/index');
                }
            }
        }

        $katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id'));

        if (!is_null($katao_supplier)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $is_just_referer = $this->getUser()->isJustReferer();
            $this->redirectWithErrorIf($is_just_delegate && !$katao_supplier->isLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()));
            $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_supplier->getRefererId());
        }

        $this->form = new KataoSupplierForm($katao_supplier);

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

            wpFlashMessages::addConfirmation('Fournisseur "' . $katao_supplier->getName() . '" sauvé avec succès.');
            $this->redirect('kataoSupplier/index');
        }

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

    public function executeEditPresentation($request) {
        $this->katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_supplier, 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');

        $is_just_delegate = $this->getUser()->isJustDelegate();
        $is_just_referer = $this->getUser()->isJustReferer();
        $this->redirectWithErrorIf($is_just_delegate && !$this->katao_supplier->isLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()));
        $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $this->katao_supplier->getRefererId());

        if ($request->isMethod('post')) {
            $this->katao_supplier->setPresentation($request->getParameter('presentation'));
            $this->katao_supplier->save();

            wpFlashMessages::addConfirmation('Présentation du fournisseur "' . $this->katao_supplier->getName() . '" sauvée avec succès.');
            $this->redirect('kataoSupplier/index');
        }
    }

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id')), 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');

        $is_just_delegate = $this->getUser()->isJustDelegate();
        $is_just_referer = $this->getUser()->isJustReferer();
        $this->redirectWithErrorIf($is_just_delegate && !$katao_supplier->isLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()));
        $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_supplier->getRefererId());

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

        $katao_supplier->delete();

        wpFlashMessages::addConfirmation('Fournisseur "' . $katao_supplier->getName() . '" supprimé avec succès.');
        $this->redirect('kataoSupplier/index');
    }

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

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

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

    public function executeSendLogin(sfWebRequest $request) {
        $this->redirectWithErrorUnless($katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id')), 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');
        $this->redirectWithErrorUnless($katao_user = $katao_supplier->getFirstKataoUser(), 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');

        $email = $katao_user->getEmail();
        if ('' == $email) {
            wpFlashMessages::addError('Le fournisseur "' . $katao_supplier->getName() . '" n\'a pas d\'adresse email.');
        } else {
            try {
                $mailer = new wpMail();
                $mailer->send(new Swift_Message('Votre login et votre mot de passe', sprintf('Madame, Monsieur

Vous trouverez ci-joint votre login et votre mot de passe :

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

                wpFlashMessages::addConfirmation('Les informations de connexion on été envoyées avec succès au fournisseur "' . $katao_supplier->getName() . '".');
            }
            catch (Exception $e) {
                $mailer->disconnect();
                wpFlashMessages::addError('Le fournisseur "' . $katao_supplier->getName() . '" n\'a pas d\'adresse email.');
            }
        }

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

    public function executeUpdateGmapCoordinates($request) {
        $this->redirectWithErrorUnless($this->katao_supplier = KataoSupplierPeer::retrieveByPk($request->getParameter('id')), 'Fournisseur #' . $request->getParameter('id') . ' inconnu.');

        if (!is_null($this->katao_supplier)) {
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $is_just_referer = $this->getUser()->isJustReferer();
            $this->redirectWithErrorIf($is_just_delegate && !$this->katao_supplier->isLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()));
            $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $this->katao_supplier->getRefererId());
        }

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

            wpFlashMessages::addConfirmation('Le fournisseur "' . $this->katao_supplier->getName() . '" a été positionné sur la carte avec succès.');
            $this->redirect('kataoSupplier/index');
        }
    }

    public function executeCheckSiretNumberAvailability($request) {
        $return = '';
        if (null != $katao_supplier = KataoSupplierPeer::retrieveBySiretNumber($request->getParameter('siret_number'), $request->getParameter('id'))) {
            if ($katao_supplier->getIsGlobal()) {
                $return = 'national';
            } else {
                $return = 'local';
            }
        }
        return $this->renderText($return);
    }

    public function executeAddLocalSupplierToNode($request) {
        if (null != $katao_supplier = KataoSupplierPeer::retrieveBySiretNumber($request->getParameter('siret_number'))) {
            if (!$katao_supplier->getIsGlobal()) {
                $katao_user = $this->getUser()->getInstance();
                $katao_member = $katao_user->getKataoMember();

                if (KataoSupplierNodePeer::createIfNotExists($katao_supplier->getId(), $katao_member->getKataoNodeId())) {
                    wpFlashMessages::addInformation('Le fournisseur local correspondant à ce n° SIRET existait déjà. Votre noeud vient d\'y être rattaché.');
                } else {
                    wpFlashMessages::addInformation('Le fournisseur local correspondant à ce n° SIRET existait déjà et votre noeud y était déjà rattaché.');
                }
            }
        }
        return true;
    }

    public function executeExportZyvon($request) {
        $sf_user = $this->getUser();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoSupplierPeer::NAME);
        $criteria->addSelectColumn(KataoSupplierPeer::EMAIL);
        $criteria->addJoin(KataoSupplierPeer::ID, KataoUserPeer::KATAO_SUPPLIER_ID);
        if ($sf_user->isJustDelegate()) {
            $criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
            $criteria->add(KataoSupplierPeer::IS_GLOBAL, true, Criteria::NOT_EQUAL);
            $criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $sf_user->getInstance()->getKataoMember()->getKataoNodeId());
        } elseif ($sf_user->isJustReferer()) {
            $criteria->add(KataoSupplierPeer::REFERER_ID, $sf_user->getInstance()->getKataoMemberId());
        }
        $criteria->add(KataoSupplierPeer::EMAIL, '', Criteria::NOT_EQUAL);
        $criteria->add(KataoSupplierPeer::EMAIL, null, Criteria::NOT_EQUAL);
        $criteria->add(KataoUserPeer::STATUS, KataoUser::STATUS_ACTIVE);
        $criteria->addAscendingOrderByColumn(KataoSupplierPeer::NAME);

    	if ('' != $this->filter_referer = $this->getUser()->getAttribute('katao_supplier_filter_referer')) {
    		$criteria->add(KataoSupplierPeer::REFERER_ID, $this->filter_referer);
    	}
    	if ('' != $this->filter_is_global = $this->getUser()->getAttribute('katao_supplier_filter_is_global')) {
    		$criteria->add(KataoSupplierPeer::IS_GLOBAL, (CONST_YES == $this->filter_is_global)?true:false);
    	}
    	if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_supplier_filter_node')) {
    		$criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
    		$criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $this->filter_node);
    	}
    	if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_supplier_filter_status')) {
    		$criteria->add(KataoSupplierPeer::STATUS, $this->filter_status);
    	}

    	if ('' != $this->search = $this->getUser()->getAttribute('katao_supplier_search')) {
    		$search_like = sprintf('%%%s%%', $this->search);
    		$criterion = $criteria->getNewCriterion(KataoSupplierPeer::NAME, $search_like, Criteria::LIKE);
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::PRESENTATION, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::EMAIL, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ADDRESS1, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ADDRESS2, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ZIP, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::CITY, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::PHONE, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::FAX, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::ACCOUNTING_CODE, $search_like, Criteria::LIKE));
    		$criterion->addOr($criteria->getNewCriterion(KataoSupplierPeer::SIRET_NUMBER, $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;
    }
}