<?php

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

	public function executeIndex() {
		$criteria = new Criteria();
		$criteria->addJoin(KataoOrderPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
		$criteria->add(KataoOrderPeer::IS_SIMULATED, false);

		if ($this->getUser()->isJustDelegate()) {
			$criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
			$criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
			$criteria->setDistinct();
		}

		$sort_method = $this->getCriteriaSortMethod();
		switch ($this->sort = $this->getRequestParameter('sort', 'supplier')) {
			case 'no':
				$criteria->$sort_method(KataoOrderPeer::ID);
				break;
			case 'status':
				$criteria->$sort_method(KataoOrderPeer::STATUS);
				break;
			case 'node':
				$criteria->$sort_method(KataoOrderPeer::KATAO_NODE_ID);
				break;
			case 'period':
				$criteria->$sort_method(KataoOrderPeer::KATAO_PERIOD_ID);
				break;
			default:
				$criteria->$sort_method(KataoOrderPeer::SUPPLIER_NAME);
		}

		if ('' != $this->filter_status = $this->getUser()->getAttribute('katao_cart_order_status')) {
			$criteria->add(KataoOrderPeer::STATUS, $this->filter_status);
		}
		if ('' != $this->filter_supplier = $this->getUser()->getAttribute('katao_cart_order_supplier')) {
			$criteria->add(KataoOrderPeer::KATAO_SUPPLIER_ID, $this->filter_supplier);
		}
		if ('' != $this->filter_node = $this->getUser()->getAttribute('katao_cart_order_node')) {
			$criteria->add(KataoOrderPeer::KATAO_NODE_ID, $this->filter_node);
		}
		if ('' != $this->filter_period = $this->getUser()->getAttribute('katao_cart_order_period', KataoPeriodPeer::getActivePeriod()->getId())) {
			$criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $this->filter_period);
		}

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

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

	public function executeSimulated() {
		$criteria = new Criteria();
		$criteria->addJoin(KataoOrderPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
		$criteria->add(KataoOrderPeer::IS_SIMULATED, true);

		if ($this->getUser()->isJustDelegate()) {
			$criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
			$criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
			$criteria->setDistinct();
		}

		$sort_method = $this->getCriteriaSortMethod();
		$criteria->$sort_method(KataoOrderPeer::SUPPLIER_NAME);

		$pager = new sfPropelPager('KataoOrder', 1000);
		$pager->setCriteria($criteria);
		$pager->setPage(1);
		$pager->init();
		$this->pager = $pager;

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

	public function executeFilter($request) {
		$this->getUser()->setAttribute('katao_cart_order_status', $request->getParameter('filter_status'));
		$this->getUser()->setAttribute('katao_cart_order_supplier', $request->getParameter('filter_supplier'));
		$this->getUser()->setAttribute('katao_cart_order_node', $request->getParameter('filter_node'));
		$this->getUser()->setAttribute('katao_cart_order_period', $request->getParameter('filter_period'));
		return $this->redirect('kataoOrder/index');
	}

	public function executeFilterReset($request) {
		$this->getUser()->setAttribute('katao_cart_order_status', '');
		$this->getUser()->setAttribute('katao_cart_order_supplier', '');
		$this->getUser()->setAttribute('katao_cart_order_node', '');
		$this->getUser()->setAttribute('katao_cart_order_period', KataoPeriodPeer::getActivePeriod()->getId());
		return $this->redirect('kataoOrder/index');
	}

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

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

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

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

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

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

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

			wpFlashMessages::addConfirmation('Commande "' . $katao_order->getSupplierName() . '" sauvée avec succès.');
			$this->redirect('kataoOrder/index');
		}

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

	public function executeDelete($request) {
		$this->redirectWithErrorUnless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');

		$katao_order->delete();

		wpFlashMessages::addConfirmation('Commande "' . $katao_order->getSupplierName() . '" supprimée avec succès.');
		$this->redirect('kataoOrder/index');
	}

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

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

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

	public function executeDeleteSimulated($request) {
		$criteria = new Criteria();
		$criteria->add(KataoOrderPeer::IS_SIMULATED, true);
		KataoOrderPeer::doDelete($criteria);

		wpFlashMessages::addConfirmation('Toutes les commandes simulées ont été supprimées avec succès.');
		$this->redirect('kataoOrder/simulated');
	}

	public function executeAdjust($request) {
		$this->redirectWithErrorUnless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->redirectWithErrorIf(KataoOrder::STATUS_GENERATED != $katao_order->getStatus());

		$katao_order->adjust($this->getUser());

		wpFlashMessages::addConfirmation('Commande "' . $katao_order->getNumber() . '" marquée comme ajustée avec succès.');
		$this->redirect('kataoOrder/index');
	}

	public function executeForceAdjustment($request) {
		$this->redirectWithErrorUnless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->redirectWithErrorIf(KataoOrder::STATUS_GENERATED != $katao_order->getStatus());
		$this->redirectWithErrorIf($this->getUser()->isJustDelegate());

		$katao_order->setStatus(KataoOrder::STATUS_ADJUSTED);
		$katao_order->save();

		$katao_order->notifyMembersWithModifiedAdjustedQuantities();

		wpFlashMessages::addConfirmation('L\'ajustement de la commande "' . $katao_order->getNumber() . '" a été forcé avec succès.');
		$this->redirect('kataoOrder/index');
	}

	public function executeAdjustProduct($request) {
		$this->redirectWithErrorUnless($this->katao_order_product = KataoOrderProductPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');

		$this->view_mode_only = KataoOrder::STATUS_GENERATED != $this->katao_order_product->getKataoOrder()->getStatus();
		if (!$this->view_mode_only && $request->isMethod('POST')) {
			$redirect_to_adjust = false;

			$katao_order_product_quantity = 0;
			foreach ($request->getParameter('quantity') as $katao_cart_product_id => $quantity) {
				if ($katao_cart_product_id) {
					KataoCartProductPeer::adjustQuantity($katao_cart_product_id, $quantity);
				} elseif (null != $katao_user_id = $request->getParameter('new_user_id')) {
					$this->katao_order_product->addProductToUser($katao_user_id, $quantity);
					$redirect_to_adjust = true;
				}
				$katao_order_product_quantity += $quantity;
			}
			$this->katao_order_product->setQuantity($katao_order_product_quantity);
			$this->katao_order_product->save();

			if ($redirect_to_adjust) {
				$this->redirect('@katao_order_product_adjust?id=' . $this->katao_order_product->getId());
			} else {
				wpFlashMessages::addConfirmation('Produit "' . $this->katao_order_product->getKataoProduct()->getName() . '" de la commande fournisseur "' . $this->katao_order_product->getKataoOrder()->getNumber() . '" ajusté avec succès.');
				$this->redirect('kataoOrder/index');
			}
		}
	}

	public function executeDeliverProduct($request) {
		$this->redirectWithErrorUnless($this->katao_order_product = KataoOrderProductPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');

		if ($request->isMethod('POST')) {
			$katao_order_product_quantity = 0;
			foreach ($request->getParameter('quantity') as $katao_cart_product_id => $quantity) {
				if ($katao_cart_product_id) {
					KataoCartProductPeer::deliverQuantity($katao_cart_product_id, $quantity);
					$katao_order_product_quantity += $quantity;
				}
			}
			$this->katao_order_product->setQuantityDelivered($katao_order_product_quantity);
			$this->katao_order_product->setHasBeenDelivered(true);
			$this->katao_order_product->save();

			wpFlashMessages::addConfirmation('Produit "' . $this->katao_order_product->getKataoProduct()->getName() . '" de la commande fournisseur "' . $this->katao_order_product->getKataoOrder()->getNumber() . '" délivré avec succès.');
			$this->redirect('kataoOrder/index');
		}
	}

	public function executeGenerateMembersInvoices($request) {
		$this->redirectWithErrorUnless($this->katao_period = KataoPeriodPeer::retrieveByPK($this->filter_period = $this->getUser()->getAttribute('katao_cart_order_period', KataoPeriodPeer::getActivePeriod()->getId())), 'Merci de sélectionner une période.');

		$katao_node_ids = array();
		if ($this->getUser()->isJustDelegate()) {
			$katao_node_ids[] = $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId();
		} elseif (!$request->isMethod('post')) {
			$this->katao_node_ids = $this->katao_period->getKataoNodeIdsForMemberInvoices();
			return sfView::SUCCESS;
		} else {
			$katao_node_ids = $request->getParameter('katao_node_ids', array());
		}
		// re-vérification des noeuds possibles pour la génération des factures pour éviter les doublons si clic simultanés ou avec 2 fen^tres en parallèle...
		$valid_katao_node_ids = $this->katao_period->getKataoNodeIdsForMemberInvoices();
		foreach ($katao_node_ids as $index => $katao_node_id) {
			if (empty($valid_katao_node_ids[$katao_node_id]['available'])) {
				unset($katao_node_ids[$index]);
			}
		}

		$katao_invoice_count = 0;
		if (0 < count($katao_node_ids)) {
			$carts_to_validate = array();
			$products_by_member = array();

			$criteria = new Criteria();
			$criteria->add(KataoOrderPeer::STATUS, KataoOrder::STATUS_RECEIVED);
			$criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $this->katao_period->getId());
			$criteria->add(KataoOrderPeer::KATAO_NODE_ID, $katao_node_ids, Criteria::IN);
			foreach (KataoOrderPeer::doSelect($criteria) as/*(KataoOrder)*/ $katao_order) {
				foreach ($katao_order->getKataoOrderProducts() as/*(KataoOrderProduct)*/ $katao_order_product) {
					foreach ($katao_order_product->getKataoCartProductsJoinKataoCart() as/*(KataoCartProduct)*/ $katao_cart_product) {
						$katao_cart = $katao_cart_product->getKataoCart();
						$katao_product = $katao_cart_product->getKataoProduct();
						$carts_to_validate[$katao_cart->getId()] = $katao_cart;

						$products_by_member[$katao_cart->getKataoUserId()]['cart'] = $katao_cart->getId();
						$products_by_member[$katao_cart->getKataoUserId()]['node'] = $katao_cart->getKataoNodeId();
						$products_by_member[$katao_cart->getKataoUserId()]['period'] = $katao_cart->getKataoPeriodId();
						$products_by_member[$katao_cart->getKataoUserId()]['products'][$katao_cart_product->getKataoProductId()] = array('name' => $katao_cart_product->getProductName(), 'price' => $katao_cart_product->getProductPriceEuro(), 'quantity' => $katao_cart_product->getQuantityAdjusted(), 'tva_rate' => $katao_cart_product->getProductTvaRate(), 'reference' => $katao_cart_product->getProductReference(), 'margin' => $katao_cart_product->getProductMargin(), 'product_max_sol_amount' => $katao_product->getMaxSolAmount(), 'katao_order_product_id' => $katao_order_product->getId(), 'katao_cart_product_id' => $katao_cart_product->getId());
					}
				}
			}

			foreach ($products_by_member as $katao_user_id => $products_data) {
				if (null != $katao_user = KataoUserPeer::retrieveByPK($katao_user_id)) {
					if (null != $katao_member = $katao_user->getKataoMember()) {
						$katao_invoice = new KataoInvoice();

						$katao_invoice->setKataoMember($katao_member);
						$katao_invoice->setKataoPeriodId($products_data['period']);
						$katao_invoice->setKataoNodeId($products_data['node']);
						$katao_invoice->setKataoCartId($products_data['cart']);
						$katao_invoice->setStatus(KataoInvoice::STATUS_GENERATED);

						$katao_invoice->setMemberFirstName($katao_member->getFirstName());
						$katao_invoice->setMemberLastName($katao_member->getLastName());
						$katao_invoice->setMemberEmail($katao_user->getEmail());
						$katao_invoice->setMemberAddress1($katao_user->getAddress1());
						$katao_invoice->setMemberAddress2($katao_user->getAddress2());
						$katao_invoice->setMemberZip($katao_user->getZip());
						$katao_invoice->setMemberCity($katao_user->getCity());

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

						$katao_invoice->save();

						$katao_invoice_count++;

						$current_amount_sol = $katao_member->getCurrentAmountSol();

						$amount = 0;
						$used_sol = 0;
						foreach ($products_data['products'] as $katao_product_id => $data) {
							$katao_invoice_product = new KataoInvoiceProduct();
							$katao_invoice_product->setKataoInvoice($katao_invoice);
							$katao_invoice_product->setKataoProductId($katao_product_id);
							$katao_invoice_product->setKataoCartProductId($data['katao_cart_product_id']);
							$katao_invoice_product->setKataoOrderProductId($data['katao_order_product_id']);
							$katao_invoice_product->setProductReference($data['reference']);
							$katao_invoice_product->setProductName($data['name']);
							$katao_invoice_product->setProductPriceEuro($data['price']);
							$katao_invoice_product->setProductMargin($data['margin']);
							$katao_invoice_product->setProductTvaRate($data['tva_rate']);
							$katao_invoice_product->setQuantity($data['quantity']);
							$katao_invoice_product->setQuantityDelivered($data['quantity']);

							$sol_amount = $data['quantity'] * $data['product_max_sol_amount'];
							if ($current_amount_sol >= $sol_amount) {
								$used_sol += $sol_amount;
								$katao_invoice_product->setSolAmount($sol_amount);
								$current_amount_sol = max(0, $current_amount_sol - $sol_amount);
							} else {
								$used_sol += $current_amount_sol;
								$katao_invoice_product->setSolAmount($current_amount_sol);
								$current_amount_sol = 0;
							}

							$katao_invoice_product->save();

							$amount += $data['quantity'] * $data['price'];
						}

						$katao_invoice->setSolAmount($used_sol);
						$katao_invoice->save();
					}
				}
			}

			foreach ($carts_to_validate as $katao_cart) {
				$katao_cart->setStatus(KataoCart::STATUS_ARCHIVED);
				$katao_cart->save();
			}
		}

		if (0 < $katao_invoice_count) {
			wpFlashMessages::addConfirmation('Factures adhérents générées avec succès (' . $katao_invoice_count . ' au total).');
			$this->redirect('kataoInvoice/index');
		}

		wpFlashMessages::addWarning('Aucune facture adhérent n\'a été générée.');
		$this->redirect('kataoOrder/index');
	}

	public function executeExportPDF($request) {
		$this->redirectWithErrorUnless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		if ($this->getUser()->isJustSupplier()) {
			$this->redirectWithErrorIf($katao_order->getKataoSupplierId() != $this->getUser()->getInstance()->getKataoSupplierId(), 'Accès restreint.', '@profile');
		}

		$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 executeSend($request) {
		$this->redirectWithErrorUnless($this->katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');

		if ('' == $this->katao_order->getDeliveryAddress()) {
			if ($request->isMethod('post')) {
				$this->katao_order->setDeliveryAddress($request->getParameter('delivery_address'));
				$this->katao_order->save();
			} else {
				$this->delivery_address = KataoOrderPeer::getLastDeliveryAddress($this->katao_order->getKataoNodeId(), $this->katao_order->getKataoSupplierId());
				return sfView::SUCCESS;
			}
		}

		try {
			if (!$request->getParameter('do_not_send')) {
				if ('' != $this->katao_order->getSupplierEmail()) {
					$katao_node = $this->katao_order->getKataoNode();

					$katao_user_delegate = $katao_node->getKataoUser();
					$katao_member_delegate = $katao_user_delegate->getKataoMember();

					$katao_member_seo = wpConfig::getInstance()->getKataoMember();
					$katao_user_seo = $katao_member_seo->getFirstKataoUser();

					$content = $this->katao_order->generatePDF();

					$mailer = new wpMail();

					$message = new Swift_Message('Commande Katao');
					$message->attach(new Swift_Message_Part(sprintf('Madame, Monsieur,

Veuillez trouver en pièce jointe notre commande n° %s du %s pour le noeud %s.

Merci de nous confirmer sa bonne réception.

Pour tout problème, merci de prendre contact avec le délégué de %s :
%s %s
%s / %s

Ou, à défaut, notre gérant :
%s %s
%s / %s

La livraison sera au plus tard le %s à l\'adresse suivante :
%s
%s', $this->katao_order->getNumber(), CatalyzDate::formatShort($this->katao_order->getCreatedAt(null)), $katao_node->getCity(), $katao_node->getCity(), $katao_member_delegate->getLastName(), $katao_member_delegate->getFirstName(), $katao_user_delegate->getPhone(), $katao_user_delegate->getEmail(), $katao_member_seo->getLastName(), $katao_member_seo->getFirstName(), $katao_user_seo->getPhone(), $katao_user_seo->getEmail(), $this->katao_order->getKataoPeriod()->getFinishAtStr(), $this->katao_order->getDeliveryAddress(), Utils::getKataoEmailFooter())));
					$message->attach(new Swift_Message_Attachment($content, sprintf('%s.pdf', $this->katao_order->getNumber()), 'application/pdf'));

					$mailer->send($message, new Swift_Address($this->katao_order->getSupplierEmail(), $this->katao_order->getSupplierName()), sfConfig::get('app_mail_from'));
					$mailer->disconnect();

					wpFlashMessages::addConfirmation('Commande "' . $this->katao_order->getNumber() . '" envoyée avec succès.');
				} else {
					wpFlashMessages::addInformation('Commande "' . $this->katao_order->getNumber() . '" non envoyée car ce fournisseur n\'a pas d\'email. Merci de bien vouloir l\'exporter et la lui envoyer ou faxer.');
				}
			} else {
				wpFlashMessages::addConfirmation('Commande "' . $this->katao_order->getNumber() . '" marquée comme envoyée avec succès.');
			}

			if (KataoOrder::STATUS_ADJUSTED == $this->katao_order->getStatus()) {
				$this->katao_order->setStatus(KataoOrder::STATUS_SENT);
				$this->katao_order->save();
			}
		}
		catch (Exception $e) {
			$mailer->disconnect();
			wpFlashMessages::addError('Impossible d\'envoyer la commande ' . $this->katao_order->getNumber() . '.');
		}
		$this->redirect('kataoOrder/index');
	}

	public function executeReceive($request) {
		$this->redirectWithErrorUnless($this->katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->redirectWithErrorIf(KataoOrder::STATUS_SENT != $this->katao_order->getStatus());

		if ($request->isMethod('post')) {
			foreach ($request->getParameter('quantity') as $katao_order_product_id => $quantity) {
				KataoOrderProductPeer::receiveQuantity($katao_order_product_id, $quantity);
			}

			$this->katao_order->setStatus(KataoOrder::STATUS_RECEIVED);
			$this->katao_order->save();

			if ($this->getUser()->isJustDelegate()) {
				$this->katao_order->notifiySeoWithReceive();
			}

			wpFlashMessages::addConfirmation('Commande "' . $this->katao_order->getNumber() . '" marquée comme réceptionnée avec succès.');
			$this->redirect('kataoOrder/index');
		}
	}

	public function executeDeliver($request) {
		$this->redirectWithErrorUnless($katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->redirectWithErrorIf(KataoOrder::STATUS_RECEIVED != $katao_order->getStatus());

		$katao_order->setStatus(KataoOrder::STATUS_DELIVERED);
		$katao_order->save();

		$katao_order->notifyMembersWithModifiedDeliveredQuantities();

		if ($this->getUser()->isJustDelegate()) {
			$katao_order->notifiySeoWithDeliver();
		}

		wpFlashMessages::addConfirmation('Commande "' . $katao_order->getNumber() . '" marquée comme délivrée avec succès.');
		$this->redirect('kataoOrder/index');
	}

	public function executeExportPDFAll($request) {
		$criteria = new Criteria();
		if ($this->getUser()->isJustDelegate()) {
			$criteria->addJoin(KataoOrderPeer::KATAO_SUPPLIER_ID, KataoSupplierPeer::ID);
			$criteria->addJoin(KataoSupplierPeer::ID, KataoSupplierNodePeer::KATAO_SUPPLIER_ID);
			$criteria->add(KataoSupplierNodePeer::KATAO_NODE_ID, $this->getUser()->getInstance()->getKataoMember()->getKataoNodeId());
			$criteria->setDistinct();
		}
		$criteria->addAscendingOrderByColumn(KataoOrderPeer::ID);
		return $this->exportOrdersToPDF(KataoOrderPeer::doSelect($criteria));
	}

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

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

		foreach ($katao_orders as/*(KataoOrder)*/ $katao_order) {
			$archive->addFromString($katao_order->getNumber() . '.pdf', $katao_order->generatePDF());
		}

		$archive->close();

		$response = $this->getResponse();
		$response->setContentType('application/zip');
		$response->setHttpHeader('Content-disposition', 'attachment; filename="KATAO_Commandes_' . 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 executeAdjustMultiple($request) {
		if (!wpPersistenceManager::isEmpty('katao_order')) {
			$done = 0;

			foreach (KataoOrderPeer::retrieveByPKs(array_keys(wpPersistenceManager::getSelectedItems('katao_order'))) as/*(KataoOrder)*/ $katao_order) {
				if (KataoOrder::STATUS_GENERATED == $katao_order->getStatus()) {
					if ($katao_order->sumProducts() >= $katao_order->getKataoSupplier()->getOrderMinAmount()) {
						$last_incomplete_package_count = 0;
						foreach ($katao_order->getKataoOrderProductsJoinKataoProduct() as/*(KataoOrderProduct)*/ $katao_order_product) {
							$last_incomplete_package_count += $katao_order_product->getKataoProduct()->getLastIncompletePackageQuantity($katao_order->getKataoPeriodId(), $katao_order->getKataoNodeId(), true);
						}

						if (0 == $last_incomplete_package_count) {
							$katao_order->adjust($this->getUser());
							$done++;
						}
					}
				}
			}

			if (0 < $done) {
				wpFlashMessages::addConfirmation($done . ' commandes sélectionnés sur ' . wpPersistenceManager::getSelectedItemCount('katao_order') . ' ont été marquées comme ajustées avec succès.');
			} else {
				wpFlashMessages::addWarning('Aucune commande sélectionnée n\'a été marquée comme ajustée.');
			}
			wpPersistenceManager::cleanSelection('katao_order');
		} else {
			wpFlashMessages::addWarning('Merci de sélectionner au moins une commande.');
		}

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

	public function executeReceiveNewProduct($request) {
		$this->redirectWithErrorUnless($this->katao_order = KataoOrderPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->redirectWithErrorIf(KataoOrder::STATUS_SENT != $this->katao_order->getStatus());

		if ($request->isMethod('post')) {
			$this->redirectWithErrorUnless($katao_product = KataoProductPeer::retrieveByPk($request->getParameter('product')), 'Produit #' . $request->getParameter('product') . ' inconnu.');

			$katao_order_product = new KataoOrderProduct();
			$katao_order_product->setKataoOrder($this->katao_order);
			$katao_order_product->setKataoProduct($katao_product);
			$katao_order_product->setProductReference($katao_product->getReference());
			$katao_order_product->setProductName($katao_product->getName());
			$katao_order_product->setProductPriceEuro($katao_product->getUnitPriceEuro());
			$katao_order_product->setProductMargin($katao_product->getMargin());
			$katao_order_product->setProductTvaRate($katao_product->getTvaRate());
			$katao_order_product->setQuantity(0);
			$katao_order_product->setQuantityReceived(0);
			$katao_order_product->setQuantityDelivered(0);
			$katao_order_product->setHasBeenReceived(false);
			$katao_order_product->setHasBeenDelivered(false);
			$katao_order_product->save();

			wpFlashMessages::addConfirmation('Produit "' . $katao_product->getName() . '" ajouté à la commande "' . $this->katao_order->getNumber() . '" avec succès.');
			$this->redirect('kataoOrder/index');
		}
	}

	public function executeSimulatedMembers($request) {
		$this->redirectWithErrorUnless($this->katao_order_product = KataoOrderProductPeer::retrieveByPk($request->getParameter('id')), 'Commande #' . $request->getParameter('id') . ' inconnue.');
		$this->katao_product = $this->katao_order_product->getKataoProduct();
		$this->katao_order = $this->katao_order_product->getKataoOrder();
	}
}