<?php

/**
 * kataoProduct actions.
 *
 * @package www.katao.fr
 * @subpackage kataoProduct
 * @author Your name here
 * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class kataoProductActions extends wpActions {
    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoProductPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
        $criteria->addJoin(KataoProductPeer::KATAO_PRODUCT_FAMILY_ID, KataoProductFamilyPeer::ID);
        $criteria->addJoin(KataoProductFamilyPeer::KATAO_PRODUCT_CATEGORY_ID, KataoProductCategoryPeer::ID);

        $sf_user = $this->getUser();
        if ($sf_user->isJustSupplier()) {
            $criteria->add(KataoProductPeer::KATAO_SUPPLIER_ID, $sf_user->getInstance()->getKataoSupplierId());
        } 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 'price':
                $criteria->$sort_method(KataoProductPeer::UNIT_PRICE_EURO);
                break;
            case 'category':
                $criteria->$sort_method(KataoProductCategoryPeer::NAME);
                break;
            case 'family':
                $criteria->$sort_method(KataoProductFamilyPeer::NAME);
                break;
            case 'supplier':
                $criteria->$sort_method(KataoSupplierPeer::NAME);
                break;
            default:
                $criteria->$sort_method(KataoProductPeer::NAME);
        }

        if ('' != $this->filter_supplier = $this->getUser()->getAttribute('katao_product_filter_supplier')) {
            $criteria->add(KataoProductPeer::KATAO_SUPPLIER_ID, $this->filter_supplier);
        }
        if ('' != $this->filter_product_category = $this->getUser()->getAttribute('katao_product_filter_product_category')) {
            $criteria->add(KataoProductFamilyPeer::KATAO_PRODUCT_CATEGORY_ID, $this->filter_product_category);
        }
        if ('' != $this->filter_product_family = $this->getUser()->getAttribute('katao_product_filter_product_family')) {
            $criteria->add(KataoProductPeer::KATAO_PRODUCT_FAMILY_ID, $this->filter_product_family);
        }
        if ('' != $this->filter_product_archived = $this->getUser()->getAttribute('katao_product_filter_archived')) {
            $criteria->add(KataoProductPeer::IS_ARCHIVED, (CONST_YES == $this->filter_product_archived)?true:false);
        }

        if ('' != $this->search = $this->getUser()->getAttribute('katao_product_search')) {
            $search_like = sprintf('%%%s%%', $this->search);
            $criterion = $criteria->getNewCriterion(KataoProductPeer::REFERENCE, $search_like, Criteria::LIKE);
            $criterion->addOr($criteria->getNewCriterion(KataoProductPeer::NAME, $search_like, Criteria::LIKE));
            $criterion->addOr($criteria->getNewCriterion(KataoProductPeer::DESCRIPTION, $search_like, Criteria::LIKE));
            $criteria->addAnd($criterion);
        }

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

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

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_product_filter_supplier', $request->getParameter('filter_supplier'));
        $this->getUser()->setAttribute('katao_product_filter_product_category', $request->getParameter('filter_product_category'));
        $this->getUser()->setAttribute('katao_product_filter_product_family', $request->getParameter('filter_product_family'));
        $this->getUser()->setAttribute('katao_product_filter_archived', $request->getParameter('filter_product_archived'));
        return $this->redirect('kataoProduct/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_product_filter_supplier', '');
        $this->getUser()->setAttribute('katao_product_filter_product_category', '');
        $this->getUser()->setAttribute('katao_product_filter_product_family', '');
        $this->getUser()->setAttribute('katao_product_filter_archived', '');
        return $this->redirect('kataoProduct/index');
    }

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

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

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

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

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

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

        if (!is_null($katao_product)) {
            $is_just_supplier = $this->getUser()->isJustSupplier();
            $is_just_referer = $this->getUser()->isJustReferer();
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $local_node_suppliers = $is_just_delegate?KataoSupplierPeer::getAllLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()):array();
            $this->redirectWithErrorIf($is_just_supplier && $this->getUser()->getInstance()->getKataoSupplierId() != $katao_product->getKataoSupplierId());
            $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_product->getKataoSupplier()->getRefererId());
            $this->redirectWithErrorIf($is_just_delegate && empty($local_node_suppliers[$katao_product->getKataoSupplierId()]));
        }

        $this->form = new KataoProductForm($katao_product);
    }

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

        $katao_product = KataoProductPeer::retrieveByPk($request->getParameter('id'));

        if (!is_null($katao_product)) {
            $is_just_supplier = $this->getUser()->isJustSupplier();
            $is_just_referer = $this->getUser()->isJustReferer();
            $is_just_delegate = $this->getUser()->isJustDelegate();
            $local_node_suppliers = $is_just_delegate?KataoSupplierPeer::getAllLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()):array();
            $this->redirectWithErrorIf($is_just_supplier && $this->getUser()->getInstance()->getKataoSupplierId() != $katao_product->getKataoSupplierId());
            $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_product->getKataoSupplier()->getRefererId());
            $this->redirectWithErrorIf($is_just_delegate && empty($local_node_suppliers[$katao_product->getKataoSupplierId()]));
        }

        $this->form = new KataoProductForm($katao_product);

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

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

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

    public function executeEditPresentation($request) {
        $this->katao_product = KataoProductPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_product, 'Produit #' . $request->getParameter('id') . ' inconnu.');

        $is_just_supplier = $this->getUser()->isJustSupplier();
        $is_just_referer = $this->getUser()->isJustReferer();
        $is_just_delegate = $this->getUser()->isJustDelegate();
        $local_node_suppliers = $is_just_delegate?KataoSupplierPeer::getAllLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()):array();
        $this->redirectWithErrorIf($is_just_supplier && $this->getUser()->getInstance()->getKataoSupplierId() != $this->katao_product->getKataoSupplierId());
        $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $this->katao_product->getKataoSupplier()->getRefererId());
        $this->redirectWithErrorIf($is_just_delegate && empty($local_node_suppliers[$this->katao_product->getKataoSupplierId()]));

        if ($request->isMethod('post')) {
            $this->katao_product->setDescription($request->getParameter('description'));
            $this->katao_product->save();

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

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_product = KataoProductPeer::retrieveByPk($request->getParameter('id')));

        $is_just_supplier = $this->getUser()->isJustSupplier();
        $is_just_referer = $this->getUser()->isJustReferer();
        $is_just_delegate = $this->getUser()->isJustDelegate();
        $local_node_suppliers = $is_just_delegate?KataoSupplierPeer::getAllLocalToNode($this->getUser()->getInstance()->getKataoMember()->getKataoNodeId()):array();
        $this->redirectWithErrorIf($is_just_supplier && $this->getUser()->getInstance()->getKataoSupplierId() != $katao_product->getKataoSupplierId());
        $this->redirectWithErrorIf($is_just_referer && $this->getUser()->getInstance()->getKataoMemberId() != $katao_product->getKataoSupplier()->getRefererId());
        $this->redirectWithErrorIf($is_just_delegate && empty($local_node_suppliers[$katao_product->getKataoSupplierId()]));

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

        $katao_product->delete();

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

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

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

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

    public function executeArchiveMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_product')) {
            $done = 0;
            foreach (KataoProductPeer::retrieveByPKs(array_keys(wpPersistenceManager::getSelectedItems('katao_product'))) as/*(KataoProduct)*/ $katao_product) {
                if (!$katao_product->getIsArchived()) {
                    $katao_product->setIsArchived(true);
                    $katao_product->save();
                    $done++;
                }
            }

            if (0 < $done) {
                wpFlashMessages::addConfirmation($done . ' produits sélectionnés sur ' . wpPersistenceManager::getSelectedItemCount('katao_product') . ' ont été archivés avec succès.');
            } else {
                wpFlashMessages::addWarning('Aucun produit sélectionné n\'a été archivé.');
            }
            wpPersistenceManager::cleanSelection('katao_product');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins un produit.');
        }

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

    public function executeAdjustPrices($request) {
        $count = 0;
        foreach (KataoProductPeer::getAll() as/*(KataoProduct)*/ $katao_product) {
            $price_ht_1 = round($katao_product->getUnitPriceEuro(), 3);
            $price_ht_2 = round($katao_product->getUnitPriceEuroCalculated(), 3);
            if ($price_ht_1 != $price_ht_2) {
                $katao_product->setUnitPriceEuro($price_ht_2);
                $katao_product->save();
                $count++;
            }
        }
        if (0 < $count) {
            wpFlashMessages::addConfirmation('Les prix HT de ces ' . $count . ' produits ont été ajustés automatiquement avec succès.');
        } else {
            wpFlashMessages::addWarning('Aucun prix HT n\'a été ajusté automatiquement.');
        }

        $this->redirect('@homepage');
    }
}