<?php

/**
 * kataoCart actions.
 *
 * @package www.katao.fr
 * @subpackage kataoCart
 * @author Your name here
 * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class kataoCartActions extends wpActions {
    public function preExecute() {
        parent::preExecute();
        sfLoader::loadHelpers(array('Asset'));
    }

    public function executeIndex() {
        $criteria = new Criteria();
        $criteria->addJoin(KataoCartPeer::KATAO_USER_ID, KataoUserPeer::ID);
        $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);

        if ($this->getUser()->isJustDelegate()) {
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
        }

        $sort_method = $this->getCriteriaSortMethod();
        switch ($this->sort = $this->getRequestParameter('sort', 'date')) {
            case 'no':
                $criteria->$sort_method(KataoCartPeer::ID);
                break;
            case 'status':
                $criteria->$sort_method(KataoCartPeer::STATUS);
                break;
            case 'member':
                $criteria->$sort_method(KataoMemberPeer::LAST_NAME);
                $criteria->$sort_method(KataoMemberPeer::FIRST_NAME);
                break;
            case 'node':
                $criteria->$sort_method(KataoCartPeer::KATAO_NODE_ID);
                break;
            case 'period':
                $criteria->$sort_method(KataoCartPeer::KATAO_PERIOD_ID);
                break;
            default:
                $criteria->$sort_method(KataoCartPeer::CREATED_AT);
        }

        if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_cart_filter_status')) {
            $criteria->add(KataoCartPeer::STATUS, $this->filter_status);
        }
        if ('' != $this->filter_member = $this->getUser()->getAttribute('katao_cart_filter_member')) {
            $criteria->add(KataoCartPeer::KATAO_USER_ID, $this->filter_member);
        }
        if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_cart_filter_node')) {
            $criteria->add(KataoCartPeer::KATAO_NODE_ID, $this->filter_node);
        }
        if ('' != $this->filter_period = $this->getUser()->getAttribute('katao_cart_filter_period', KataoPeriodPeer::getActivePeriod()->getId())) {
            $criteria->add(KataoCartPeer::KATAO_PERIOD_ID, $this->filter_period);
        }

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

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

        $this->katao_period = KataoPeriodPeer::getActivePeriod();
    }

    public function executeFilter($request) {
        $this->getUser()->setAttribute('katao_cart_filter_status', $request->getParameter('filter_status'));
        $this->getUser()->setAttribute('katao_cart_filter_member', $request->getParameter('filter_member'));
        $this->getUser()->setAttribute('katao_cart_filter_node', $request->getParameter('filter_node'));
        $this->getUser()->setAttribute('katao_cart_filter_period', $request->getParameter('filter_period'));
        return $this->redirect('kataoCart/index');
    }

    public function executeFilterReset($request) {
        $this->getUser()->setAttribute('katao_cart_filter_status', '');
        $this->getUser()->setAttribute('katao_cart_filter_member', '');
        $this->getUser()->setAttribute('katao_cart_filter_node', '');
        $this->getUser()->setAttribute('katao_cart_filter_period', KataoPeriodPeer::getActivePeriod()->getId());
        return $this->redirect('kataoCart/index');
    }

    public function executeShow($request) {
        $this->katao_cart = KataoCartPeer::retrieveByPk($request->getParameter('id'));
        $this->redirectWithErrorUnless($this->katao_cart, 'Demande #' . $request->getParameter('id') . ' inconnue.');
    }

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

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

    public function executeEdit($request) {
        $this->form = new KataoCartForm(KataoCartPeer::retrieveByPk($request->getParameter('id')));
    }

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

        $this->form = new KataoCartForm(KataoCartPeer::retrieveByPk($request->getParameter('id')));

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

            wpFlashMessages::addConfirmation('Demande "' . $katao_cart->getMemberName() . '" sauvée avec succès.');
            $this->redirect('kataoCart/index');
        }

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

    public function executeDelete($request) {
        $this->redirectWithErrorUnless($katao_cart = KataoCartPeer::retrieveByPk($request->getParameter('id')), 'Demande #' . $request->getParameter('id') . ' inconnue.');

        $katao_cart->delete();

        wpFlashMessages::addConfirmation('Demande "' . $katao_cart->getMemberName() . '" supprimée avec succès.');
        $this->redirect('kataoCart/index');
    }

    public function executeDeleteMultiple($request) {
        if (!wpPersistenceManager::isEmpty('katao_cart')) {
            $criteria = new Criteria();
            $criteria->add(KataoCartPeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_cart')), Criteria::IN);
            KataoCartPeer::doDelete($criteria);

            wpPersistenceManager::cleanSelection('katao_cart');
            wpFlashMessages::addConfirmation('Les demandes sélectionnées ont été supprimées avec succès.');
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une demande.');
        }

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

    public function executeGenerateSuppliersOrders($request) {
        $this->redirectWithErrorUnless($katao_period = KataoPeriodPeer::retrieveByPK((int)$this->getUser()->getAttribute('katao_cart_filter_period', KataoPeriodPeer::getActivePeriod()->getId())), 'Merci de filtrer les demandes sur une période avant de générer les commandes fournisseurs.', 'kataoCart/index');
        // $this->redirectWithErrorIf(!Utils::between(time(), $katao_period->getOrderEndedAt(null), $katao_period->getFinishAt(null)));
        $katao_node_ids = array();
        if ($this->getUser()->isJustDelegate()) {
            $katao_node_ids[] = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
        } elseif (!$request->isMethod('post')) {
            $this->katao_node_ids = $katao_period->getKataoNodeIdsForSupplierOrders();
            return sfView::SUCCESS;
        } else {
            $katao_node_ids = $request->getParameter('katao_node_ids', array());
        }

        $katao_order_count = 0;
        if (0 < count($katao_node_ids)) {
            $criteria = new Criteria();
            $criteria->add(KataoOrderPeer::STATUS, array(KataoOrder::STATUS_GENERATED, KataoOrder::STATUS_ADJUSTED), Criteria::NOT_IN);
            $criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $katao_period->getId());
            $criteria->add(KataoOrderPeer::KATAO_NODE_ID, $katao_node_ids, Criteria::IN);
            if (0 < KataoOrderPeer::doCount($criteria)) {
                wpFlashMessages::addError('Impossible de re-générer les commandes pour ces noeuds et cette période car une commande à déjà été envoyée.');
                return $this->redirect('kataoCart/index');
            }

            $criteria = new Criteria();
            $criteria->add(KataoOrderPeer::STATUS, array(KataoOrder::STATUS_GENERATED, KataoOrder::STATUS_ADJUSTED), Criteria::IN);
            $criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $katao_period->getId());
            $criteria->add(KataoOrderPeer::KATAO_NODE_ID, $katao_node_ids, Criteria::IN);
            if (0 < $katao_order_deleted = KataoOrderPeer::doDelete($criteria)) {
                wpFlashMessages::addInformation('Certaines commandes fournisseurs ont été re-générées (' . $katao_order_deleted . ' au total).');
            }

            $products_by_node_and_period_and_supplier = array();

            $criteria = new Criteria();
            $criteria->add(KataoCartPeer::KATAO_PERIOD_ID, $katao_period->getId());
            $criteria->add(KataoCartPeer::KATAO_NODE_ID, $katao_node_ids, Criteria::IN);

            $is_simulated = false;
            foreach (KataoCartPeer::doSelect($criteria) as/*(KataoCart)*/ $katao_cart) {
                if (KataoCart::STATUS_VALIDATED != $katao_cart->getStatus()) {
                    $is_simulated = true;
                }
                foreach ($katao_cart->getKataoCartProductsJoinKataoProduct() as/*(KataoCartProduct)*/ $katao_cart_product) {
                    $katao_product = $katao_cart_product->getKataoProduct();
                    if (!isset($products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['quantity'])) {
                        $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['quantity'] = 0;
                    }
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['quantity'] += $katao_cart_product->getQuantity();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['reference'] = $katao_product->getReference();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['name'] = $katao_product->getName();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['price_euro'] = $katao_product->getUnitPriceEuro();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['margin'] = $katao_product->getMargin();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['tva_rate'] = $katao_product->getTvaRate();
                    $products_by_node_and_period_and_supplier[$katao_cart->getKataoNodeId()][$katao_cart->getKataoPeriodId()][$katao_product->getKataoSupplierId()][$katao_product->getId()]['katao_cart_products'][] = $katao_cart_product;
                }
            }

            foreach ($products_by_node_and_period_and_supplier as $katao_node_id => $periods) {
                foreach ($periods as $katao_period_id => $suppliers) {
                    foreach ($suppliers as $katao_supplier_id => $products) {
                        if (null != $katao_supplier = KataoSupplierPeer::retrieveByPK($katao_supplier_id)) {
                            $katao_order = new KataoOrder();

                            $katao_order->setIsSimulated($is_simulated);

                            $katao_order->setKataoSupplierId($katao_supplier_id);
                            $katao_order->setKataoNodeId($katao_node_id);
                            $katao_order->setKataoPeriodId($katao_period_id);
                            $katao_order->setStatus(KataoOrder::STATUS_GENERATED);

                            $katao_order->setSupplierName($katao_supplier->getName());
                            $katao_order->setSupplierEmail($katao_supplier->getEmail());
                            $katao_order->setSupplierAddress1($katao_supplier->getAddress1());
                            $katao_order->setSupplierAddress2($katao_supplier->getAddress2());
                            $katao_order->setSupplierZip($katao_supplier->getZip());
                            $katao_order->setSupplierCity($katao_supplier->getCity());

                            $katao_order->setKataoName(wpConfig::getName());
                            $katao_order->setKataoAddress(wpConfig::getAddress());
                            $katao_order->setKataoSiretNumber(wpConfig::getSiretNumber());
                            $katao_order->setKataoRcsNumber(wpConfig::getRCSNumber());
                            $katao_order->setKataoCapital(wpConfig::getCapital());

                            $katao_order->save();

                            $katao_order_count++;

                            foreach ($products as $katao_product_id => $product_data) {
                                $katao_order_product = new KataoOrderProduct();
                                $katao_order_product->setKataoOrder($katao_order);
                                $katao_order_product->setKataoProductId($katao_product_id);
                                $katao_order_product->setProductReference($product_data['reference']);
                                $katao_order_product->setProductName($product_data['name']);
                                $katao_order_product->setProductPriceEuro($product_data['price_euro']);
                                $katao_order_product->setProductMargin($product_data['margin']);
                                $katao_order_product->setProductTvaRate($product_data['tva_rate']);
                                $katao_order_product->setQuantity($product_data['quantity']);
                                $katao_order_product->save();

                                foreach ($product_data['katao_cart_products'] as $katao_cart_product) {
                                    $katao_cart_product->setKataoOrderProduct($katao_order_product);
                                    $katao_cart_product->setQuantityAdjusted($katao_cart_product->getQuantity());
                                    $katao_cart_product->setHasBeenAdjusted(true);
                                    $katao_cart_product->save();
                                }
                            }
                        }
                    }
                }
            }
        }

        if (0 < $katao_order_count) {
            wpFlashMessages::addConfirmation('Commandes fournisseurs générées avec succès (' . $katao_order_count . ' au total).');
            if ($is_simulated) {
                $this->redirect('kataoOrder/simulated');
            } else {
                $this->redirect('kataoOrder/index');
            }
        }

        wpFlashMessages::addWarning('Aucune commande fournisseur n\'a été générée.');
        $this->redirect('kataoCart/index');
    }

    public function executeExportPDF($request) {
        $this->redirectWithErrorUnless($katao_cart = KataoCartPeer::retrieveByPk($request->getParameter('id')), 'Demande #' . $request->getParameter('id') . ' inconnue.');

        $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 executeExportPDFAll($request) {
        $criteria = new Criteria();
        if ($this->getUser()->isJustDelegate()) {
            $criteria->addJoin(KataoCartPeer::KATAO_USER_ID, KataoUserPeer::ID);
            $criteria->addJoin(KataoUserPeer::KATAO_MEMBER_ID, KataoMemberPeer::ID);
            $criteria->add(KataoMemberPeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
        }
        $criteria->addAscendingOrderByColumn(KataoCartPeer::ID);
        return $this->exportCartsToPDF(KataoCartPeer::doSelect($criteria));
    }

    public function executeExportPDFSelected($request) {
        if (!wpPersistenceManager::isEmpty('katao_cart')) {
            $criteria = new Criteria();
            $criteria->add(KataoCartPeer::ID, array_keys(wpPersistenceManager::getSelectedItems('katao_cart')), Criteria::IN);
            $criteria->addAscendingOrderByColumn(KataoCartPeer::ID);
            return $this->exportCartsToPDF(KataoCartPeer::doSelect($criteria));
        } else {
            wpFlashMessages::addWarning('Merci de sélectionner au moins une demande.');
            $this->redirect('kataoCart/index');
        }
    }

    protected function exportCartsToPDF($katao_carts) {
        $file = tempnam('tmp', 'zip');
        $archive = new ZipArchive();
        $archive->open($file, ZipArchive::OVERWRITE);

        foreach ($katao_carts as/*(KataoCart)*/ $katao_cart) {
            $archive->addFromString($katao_cart->getNumber() . '.pdf', $katao_cart->generatePDF());
        }

        $archive->close();

        $response = $this->getResponse();
        $response->setContentType('application/zip');
        $response->setHttpHeader('Content-disposition', 'attachment; filename="KATAO_Demandes_' . date('Y-m-d') . '.zip"');
        $response->setHttpHeader('Content-Length', filesize($file));
        $response->setHttpHeader('Pragma', 'public');
        $response->setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setHttpHeader('Expires', '0');
        $response->setContent(file_get_contents($file));
        return sfView::NONE;
    }

    public function executeValidate($request) {
        $this->redirectWithErrorUnless($katao_cart = KataoCartPeer::retrieveByPk($request->getParameter('id')), 'Demande #' . $request->getParameter('id') . ' inconnue.');

        $katao_cart->setStatus(KataoCart::STATUS_VALIDATED);
        $katao_cart->save();

        wpFlashMessages::addConfirmation('Demande "' . $katao_cart->getNumber() . '" validée avec succès.');
        $this->redirect('kataoCart/index');
    }

    public function executeUnvalidate($request) {
        $this->redirectWithErrorUnless($katao_cart = KataoCartPeer::retrieveByPk($request->getParameter('id')), 'Demande #' . $request->getParameter('id') . ' inconnue.');

        $katao_cart->setStatus(KataoCart::STATUS_IN_PROGRESS);
        $katao_cart->save();

        wpFlashMessages::addConfirmation('Demande "' . $katao_cart->getNumber() . '" dé-validée avec succès.');
        $this->redirect('kataoCart/index');
    }
}