Current File : /home/karenpetzb/application/modules/default/controllers/ProduitsController.php
<?php

class ProduitsController extends Modules_Default_Controllers_MainController
{

	private $myCaddy;

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}
	public function indexAction()
	{
		$this->_redirect('/');
	}
    public function ajaxdownloaddocumentAction() {
    
        $message = "";
        $isSuccess = false;
        if ($this->getRequest()->isPost()) {
        
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$validatorEmail = new Zend_Validate_EmailAddress();
                
			$params = array();
			$params = $this->getRequest()->getPost();

			$civility = $filter->filter($params['civility_doc']);
			$name = $filter->filter($params['name_doc']);
			$firstname = $filter->filter($params['firstname_doc']);
			$email = $filter->filter($params['email_doc']);
			$product_id = (int) $params['product_id_doc'];
            
			if ($validator->isValid($civility) && $validator->isValid($name)  && $validator->isValid($firstname)
             && $validatorEmail->isValid($email)  && $product_id > 0) {
             
				$product = $this->computeProductDetail($product_id);
                $linkProd = $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlProduct($product['NAVNOM_URLPARENTS'], $product['NAVNOM'], $product['ID']);
	            $linkCat = $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlCategory($product['NAVNOM_URLPARENTS'], $product['CATNAVNOM'], $product['IDCATEGORY']);
                $prodName = $product['NOM'];
                $catName = $product['CATNOM'];
                
                $docUrl =$product['DOCURL'];
                if (empty($docUrl)) {
					$listFTFDS = $this->getFTFDSByIdProd($product_id);
                    if (isset($listFTFDS) && !empty($listFTFDS) && sizeof($listFTFDS) > 0) {
                           $docUrl = $listFTFDS[0]['URL'];
                    }
                }
                
                $destFullName = $civility." ".$firstname." ".$name;
                
                $fromEmail = $this->no_reply_Mail;
                $fromName = $this->siteName;
                $toEmail = $email;
                
                try {
                    $userGuest = new UserGuest();
                    $date = new Zend_Date();
                    $data = array (
						'INFORMATION' => $destFullName,
						'ACTION' => "Fiche technique � t�l�charger : ".$prodName,
						'EMAIL' => $toEmail,
                        'DATEINSERT' => $date->toString('YYYY-MM-dd HH:mm:ss')
					);
					$userGuest->insert($data);
                    
			        $view = new Zend_View();
			        $view->addScriptPath('../application/modules/default/views/helpers/');
			        $view->assign("user_name",$name);
			        $view->assign("user_firstname",$firstname);
			        $view->assign("user_email",$email);
			        $view->assign("user_civility",$civility);
			        $view->assign("user_fullname",$destFullName);
                    
			        $view->assign("site_url",$this->siteName);
			        $view->assign("product_url",$linkProd);
			        $view->assign("category_url",$linkCat);
			        $view->assign("category_name",$catName);
			        $view->assign("product_name",$prodName);
			        $view->assign("document_link",$this->baseUrl_SiteCommerceUrl."/".$docUrl);
                    
                    $body = $view->render("mail_ajaxdownloaddocument.phtml");
			        $subject = "Fiche technique : ".$prodName;
				
			        $mail = new Zend_Mail();
			        $mail->setBodyHtml($body);
			        $mail->setFrom($fromEmail, $fromName);
			        $mail->addTo($toEmail);
			        $mail->setSubject($subject);

			        $mail->send();
			        $this->log("L'email de fiche technique a �t� envoy� par : ".$fromEmail.", ".$fromName." � ".$toEmail,'info');
 
		        } catch (Zend_Exception $e) {
			        $this->log($e->getMessage(),'err');
		        }         
             
                $message = "Le mail � �t� envoy� � <b>".$destFullName."</b>.";
                $isSuccess = true;
            }   else if ($product_id > 0) {
				$product = $this->computeProductDetail($product_id);
			    $this->view->detailProduct = $product;
            }  
        }
        
        $this->view->message = $message;
        $this->view->isSuccess = $isSuccess;
        
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
    }
    public function ajaxsendfriendAction() {
    
        $message = "";
        $isSuccess = false;
        if ($this->getRequest()->isPost()) {
        
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();

			$name = $filter->filter($params['name_friend']);
			$email = $filter->filter($params['email_friend']);
			$message = nl2br(htmlspecialchars($params['message_friend']));
			$product_id = (int) $params['product_id_friend'];
            
			if ($validator->isValid($name)  && $validator->isValid($email) && $validator->isValid($message) && $product_id > 0) {
            
                $fromEmail = $this->no_reply_Mail;
                $fromName = $name;
                $toEmail = $email;
				$product = $this->computeProductDetail($product_id);
                
                 try {
                 
                    $userGuest = new UserGuest();
					$date = new Zend_Date();
                    $data = array (
						'INFORMATION' => $name,
						'ACTION' => "Conseillez cet article : ".$product["NOM"],
						'EMAIL' => $toEmail,
                        'DATEINSERT' => $date->toString('YYYY-MM-dd HH:mm:ss')
					);
					$userGuest->insert($data);
                    
			        $view = new Zend_View();
			        $view->addScriptPath('../application/modules/default/views/helpers/');              
			        $view->assign("text_message",$message);
                    
                    $body = $view->render("mail_ajaxsendfriend.phtml");
			        $subject = "Voici un article conseill� par ".$name;
				 
			        $mail = new Zend_Mail();
			        $mail->setBodyHtml(utf8_decode($body));
			        $mail->setFrom($fromEmail, $fromName);
			        $mail->addTo($toEmail);
			        $mail->setSubject($subject);

			        $mail->send();
			        $this->log("L'email de conseille a �t� envoy� par : ".$fromEmail.", ".$fromName." � ".$toEmail,'info');
 
		        } catch (Zend_Exception $e) {
			        $this->log($e->getMessage(),'err');
		        }      
             
                $message = "Le mail � �t� envoy� � <b>".$email."</b>.";
                $isSuccess = true;
            }    
        }
        
        $this->view->message = $message;
        $this->view->isSuccess = $isSuccess;
        
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
    }
        
	public function nosmarquesAction() {        
		$this->view->title = 'Nos marques';
        $brand = new SupplierBrend();
        $this->view->brends = $brand->getAllShowableBrends();
    }
    
	public function nosmarquesdetailAction() {   
		$this->view->title = 'Nos marques'; 
        if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
            if ($id > 0) {
                try {
                    $brand = new SupplierBrend();
                    $brendData = $brand->getBrendByID($id);
                    $this->view->brends = $brendData;
                    $this->view->title = 'Nos marques - '.$brendData["BREND"]; 
		        } catch (Zend_Exception $e) {
			        $this->log("Error nosmarquesdetailAction : ".$id." : ".$e->getMessage(),'err');
                    $this->_forward('nosmarques','produits');
		        }
            } 
        }else {
            $this->_forward('nosmarques','produits');
        }
    }
    
	public function ajaxshowchildqtepriceAction() {
		$this->view->detailProductQte = array();
		$id = (int)$this->getRequest()->getParam('id');
		if ($id > 0) {
			$productChildQte = new ProductChildQte();
			$detailProductQte = $productChildQte->getAllActiveByItem($id);
				
			//Calcul des promos pour le prix degressif
			$productChild = new ProductChild();
			$childs = $productChild->getChildsInfoByListId($id);
			$promo = new PromoCalculator();
			$facture = new Facture();
			foreach ($detailProductQte AS $row) {
				$factureLine = new FactureLine();
				$childs[0]["PRIX"] = $row["PRIX"];
				$factureLine->setLineInfo($childs[0], 1, "N");
				$factureLine->setPromoCaddyType(false);
				$facture->addLine($factureLine);
				$promo->computeAllPromos($facture, null);
				$row["PRIX"] = $factureLine->getPrixTotalHT(true);
			}
				
			if (!empty($detailProductQte)) {
				$this->view->detailProductQte = $detailProductQte;
			}
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}
	public function ajaxshowallchildsAction() {
		$id = (int)$this->getRequest()->getParam('id');
		if ($id > 0) {
			$myProduct = $this->computeProductDetail($id);
			if ($myProduct) {
				$this->view->detailProduct = $myProduct;
				$category = new Category();
				$categoryFirst = $category->getParentFirstOf($myProduct['IDCATEGORY']);
				$this->view->actualDesign = $this->showDesign($categoryFirst['ID'], $categoryFirst);
			} else {
				$this->view->detailProduct = array();
				$this->view->actualDesign = array();
			}
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}

	public function ajaxcodereductionAction() {
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();

			$codeReduc = $filter->filter($params['codeReduc']);
			$this->view->messageSuccessReduc = "NOK";

			$user_namespace = $this->getSession();
			if (isset($user_namespace->urlCurrentProduct) && !empty($user_namespace->urlCurrentProduct)) {
				$this->view->urlCurrentProduct = $user_namespace->urlCurrentProduct;
			}

			if ($validator->isValid($codeReduc)) {

				$codeReduction = new CodeReduction();
				$resultCode = $codeReduction->getVerifyCodeBy($codeReduc);
				if (isset($resultCode) && !empty($resultCode)) {
					if ($resultCode['isACTIF'] == 1) {

						$usernamespace =  $this->getSession();
							
						$myFacture = $usernamespace->myFactureValidate;

						$myFacture->code_reduction = $resultCode;

						$myFacture->code_reduction['EURO'] = $myFacture->getPrixCodeReduction();
						$usernamespace->myFactureValidate = $myFacture;
						$this->view->messageSuccessReduc = "OK";
						$this->view->messageMessReduc = "Le code de r�duction est disponible";
					} else { $this->view->messageMessReduc = "Le code de r�duction n'est pas actif"; }
				} else { $this->view->messageMessReduc = "Le code de r�duction n'est plus disponible"; }
			} else {
				$usernamespace =  $this->getSession();
				$myFacture = $usernamespace->myFactureValidate;
				$myFacture->code_reduction = array();
				$usernamespace->myFactureValidate = $myFacture;

				$this->view->messageMessReduc = "Le code de r�duction n'est pas valide";
			}
		}
		$this->computeMonPanier();
		$this->_forward('ajaxcaddy','ajax');
	}

	private function computeLivraison ($totalHT) {
		$result = array();
		$result['fraisLivEUR'] = 0;
		$result['fraisLivPOUR'] = 0;
		$result['francoEur'] = 0;
		$result['resteFrancoLiv'] = 0;
		$promoCommand = new PromoCommand();
		try {
			$fraisCMD = $promoCommand->fetchAll('MONTANTFRAISCMD IS NOT NULL','MONTANTFRAISCMD ASC')->toArray();
			if ($fraisCMD) {
				foreach ($fraisCMD as $rowFrais) {
					if ($totalHT < $rowFrais['MONTANTFRAISCMD']) {
						if ($rowFrais['REMISEEURO'] > 0) {
							$result['fraisLivEUR'] = $rowFrais['REMISEEURO'];
						} else if ($rowFrais['REMISEPOUR'] > 0) {
							$result['fraisLivEUR'] = sprintf("%.2f", ($totalHT * $rowFrais['REMISEPOUR']) / 100);
							$result['fraisLivPOUR'] = $rowFrais['REMISEPOUR'];
						}
						break;
					}
				}
				foreach ($fraisCMD as $rowFrais) {
					$result['francoEur'] = $rowFrais['MONTANTFRAISCMD'];
				}
					
				if($totalHT < $result['francoEur']) {
					$result['resteFrancoLiv'] = $result['francoEur'] - $totalHT;
				}
			}
		} catch (Zend_Exception $e) {
			$this->log("Error computeOldLivraison : ".$e->getMessage(),'err');
		}
		return $result;
	}

	public function monpanierAction() {
		if ($this->getRequest()->getParam('paypalVerifError')) {
			$this->view->paypalVerifError = "Votre commande n'a pas �t� prise en compte, rev�rifier vos informations";
		}

		$user_namespace = $this->getSession();

		if (isset($user_namespace->urlCurrentProduct) && !empty($user_namespace->urlCurrentProduct)) {
			$this->view->urlCurrentProduct = $user_namespace->urlCurrentProduct;
		}
        
		$this->view->title = 'Mon Panier';
		$this->view->etapeCommande = 1;
		$linksMenu = array();
		$linksMenu[0]['NAVURL'] = '/mon-panier.html';
		$linksMenu[0]['NAVNOM'] = 'Mon Panier';

		$this->view->linksMenu = $linksMenu;

		$this->saveCaddyTemp();

		$this->computeMonPanier();
        
	}

	private function saveCaddyTemp() {

		$userNamespace = $this->getSession();
		if (isset($userNamespace->myObjectCaddy) && !empty($userNamespace->myObjectCaddy)) {
			$myCaddy = $userNamespace->myObjectCaddy;
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			if ($auth->hasIdentity() && isset($storage['user']) && !empty($myCaddy->items)) {
				$caddyTemp = new CaddyTemp();
				$caddyTemp->delete('USERID = '.$storage['user']['id']);

				foreach ($myCaddy->items as $item) {
					$data = array (
						'CHILDID' => $item->idChild,
						'CHILDQUANTITY' => $item->qteChild,
						'PRODUCTID' => $item->idProduit,
						'PRODUCTNOM' => $item->nom,
						'DESCSHORT' => $item->descshort,
						'NAVNOM' => $item->navnom,
						'URL' => $item->url,
						'DESIGNATION' => $item->designation,
						'USERID' => $storage['user']['id'],
						'SELECTEDOPTION' => $item->selectedOption 
					);

					$caddyTemp->insert($data);
				}
                
                if ($this->carte_fidelite_enabled) {
                    $carteFidelite = new CarteFidelite();
                    $this->view->myCaddyFideliteAvailable = $carteFidelite->getAnnoncesByAvailability($storage['user']['id']);
                    $this->view->myCaddyFideliteAllExceptCurrents = $carteFidelite->getAnnoncesByAvailabilityWithoutCurrent($storage['user']['id']);
                    $this->view->myUserFideliteInfo = $carteFidelite->getInfosByUser($storage['user']['id']);
                }
			}
		}
	}

	private function generateFacture($facture, $caddy) {
		foreach($caddy->items as $item) {
			$optionList = new OptionList();
			$productChild = new ProductChild();
			$results = $productChild->getChildsInfoByListId($item->idChild);
			foreach ($results AS $row) {
				$myItem = $caddy->getItemByIdAndOption($row['IDCHILD'], $item->selectedOption);

				if ($myItem != null) {
					$factureLine = new FactureLine();
					$factureLine->setLineInfo($row, $myItem->qteChild, $myItem->isAccessoire);

					$factureLine->item_selectedOption = $myItem->selectedOption;
						
					$factureLine->product_navnom = $this->verifyNavigationString($factureLine->product_navnom, $factureLine->product_nom, '');

					$factureLine->setPromoCaddyType(false);

					$facture->addLine($factureLine);
				}
			}
		}   
        
		$userNamespace = $this->getSession();    
        if (isset($userNamespace->myObjectCaddyFidelite) && !empty($userNamespace->myObjectCaddyFidelite)) {
            $fidelitegifts = $userNamespace->myObjectCaddyFidelite;
		        foreach($fidelitegifts->items as $item) {
			        $factureLine = new FactureLine();
			        $factureLine->setFideliteGift($item);
                    $facture->addFideliteLine($factureLine);
                }
        }
                
	}

	private function generateFactureCaddyType($facture, $caddy) {
		$userCaddyType = new UserCaddyType();
		foreach($caddy->itemsCaddyType as $item) {
			$results = $userCaddyType->getArticleByCaddyIdList($item->id);
			foreach ($results AS $row) {
				$myItem = $caddy->getItemCaddyTypeByIdChildAndOption($row['IDCHILD'], $item->selectedOption);
				if ($myItem != null && ($row['REMISEEURO'] > 0 || $row['REMISEPOUR'] > 0)) {

					$factureLine = new FactureLine();
					$factureLine->product_navnom = $this->verifyNavigationString($factureLine->product_navnom, $factureLine->product_nom, '');
					$factureLine->setLineInfo($row, $myItem->qte, 'N');
					$factureLine->caddytype_id = $myItem->id;
						
					$factureLine->item_selectedOption = $myItem->selectedOption;

					if ($row['REMISEEURO'] > 0) {
						$factureLine->remise_euro = $row['REMISEEURO'];
						$factureLine->setPromoCaddyType(true);
						$factureLine->caddytype_isActif = 'Y';
					} else if ($row['REMISEPOUR'] > 0) {
						$factureLine->remise_pour = $row['REMISEPOUR'];
						$factureLine->setPromoCaddyType(true);
						$factureLine->caddytype_isActif = 'Y';
					}

					if ($factureLine->isCaddyTypeActif()) {
						$poidsCurrent = $factureLine->getPoidsTotal();
						if ($poidsCurrent > 0) { $facture->total_poids += $poidsCurrent ;
						} else { $facture->isAncienPoids = true;  }
						if ($factureLine->isFrancoDenied()) { $facture->isFrancoDenied = true; }

						$facture->total_HT_HR += $factureLine->getPrixTotalHT(true);

						$facture->addLine($factureLine);
					}
				}
			}
		}
	}
		
	private function computeFactureGlobalByQteDegressif($myFacture) {
		$productChildQte = new ProductChildQte();
		$productChild = new ProductChild();
		foreach ($myFacture->facture_lines as $lines) {
			$result = $productChild->getChildPriceByIdChild($lines->item_id);
			$currentPrice = $productChildQte->getCurrentPrice($lines->item_id, $lines->item_qte, $result['PRIX']);
			$lines->item_prix = sprintf("%.2f",$currentPrice);
		}
	}

	public function computeMonPanier() {
		$userNamespace = $this->getSession();
		$myCaddyTemp = $userNamespace->myObjectCaddy;
		if ((isset($myCaddyTemp->items) && !empty($myCaddyTemp->items)) ||
		(isset($myCaddyTemp->itemsCaddyType) && !empty($myCaddyTemp->itemsCaddyType))) {

			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$user = array();
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$user = $storage['user'];
			}

			$myFacture_CodeReduc = array();
			if (isset($userNamespace->myFactureValidate)) {
				$myFacture = $userNamespace->myFactureValidate;
				if (isset($myFacture->code_reduction) && !empty($myFacture->code_reduction)) {
					$myFacture_CodeReduc = $myFacture->code_reduction;
				}
			}

			$myFacture = new Facture();

			$userNamespace->myFactureValidate = $myFacture;

			$resteFrancoLiv = 0;

			$this->generateFacture($myFacture, $myCaddyTemp);
			if (isset($user) && !empty($user) && $user['iscaddytype'] == 'Y') {
				//Panier Type apres le calcul des promos
				$this->generateFactureCaddyType($myFacture, $myCaddyTemp);
			}
			/*Recuperation du prix degressif*/
			$this->computeFactureGlobalByQteDegressif($myFacture);

			$myFacture->code_reduction = $myFacture_CodeReduc;

			/*
			 * CALCUL DES PROMOS
			 */
			$promo = new PromoCalculator();
			$promo->computeAllPromos($myFacture, $user);

			$resteToValid = $promo->getPrixCommandValidation($myFacture);
			if ($resteToValid > 0) {
				$this->view->isCommandValid = "Vous ne pouvez pas valider votre commande,<br/> il vous manque la somme de <b>".$resteToValid."</b> euros, pour atteindre le <b>minimum requis</b>.";
			}

			$myFacture->total_HT = $myFacture->getPrixTotalHT();

			/*
			 * MODE DE LIVRAISON
			 */

			//Calcul des frais de livraison
			$lastFraisLivEur = 0;

			$arrayLivraison = $this->computeLivraison($myFacture->total_HT);
			if (isset($arrayLivraison) && !empty($arrayLivraison)) {
				if ($myFacture->total_HT == 0) {
					$myFacture->total_frais_port = sprintf("%.2f", 0);
					$myFacture->total_frais_port_pour  = 0;
				} else {
					$myFacture->total_frais_port = $arrayLivraison['fraisLivEUR'];
					$myFacture->total_frais_port_pour  = $arrayLivraison['fraisLivPOUR'];
				}

				$lastFraisLivEur  = $arrayLivraison['francoEur'];
				$resteFrancoLiv  = $arrayLivraison['resteFrancoLiv'];
			}

			$myFacture->total_HT_FP = $myFacture->getPrixTotalHT_FP(false);
			$myFacture->total_TVA = $myFacture->getPrixTotalTVA(false);
			$myFacture->total_TTC = $myFacture->getPrixTotalTTC(false);
			$myFacture->total_remise = $myFacture->getPrixRemise();

			$myFacture->resteFrancoLiv = $resteFrancoLiv;
			if ($myFacture->resteFrancoLiv > 0) {
				$this->view->resteFrancoLiv = "Il vous reste <b>".number_format(sprintf("%.2f", $myFacture->resteFrancoLiv), 2, ',', ' ')."</b> euros, avant d'avoir le franco de port.";
			}
            
			if ($this->carte_fidelite_enabled) {
                $carteFidelite = new CarteFidelite();
                $myUserFideliteInfo = $carteFidelite->getInfosByUser($user['id']);                
                if (!$myFacture->isCarteFidelitePointsValid($myUserFideliteInfo['POINTFIDELITETOTAL'])) {
                	$this->view->isCommandValid = "Vous ne pouvez pas valider votre commande,<br/> vous n'avez pas assez de <b>points fid�lit�</b>.";
			    }
			}
            
			$userNamespace->myFactureValidate = $myFacture;
			$this->view->myFacture = $myFacture;
			$this->view->user_facture_validate = $myFacture;
            
		} else {
			$userNamespace->myFactureValidate = new Facture();
			$userNamespace->myObjectCaddy = new Caddy();
			$this->view->myFacture = $userNamespace->myFactureValidate;
			$this->view->user_facture_validate = $userNamespace->myFactureValidate;
            
		}
	}



	public function formatNumber($number) {
		return number_format($number, 2, ',', ' ');
	}

	public function getCaddyProducts($myCaddyTemp) {

		$i = 0;
		foreach($myCaddyTemp->items as $item) {
			if ($i == 0 ) {
				$stringTempP = $item->idProduit;
				$stringTempC = $item->idChild;
			} else {
				$stringTempP .= ', '.$item->idProduit;
				$stringTempC .= ', '.$item->idChild;
			}
			$i++;
		}



		$sql = "
			SELECT p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.ID IDPRODUCT, pic.URL URL,p.isPROMO isPROMO, pc.DESIGNATION DESIGNATION, p.STOCK STOCK,
			pc.ID IDCHILD, pc.REFERENCE REFERENCE, pc.isDEVIS isDEVIS, pc.isPROMO isPROMOCHILD, pc.PRIX PRIX, p.DATEPROMO DATEPROMO,
			p.IDCATEGORY IDCATEGORY, p.IDBREND IDBREND, p.isSHOWBREND isSHOWBREND, pc.QUANTITYMIN QUANTITYMIN, pc.POIDS POIDS, pc.isFRANCODENIED isFRANCODENIED
			FROM product p
			LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
			LEFT JOIN productchild pc ON pc.IDPRODUCT = p.ID
			WHERE p.ID IN ( ".$stringTempP." )
			AND pc.ID IN ( ".$stringTempC." )
			AND p.isACTIVE = 0
			AND pic.POSITION = 1
			";


		$product = new Product();
		$result = $product->getAdapter()->fetchAll($sql);


		$promoProduct = new PromoProduct();
		$i = 0;

		$childRefBuy = '';
		$myTemp = array();
		foreach ($result AS $row) {

			$myItem = $myCaddyTemp->getItemById($row['IDCHILD']);

			if ($myItem != null)
			{
				$myTemp[$i]['CHILD']['isACCESSOIRE'] = $myItem->isAccessoire;

				$myTemp[$i]['CHILD']['ID'] = $row['IDCHILD'];
				$myTemp[$i]['CHILD']['REFERENCE'] = $row['REFERENCE'];
				$myTemp[$i]['CHILD']['DESIGNATION'] = $row['DESIGNATION'];
				$myTemp[$i]['CHILD']['isPROMO'] = $row['isPROMOCHILD'];
				$myTemp[$i]['CHILD']['isDEVIS'] = $row['isDEVIS'];
				$myTemp[$i]['CHILD']['POIDS'] = $row['POIDS'];
				$myTemp[$i]['CHILD']['isFRANCODENIED'] = $row['isFRANCODENIED'];
				$myTemp[$i]['CHILD']['QUANTITYMIN'] = $row['QUANTITYMIN'];
				$myTemp[$i]['CHILD']['PRIX'] = sprintf("%.2f",$row['PRIX']);
				$myTemp[$i]['CHILD']['REMISEEURO'] = 0;
				$myTemp[$i]['CHILD']['REMISEPOUR'] = 0;

				$myTemp[$i]['CHILD']['QUANTITY'] = $myItem->qteChild;

				//Insertion du code pour la gestion des promos
				$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX']);

				if ($row['isPROMOCHILD'] == 0) {
					//Produit - REFERENCE
					$myPromo = $promoProduct->fetchRow("REFERENCE = '".$row['REFERENCE']."'");
					if ($myPromo['REMISEEURO'] > 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX'] - $myPromo['REMISEEURO']);
					}
					if ($myPromo['REMISEPOUR'] > 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX'] - (($row['PRIX'] * $myPromo['REMISEPOUR']) / 100));
					}

					if ($myTemp[$i]['CHILD']['PROMOPRIX'] < 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX']);
					}
				}

				if ($myTemp[$i]['CHILD']['isDEVIS'] == 0) {
					$myTemp[$i]['CHILD']['PRIX'] = 0;
					$myTemp[$i]['CHILD']['PROMOPRIX'] = 0;
				}

				$myTemp[$i]['PRODUIT']['ID'] = $row['IDPRODUCT'];
				$myTemp[$i]['PRODUIT']['NOM'] = $row['NOM'];
				$myTemp[$i]['PRODUIT']['DESCSHORT'] = $row['DESCSHORT'];
				$myTemp[$i]['PRODUIT']['isPROMO'] = $row['isPROMO'];
				$myTemp[$i]['PRODUIT']['IDBREND'] = $row['IDBREND'];
				$myTemp[$i]['PRODUIT']['isSHOWBREND'] = $row['isSHOWBREND'];
				$myTemp[$i]['PRODUIT']['IDCATEGORY'] = $row['IDCATEGORY'];
				$myTemp[$i]['PRODUIT']['DATEPROMO'] = $row['DATEPROMO'];
				$myTemp[$i]['PRODUIT']['STOCK'] = $row['STOCK'];

				$myTemp[$i]['PRODUIT']['NAVNOM'] = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$myTemp[$i]['PRODUIT']['URL'] = $row['URL'];


				$i++;
			}
		}
		return $myTemp;

	}


	public function ajaxaddpanierAction() {
		if ($this->getRequest()->isPost('productAddForm')) {
			$params = $this->getRequest()->getPost();

			$idProduct = $params['idProd'];

			for ($i = 0; $i < $params['nbr']; $i++) {
				if (isset($params['idChild_'.$i])) {
					$idchild = $params['idChild_'.$i];

					if (isset($params['quantity_'.$idchild])) {
						$qte = intval($params['quantity_'.$idchild]);
						$quantityMin = intval($params['qtyMinChild_'.$i]);
						$isAccessoire = $params['isAccessoire_'.$i];
						$selectedOptionValue = '';
						if (isset($params['selectedOption_'.$i]) && !empty($params['selectedOption_'.$i])) {
							$selectedOptionValue = $params['selectedOption_'.$i];
						}

						if ($qte > 0) {

							$qte = $this->computeQtyMin($qte, $quantityMin);

							$this->ajouterArticle( $idchild, $qte, $isAccessoire, $selectedOptionValue);
							$this->view->messageError = '';
							$this->view->messageSuccess = "Le produit a &eacute;t&eacute; ajout&eacute; &agrave; votre panier";
						} else {
							$this->supprimerArticle($idchild, $selectedOptionValue);
							$this->view->messageSuccess = "Votre panier a &eacute;t&eacute; actualis&eacute;";
							$this->view->messageError = '';
						}
					}
				}
			}

		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}

	public function ajaxcountcaddyAction() {
		$userNamespace = $this->getSession();
		$myCaddy = $userNamespace->myObjectCaddy;
		$nbArticles = 0;
		if (isset($myCaddy->items)) {
			$nbArticles=count($myCaddy->items);
		}
		if ($nbArticles > 1) {
			$this->view->messageSuccess = $nbArticles.' PRODUITS';
		} else if ($nbArticles == 0) {
			$this->view->messageSuccess = 'Aucun produit';
		} else {
			$this->view->messageSuccess = $nbArticles.' PRODUIT';
		}
		$this->_forward('ajaxvalue', 'ajax');
	}
	/*
	 * Caddy
	 *
	 */
	public function ajaxcheckcaddyAction() {
		if ($this->getRequest()->isPost('caddyCheckForm')) {
			$params = $this->getRequest()->getPost();

			if (isset($params['Child'],$params['Quantity'])) {
				$listChild = $params['Child'];
				$listQuantity = $params['Quantity'];
				$listQuantityMin = $params['QuantityMin'];
				$listAcc= $params['Accessoire'];
				$listCaddyType= $params['CaddyType'];
				$listSelectedOption= $params['selectedOption'];

				for ($i = 0; $i < sizeof($listChild); $i++) {
					if (isset($listChild[$i],$listQuantity[$i])) {
						$idchild = intval($listChild[$i]);
						$qte = intval($listQuantity[$i]);
						$quantityMin = intval($listQuantityMin[$i]);
						$isAccessoire = $listAcc[$i];
						$idCaddyType = intval($listCaddyType[$i]);
						$selectedOption = $listSelectedOption[$i];

						if ($qte > 0) {
							$qte = $this->computeQtyMin($qte, $quantityMin);

							if ($idCaddyType > 0) {
								$this->ajouterArticleCaddyType($idCaddyType, $qte, $selectedOption);
							} else {
								$this->ajouterArticle($idchild, $qte, $isAccessoire, $selectedOption);
							}
							$this->view->messageError="";
							$this->view->messageSuccess = "Votre caddy a &eacute;t&eacute; modifi&eacute;";
						} else {
							if ($idCaddyType > 0) {
								$this->supprimerArticleCaddyType($idCaddyType, $selectedOption);
							} else {
								$this->supprimerArticle($idchild, $selectedOption);
							}
						}
					}
				}
			}
		}

		$this->_forward('ajaxmessage','ajax');
	}

	private function computeQtyMin($qte, $qteMin)
	{
		$reste = $qte % $qteMin;
		$value = ($qte - $reste) / $qteMin;

		if ($reste != 0) {
			$value++;
		}
		$result = $qteMin * $value;
		return $result;
	}



	private function ajouterArticleCaddyType($idCaddyType, $qteChild, $selectedOption){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->addItemToCaddyType($idCaddyType, $qteChild, $selectedOption);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function ajouterArticle($idChild, $qteChild, $isAccessoire, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->addItemToCaddy($idChild, $qteChild, $isAccessoire, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function supprimerArticle($idChild, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->delItemToCaddy($idChild, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function supprimerArticleCaddyType($idCaddyType, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->delItemToCaddyType($idCaddyType, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function computeProductChildsList($id, $idCat, $idBrend) {
		$myListChild = array();
		try {
			$productChild = new ProductChild();
			$productChildTemp = $productChild->getProductChildsByIdProduct($id);

			$myListChild = $this->computeProductChildsListArray($productChildTemp, $idCat, $idBrend);
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		return $myListChild;
	}


	private function computeProductChildsListArray($productChilds, $idCat, $idBrend) {
		$myListChild = array();
		try {
			$i = -1;
			$actualChild = 0;

			$isAllPromos = false;
			$currentPromoAll = array();
			$currentPromo = array();
			$listUserCodeInternIdBrendFound = array();
			$listUserCodeInternIdBrends = array();
			$listIdBrendFound = array();
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
			$listIdBrends = array();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$promoUser = new PromoUser();

            $user = array();
            try {
			    $auth = Zend_Auth::getInstance();
			    $auth->setStorage($this->getSessionStorage());
			    $storage = $auth->getStorage()->read();
			    if ($auth->hasIdentity() && isset($storage['user'])) {
				    $user = $storage['user'];
                }
            }
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(), 'err');
            }


			if (!empty($productChilds)) {
				$idCategory = $idCat;
				$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
				if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
			}

			$userNamespace = $this->getSession();
			$myCaddy = $userNamespace->myObjectCaddy;
				
			$productChildQte = new ProductChildQte();
			foreach ($productChilds as $child) {
				if ($child['ID'] != $actualChild) {
					$i++;
					/* Prix Unitaire par Quantite*/
					$myListChild[$i]['QTEPRIXITEM'] = $productChildQte->getQteByItem($child['ID']);
					$myListChild[$i]['isQTEPRIXACTIVE'] = $child['isQTEPRIXACTIVE'];
					$child['PRIX'] = $productChildQte->getCurrentPrice($child['ID'], $myCaddy->getQuantity($child['ID']), $child['PRIX']);
						
					$myListChild[$i]['ID'] = $child['ID'];
					$myListChild[$i]['PRODUCTNAVNOM'] = $this->verifyNavigationString($child['PRODUCTNAVNOM'], $child['PRODUCTNOM'], '') ;
					$myListChild[$i]['PRODUCTNOM'] = $child['PRODUCTNOM'];
					$myListChild[$i]['PRODUCTID'] = $child['PRODUCTID'];
					$myListChild[$i]['REFERENCE'] = $child['REFERENCE'];
					$myListChild[$i]['DESIGNATION'] = $child['DESIGNATION'];
					$myListChild[$i]['PRIX'] = sprintf("%.2f",$child['PRIX']);
					$myListChild[$i]['isPROMO'] = $child['isPROMO'];
					$myListChild[$i]['isDEVIS'] = $child['isDEVIS'];
					$myListChild[$i]['QUANTITYMIN'] = $child['QUANTITYMIN'];

					$myListChild[$i]['PROMOPRIX'] = '';
					if ($child['isPROMO'] == 0) {
						$myPromo = $promoProduct->fetchRow("REFERENCE = '".$child['REFERENCE']."'");
						if ($myPromo['REMISEEURO'] > 0) {
							$myListChild[$i]['PROMOPRIX'] = sprintf("%.2f",$child['PRIX'] - $myPromo['REMISEEURO']);
						}
						if ($myPromo['REMISEPOUR'] > 0) {
							$myListChild[$i]['PROMOPRIX'] = sprintf("%.2f",$child['PRIX'] - (($child['PRIX'] * $myPromo['REMISEPOUR']) / 100));
						}
						if ($myListChild[$i]['PROMOPRIX'] < 0) { $myListChild[$i]['PROMOPRIX'] = 0; }
					}

					$myListChild[$i]['IMAGEPROMO'] = $child['IMAGEPROMO'];
					$myListChild[$i]['OPTION_VALUES'] = array();
					$actualChild = $child['ID'];


					/*
					 * CALCUL PROMO
					 */

					if (!in_array($idBrend, $listIdBrends, true)) {
						$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
						array_push($listIdBrends, $idBrend);
						if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
					}
					if ($child['isPROMO'] == 1) {
						$isRemise = false;
						if (in_array($idBrend, $listIdBrends, true)) {
							foreach ($listIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend) {
									$myListChild[$i]['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
						if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
							$myListChild[$i]['isPROMO'] = 0;
							if ($currentPromoAll['REMISEEURO'] > 0) {
								$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromoAll['REMISEEURO']);
							}
							if ($currentPromoAll['REMISEPOUR'] > 0) {
								$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromoAll['REMISEPOUR']);
							}
						}
					}
					if (isset($user) && !empty($user)) {
						$userId = $user['id'];
						$codeIntern = $user['cintern'];
						$isRemise = false;

						if (!empty($codeIntern)) {
							if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
								$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
								array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
								if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
							}
							if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
								foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
									if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
										$myListChild[$i]['isPROMO'] = 0;
										$currentPromo = $brendPromos['PROMO'];
										if ($currentPromo['REMISEEURO'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
											$isRemise = true;
										}
										if ($currentPromo['REMISEPOUR'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
											$isRemise = true;
										}
										break;
									}
								}
							}
						}
						if (!$isRemise) {
							if (!in_array($idBrend, $listUserIdBrends, true)) {
								$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
								array_push($listUserIdBrends, $idBrend);
								if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
							}
							if (in_array($idBrend, $listUserIdBrends, true)) {
								foreach ($listUserIdBrendFound as $brendPromos) {
									if ($brendPromos['ID'] == $idBrend) {
										$myListChild[$i]['isPROMO'] = 0;
										$currentPromo = $brendPromos['PROMO'];
										if ($currentPromo['REMISEEURO'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
											$isRemise = true;
										}
										if ($currentPromo['REMISEPOUR'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
											$isRemise = true;
										}
										break;
									}
								}
							}
						}
					}
					if ($myListChild[$i]['PROMOPRIX'] < 0) { $myListChild[$i]['PROMOPRIX'] = $myListChild[$i]['PRIX']; }
				}
				$myListChild[$i]['OPTION_VALUES'][$child['OPTIONID']]['OPTIONVALUE'] = $child['OPTIONVALUE'];
				$myListChild[$i]['OPTION_VALUES'][$child['OPTIONID']]['OPTIONID'] = $child['OPTIONID'];
			}

		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		return $myListChild;
	}

	private function checkTypeOfPromo($id) {
		$category = new Category2();
		$firstCategory = $category->getParentFirstOf($id);
		if ($firstCategory != null) {
			$currentId = $firstCategory["ID"];
			if ($currentId == 2) { $this->view->prefixPromoClass = "eco-"; }
		}
	}

	private function computeProductDetail($id) {
		try {
			$product = new Product();

			//Get Product
			$productTemp = $product->getProductById($id);

            $currentUser = array();
            try {
                $auth = Zend_Auth::getInstance();
                $auth->setStorage($this->getSessionStorage());
                $storage = $auth->getStorage()->read();
                if ($auth->hasIdentity() && isset($storage['user'])) {
                    $currentUser = $storage['user'];
                }
            }
            catch (Zend_Exception $e) { }

			if ($productTemp) {
				//Get Picture
				$picture = new Picture();
				$productPics = $picture->getAllByIdProduct($id);

				//Produits Annexe
				$productAnnexe = new ProductAnnexe();
				$productList = $productAnnexe->getAnnexesByProductID($id, 'NOM ASC');
				$listAnnexes = $this->computeProductListToShow($productList, $currentUser);
				$this->view->listAnnexes = $listAnnexes['PRODUCTS'];

				//Produits Accessoire
				$productAccessoire = new ProductAccessoire();
				$listAccessoires = $productAccessoire->getAccessoiresOptionsByProductID($id, 'NOM ASC');

				$listAccessoireChilds = $this->computeProductChildsListArray($listAccessoires, $productTemp[0]['IDCATEGORY'], $productTemp[0]['IDBREND']);

				$myProduct = array();

				$myProduct['PRODUCT_ACCESSOIRE'] = $listAccessoireChilds;

				if ($product->isInCategorySubsidiaire($productTemp[0]['ID'], 2)) {
					$this->view->prefixPromoClass = "eco-";
				}

				$myProduct['ID'] = $productTemp[0]['ID'];
				$myProduct['NOM'] = $productTemp[0]['NOM'];

				$myProduct['NAVNOM'] = $this->verifyNavigationString( $productTemp[0]['NAVNOM'], $productTemp[0]['NOM'], "");

				$myProduct['NAVTITRE'] = $productTemp[0]['NAVTITRE'];
				$myProduct['NAVDESC'] = $productTemp[0]['NAVDESC'];

				if (empty($myProduct['NAVTITRE'])) {
					$myProduct['NAVTITRE'] = $myProduct['NOM'];
				}
				if (empty($myProduct['NAVDESC'])) {
					$myProduct['NAVDESC'] = $productTemp[0]['DESCSHORT'];
				}
				$myProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($productTemp[0]);

				$myProduct['KEYWORDS'] = $productTemp[0]['KEYWORDS'];
				$myProduct['DESCSHORT'] = $productTemp[0]['DESCSHORT'];
				$myProduct['DESCLONG'] = $productTemp[0]['DESCLONG'];
				$myProduct['DESCNORME'] = $productTemp[0]['DESCNORME'];
				$myProduct['DESCTECH'] = $productTemp[0]['DESCTECH'];
				$myProduct['PRIX'] = sprintf("%.2f",$productTemp[0]['PRIX']);
				$myProduct['PRIXLOWEST'] = $product->calculateLowestPrice($productTemp[0]['ID']);
				$myProduct['isPROMO'] = $productTemp[0]['isPROMO'];
				$myProduct['IDCATEGORY'] = $productTemp[0]['IDCATEGORY'];
				$myProduct['CATNOM'] = $productTemp[0]['CATNOM'];
				$myProduct['CATNAVNOM'] = $productTemp[0]['CATNAVNOM'];
				$myProduct['URL'] = $productTemp[0]['URL'];
				$myProduct['BREND'] = $productTemp[0]['BREND'];
				$myProduct['IDBREND'] = $productTemp[0]['IDBREND'];
				$myProduct['isSHOWBREND'] = $productTemp[0]['isSHOWBREND'];
				$myProduct['BRENDURL'] = $productTemp[0]['BRENDURL'];
				$myProduct['isDEVISPRODUCT'] = $productTemp[0]['isDEVISPRODUCT'];
				$myProduct['DOCNAME'] = $productTemp[0]['DOCNAME'];
				$myProduct['DOCURL'] = $productTemp[0]['DOCURL'];
				$myProduct['STOCK'] = $productTemp[0]['STOCK'];
				$myProduct['isQTEPRIXACTIVE'] = $productTemp[0]['isQTEPRIXACTIVE'];
				$myProduct['BOOSTED_BESTSELLER'] = $productTemp[0]['BOOSTED_BESTSELLER'];

				$myProduct['ONSELECT_IDOPTION'] = $productTemp[0]['ONSELECT_IDOPTION'];
				if ($myProduct['ONSELECT_IDOPTION'] > 0) {
					$optionList = new OptionList();
					$myProduct['ONSELECT_OPTION'] = $optionList->getByIdProduct($myProduct['ID']);
				}

				$myProduct['LISTPICS'] = $productPics;

				$i = 0;
				$myProduct['LISTOPTION'] = array();
				foreach ($productTemp as $option) {
                    $hasOption = false;
                    foreach ($myProduct['LISTOPTION'] as $current_option) {
                        if ($current_option['IDOPTION'] == $option['IDOPTION']) {
                            $hasOption = true;
                            break;
                        }
                    }
                    if (!$hasOption) {
                        $myProduct['LISTOPTION'][$i]['NOMOPTION'] = $option['NOMOPTION'];
                        $myProduct['LISTOPTION'][$i]['IDOPTION'] = $option['IDOPTION'];
                        $i++;
                    }
				}

				$myProduct['LISTCHILD'] = $this->computeProductChildsList($id, $myProduct['IDCATEGORY'], $myProduct['IDBREND']);

				return $myProduct;
			} else { return false;}
		} catch (Zend_Exception $e) {
			$this->log("ComputeProductDetail : "+$e->getMessage(), 'err');
		}
		return false;
	}
    
    private function checkForProductRedirection($row) {
	    $link = "";
	    if(isset($row['PRODUCT_URL'])) {
		    $link = "/".$row['PRODUCT_URL'];
	    } else if (isset($row['NAVNOM'])) {
		    $link = "/".Utils_Tool::getFormattedUrlProduct($row['NAVNOM_URLPARENTS'], $row['NAVNOM'], $row['ID']);
	    } else if (isset($row['PRODNAVNOM'])){
		    $link = "/".Utils_Tool::getFormattedUrlProduct($row['NAVNOM_URLPARENTS'], $row['PRODNAVNOM'], $row['ID']);
	    } 
        if ($this->FeatureRedirectionAuto) {
            $front = Zend_Controller_Front::getInstance();
            $currentpage = $front->getRequest()->getRequestUri();
            if ($link != $currentpage) {
                $this->send301Redirection($this->baseUrl_SiteCommerceUrl.$link);
            }
        }
        $this->setCanonicalUrl($this->baseUrl_SiteCommerceUrl.$link);
    }
    private function checkForCategoryRedirection($row) {
	    $link = "/".Utils_Tool::getFormattedUrlCategory($row['NAVNOM_URLPARENTS'], $row['NAVNOM'], $row['ID']); 
        if ($this->FeatureRedirectionAuto) {
            $front = Zend_Controller_Front::getInstance();
            $currentpage = $front->getRequest()->getRequestUri();
        
            if ($link != $currentpage) {
                $this->send301Redirection($this->baseUrl_SiteCommerceUrl.$link);
            }
        }
        $this->setCanonicalUrl($this->baseUrl_SiteCommerceUrl.$link);
    }

	public function detailAction()
	{
		if ($this->getRequest()->getParam('p')) {
			$id = (int)$this->getRequest()->getParam('p');

			if ($id>0) {
                $user_namespace = null;
				try {
					$user_namespace = $this->getSession();
	            } catch (Zend_Exception $e) {  
                
                }
	
				try {				
                    $myProduct = $this->computeProductDetail($id);

					if ($myProduct) {
                    
                        $this->checkForProductRedirection($myProduct);

                        if (isset($user_namespace) && !empty($user_namespace)){
						    $user_namespace->urlCurrentProduct = $this->getRequest()->getRequestUri();

						    $user_namespace->currentProductDetail = $myProduct;
                        }

						$category = new Category();

						$breadcrumb = $category->getTreeInLineOf($myProduct['IDCATEGORY']);

						$this->view->listFTFDS = $this->getFTFDSByIdProd($id);

						$this->view->breadcrumb = $breadcrumb;
                        
                        if (isset($user_namespace) && !empty($user_namespace)){
						    $user_namespace->currentProductDetailDesign = $this->showDesign($breadcrumb[0]['ID'], $breadcrumb[0]);
						    $this->view->actualDesign = $user_namespace->currentProductDetailDesign;
                        }
						$this->view->title = $myProduct['NAVTITRE'];

						$filter = new Zend_Filter();
						$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());
						$this->view->metadescription = $filter->filter($myProduct['NAVDESC']);
						$this->view->metakeywords = $myProduct['KEYWORDS'];

						$this->view->detailProduct = $myProduct;
                                                
                        $isProductOutOfStock = false;
                        if ($myProduct['STOCK'] == 4) {
                            $isProductOutOfStock = true;
                        }
                        $this->view->isProductOutOfStock = $isProductOutOfStock; 
                        
					} else { $this->log('Le produit est introuvable : '.$this->getRequest()->getRequestUri(), 'warn'); $this->_redirect('/'); }
				} catch (Zend_Exception $e) {  $this->log($e->getMessage(), 'err'); $this->_redirect('/');  }
			} else { $this->_redirect('/');  }
		}  else { $this->_redirect('/');  }
	}


	private function isPromoActive($myPromo) {
		if ($myPromo) {
			if ($myPromo['REMISEEURO'] > 0) { return true; }
			if ($myPromo['REMISEPOUR'] > 0) { return true; }
		}
		return false;
	}


	private function computeProductListToShowOld($list, $user) {
		$i = 0;
		$j = 1;
		$isFirst = true;
		$listProducts = array();
		$metakeywords = '';

		$isAllPromos = false;
		$currentPromoAll = array();
		$currentPromo = array();
		$listUserCodeInternIdBrendFound = array();
		$listUserCodeInternIdBrends = array();
		$listIdBrendFound = array();
		$listUserIdBrendFound = array();
		$listUserIdBrends = array();
		$listIdBrends = array();
		$promoCalculator = new PromoCalculator();
		$promoProduct = new PromoProduct();
		$promoUser = new PromoUser();
 
		if (!empty($list)) {
			$idCategory = $list[0]['CATID'];
			$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
			if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
             
		}

		foreach ($list AS $row) {
			if ($j == 9 ) {
				$j = 1;
				$i++;
				$isFirst = true;
			} else {
				if (!$isFirst) {
					$j++;
				}
			}

			$listProducts[$i][$j]['ID'] = $row['ID'];
			$listProducts[$i][$j]['NOM'] = $row['NOM'];
			$listProducts[$i][$j]['DESCSHORT'] = $this->cutString($row['DESCSHORT'], 80);
			$listProducts[$i][$j]['URL'] = $row['URL'];
			$listProducts[$i][$j]['BREND'] = $row['BREND'];
			$listProducts[$i][$j]['isSHOWBREND'] = $row['isSHOWBREND'];
			$listProducts[$i][$j]['BRENDURL'] = $row['BRENDURL'];
			$listProducts[$i][$j]['NBREFERENCE'] = $row['NBREFERENCE'];
			$listProducts[$i][$j]['isDEVISPRODUCT'] = $row['isDEVISPRODUCT'];
			$listProducts[$i][$j]['BOOSTED_BESTSELLER'] = $row['BOOSTED_BESTSELLER'];

			$listProducts[$i][$j]['NAVNOM'] = $this->verifyNavigationString($row['PRODNAVNOM'], $row['NOM'], '');
			$listProducts[$i][$j]['NAVNOM_URLPARENTS'] = $row['NAVNOM_URLPARENTS'];

			$listProducts[$i][$j]['NAVTITRE'] = $row['NAVTITRE'];
			$listProducts[$i][$j]['NAVDESC'] = $row['NAVDESC'];

			$isFirst = false;

			if (empty($metakeywords)) {
				$metakeywords .= $row['KEYWORDS_PROD'];
			} else {
				$metakeywords .= ','.$row['KEYWORDS_PROD'];
			}

			$listProducts[$i][$j]['isPROMO'] = $row['isPROMO'];
			$listProducts[$i][$j]['PRIX'] = $row['PRIX'];

			/*
			 * CALCUL PROMO
			 */
			$idBrend = $row['BRENDID'];

			if (!in_array($idBrend, $listIdBrends, true)) {
				$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
				array_push($listIdBrends, $idBrend);
				if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
			}
			if ($row['isPROMO'] == 1) {
				$isRemise = false;
				if (in_array($idBrend, $listIdBrends, true)) {
					foreach ($listIdBrendFound as $brendPromos) {
						if ($brendPromos['ID'] == $idBrend) {
							$listProducts[$i][$j]['isPROMO'] = 0;
							$currentPromo = $brendPromos['PROMO'];
							if ($currentPromo['REMISEEURO'] > 0) {
								$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
								$isRemise = true;
							}
							if ($currentPromo['REMISEPOUR'] > 0) {
								$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
								$isRemise = true;
							}
							break;
						}
					}
				}
				if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
					$listProducts[$i][$j]['isPROMO'] = 0;
					if ($currentPromoAll['REMISEEURO'] > 0) {
						$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
					}
					if ($currentPromoAll['REMISEPOUR'] > 0) {
						$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
					}
				}
			}
			if (isset($user) && !empty($user)) {
				$userId = $user['id'];
				$codeIntern = $user['cintern'];
				$isRemise = false;

				if (!empty($codeIntern)) {
					if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
						$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
						array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
						if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
					}
					if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
						foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
								$listProducts[$i][$j]['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
				}
				if (!$isRemise) {
					if (!in_array($idBrend, $listUserIdBrends, true)) {
						$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
						array_push($listUserIdBrends, $idBrend);
						if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
					}
					if (in_array($idBrend, $listUserIdBrends, true)) {
						foreach ($listUserIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend) {
								$listProducts[$i][$j]['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
				}
			}


			if ($listProducts[$i][$j]['PRIX'] <= 0 ) { $listProducts[$i][$j]['PRIX'] = $row['PRIX']; }
		}
		return $result = array( 'PRODUCTS' => $listProducts, 'META_KEY' =>  $metakeywords);
	}
    
    private function computeUrlNavigationParent($row) {
        return $row['NAVNOM_URLPARENTS']."/".$row['CATNAVNOM'];
    }
 

	private function computeProductListToShowFromEs($user, $searchWord, $listFacets) {
		try {
            if (empty($this->FeatureElasticSearchWsdl) || empty($this->FeatureElasticSearchUsername) || empty($this->FeatureElasticSearchKey) || $this->FeatureElasticSearchEnableOnSearch == false) {
		        return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
            }
            $facetsValues = "";
            if (!empty($listFacets)){
                $facetsValues = json_encode($listFacets);
            }
            $this->log("Elastic search => Search word : ".$searchWord. " / Facets : ".$facetsValues,'info');
             
            $result = new stdClass();
            $isCalledSucceed = false;
            try
            {     
                $soapClient = $this->getSoapClient($this->FeatureElasticSearchWsdl);
                $request = $this->getSoapHeader($this->FeatureElasticSearchUsername, $this->FeatureElasticSearchKey);
                    
                $request->SearchWord = $searchWord;
                if (!empty($listFacets)){
                    $request->Facets = $facetsValues;
                }
                
                $parameters = new stdClass();
                $parameters->request = $request;
                    
                $result = $soapClient->SearchProducts($parameters);
                
                $isCalledSucceed = true;
                $soapClient = null;   
            }
            catch (SoapFault $fault)
            {
				$this->log($fault->faultstring,'err');
            }
                
            if (!$isCalledSucceed || $result->SearchProductsResult->Total == 0) {
		        return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
            }   
            //------------------------------------------------------
            
            $listProducts = array();  
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
		    $listIdBrends = array(); 
		    $listIdBrendFound = array();
			$promoUser = new PromoUser();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$product = new Product();
			$metakeywords = '';  
            
			$isAllPromos = false;
              
            $listOfFacets = array();
            
            if (isset($result->SearchProductsResult->Facets->ProductFacet)) {
                if (!is_array($result->SearchProductsResult->Facets->ProductFacet)) { 
                    array_push($listOfFacets, $result->SearchProductsResult->Facets->ProductFacet); 
                } else {
                    $listOfFacets = $result->SearchProductsResult->Facets->ProductFacet;
                }
            }
            
            $listOfProducts = array();
            if ($result->SearchProductsResult->Total == 1) {
                array_push($listOfProducts, $result->SearchProductsResult->Products->ProductDetail); 
            } else {
                $listOfProducts = $result->SearchProductsResult->Products->ProductDetail;
            }
            
			foreach ($listOfProducts as $row) { 
                try
                {     
				    $currentProduct = array();
				    $currentProduct['ID'] = $row->ProductId;
				    $currentProduct['NOM'] = $row->Name;
				    $currentProduct['DESCSHORT'] = $row->ShortDescription;
				    $currentProduct['PRODUCT_URL'] = $row->ProductUrl;
			  
				    $currentProduct['NAVNOM'] =  $row->MetaNavigationName; 
				    $currentProduct['NAVTITRE'] =  $row->MetaTitle;
				    $currentProduct['NAVDESC'] =  $row->MetaDescription;
                  
                    $isPromo = false; 
                    $currentPrice = 99999; 
                    if (isset($row->ProductPrice)) {
				        $currentProduct['isDEVISPRODUCT'] = !$row->ProductPrice->IsDevis;
				        $currentProduct['PRIX'] = $row->ProductPrice->Price;
				        $currentProduct['PRIXLOWEST'] = $currentProduct['PRIX'];
				        $currentProduct['isPRIXDEGRESSIF'] = $row->ProductPrice->IsDegresivePrice;
				        $currentProduct['isPROMO'] = !$row->ProductPrice->IsPromo;
                        $currentPrice = $row->ProductPrice->Price; 
                        $isPromo = $currentProduct['isPROMO'];
                    } else {
				        $currentProduct['isDEVISPRODUCT'] = "";
				        $currentProduct['PRIX'] = $currentPrice;
				        $currentProduct['PRIXLOWEST'] = $currentProduct['PRIX'];
				        $currentProduct['isPRIXDEGRESSIF'] = 0;
				        $currentProduct['isPROMO'] = 1;
                    }
					
                    if (isset($row->Category)) {
				        $currentProduct['CATID'] = $row->Category->Id;
				        $currentProduct['CATNOM'] = $row->Category->Name;
                        $currentProduct['NAVNOM_URLPARENTS'] = $row->Category->NavigationName;
                    } else {
				        $currentProduct['CATID'] = 0;
				        $currentProduct['CATNOM'] = "";
                        $currentProduct['NAVNOM_URLPARENTS'] = "";
                    }
                
                    if (isset($row->Reranking)) {
                        $currentProduct['BOOSTED_BESTSELLER'] = $row->Reranking->BestSeller; 
                    } else {
                        $currentProduct['BOOSTED_BESTSELLER'] = 99999; 
                    }
                 
				    $currentProduct['URL'] = $row->DefaultPictureUrl; 
                
				    $idBrend = 0;
                    if (isset($row->Brand)) {
				        $currentProduct['isSHOWBREND'] = !$row->Brand->IsShow;
				        $currentProduct['BREND'] = $row->Brand->Name;
				        $currentProduct['BRENDURL'] = $row->Brand->Url;
                        $idBrend = $row->Brand->Id;
                    } else {
				        $currentProduct['isSHOWBREND'] = false;
				        $currentProduct['BREND'] = "";
				        $currentProduct['BRENDURL'] = "";
                    }
				    $currentProduct['NBREFERENCE'] = $row->NbReferences;
                 
                
			        $listUserCodeInternIdBrendFound = array();
			        $listUserCodeInternIdBrends = array();
                   
				    /*
				        * CALCUL PROMO
				        */ 
                
				    if (!in_array($idBrend, $listIdBrends, true)) {
					    $myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
					    array_push($listIdBrends, $idBrend);
					    if ($this->isPromoActive($myPromo)) {
                            $isPromo = true;
                            array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); 
                        }
				    }
				    if ($isPromo) {
					    $isRemise = false;
					    if (in_array($idBrend, $listIdBrends, true)) {
						    foreach ($listIdBrendFound as $brendPromos) {
							    if ($brendPromos['ID'] == $idBrend) {
								    $currentProduct['isPROMO'] = 0;
								    $currentPromo = $brendPromos['PROMO'];
								    if ($currentPromo['REMISEEURO'] > 0) {
									    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
									    $isRemise = true;
								    }
								    if ($currentPromo['REMISEPOUR'] > 0) {
									    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
									    $isRemise = true;
								    }
								    break;
							    }
						    }
					    }
					    if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
						    $currentProduct['isPROMO'] = 0;
						    if ($currentPromoAll['REMISEEURO'] > 0) {
							    $currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
						    }
						    if ($currentPromoAll['REMISEPOUR'] > 0) {
							    $currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
						    }
					    }
				    }
				    if (isset($user) && !empty($user)) {
					    $userId = $user['id'];
					    $codeIntern = $user['cintern'];
					    $isRemise = false;

					    if (!empty($codeIntern)) {
						    if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							    $myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
							    array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
							    if ($this->isPromoActive($myPromo)) { 
                                    $isPromo = true;
                                    array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); 
                                }
						    }
						    if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							    foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
								    if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
									    $currentProduct['isPROMO'] = 0;
									    $currentPromo = $brendPromos['PROMO'];
									    if ($currentPromo['REMISEEURO'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
										    $isRemise = true;
									    }
									    if ($currentPromo['REMISEPOUR'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
										    $isRemise = true;
									    }
									    break;
								    }
							    }
						    }
					    }
					    if (!$isRemise) {
						    if (!in_array($idBrend, $listUserIdBrends, true)) {
							    $myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
							    array_push($listUserIdBrends, $idBrend);
							    if ($this->isPromoActive($myPromo)) { 
                                    $isPromo = true;
                                    array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); 
                                }
						    }
						    if (in_array($idBrend, $listUserIdBrends, true)) {
							    foreach ($listUserIdBrendFound as $brendPromos) {
								    if ($brendPromos['ID'] == $idBrend) {
									    $currentProduct['isPROMO'] = 0;
									    $currentPromo = $brendPromos['PROMO'];
									    if ($currentPromo['REMISEEURO'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
										    $isRemise = true;
									    }
									    if ($currentPromo['REMISEPOUR'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
										    $isRemise = true;
									    }
									    break;
								    }
							    }
						    }
					    } 
                    }  
				    if ($currentProduct['PRIX'] <= 0 ) { 
                        $currentProduct['PRIX'] = $currentPrice; 
                    } 
				    $currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($currentProduct['ID']);
					
				    array_push($listProducts, $currentProduct);
                }
                catch (Zend_Exception $e)
                {
			        $this->log($e->getMessage(),'err');
                }
            } 
            
			return array( 'PRODUCTS' => $listProducts, 'FACETS' => $listOfFacets, 'META_KEY' =>  $metakeywords);
		} catch (Zend_Exception $e) {
			$this->log('computeProductListToShowFromEs : '.$e->getMessage(),'err');
		}
		return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
    }
      
      
	private function computeProductListToShow($list, $user) {
		try {
			$listProducts = array();
			$metakeywords = '';

			$isAllPromos = false;
			$currentPromoAll = array();
			$currentPromo = array();
			$listUserCodeInternIdBrendFound = array();
			$listUserCodeInternIdBrends = array();
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
			$listIdBrends = array();
			$listIdBrendFound = array();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$promoUser = new PromoUser();
			$product= new Product();

			if (!empty($list)) {
				$idCategory = $list[0]['CATID'];
				$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
				if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
			}
			$productChildQte = new ProductChildQte();

			foreach ($list AS $row) {
				$currentProduct = array();
				$currentProduct['ID'] = $row['ID'];
				$currentProduct['NOM'] = $row['NOM'];
				$currentProduct['CATID'] = $row['CATID'];
				$currentProduct['CATNOM'] = $row['CATNOM'];
				$currentProduct['DESCSHORT'] = $row['DESCSHORT'];
				$currentProduct['URL'] = $row['URL'];
				$currentProduct['BREND'] = $row['BREND'];
				$currentProduct['isSHOWBREND'] = $row['isSHOWBREND'];
				$currentProduct['BRENDURL'] = $row['BRENDURL'];
				$currentProduct['NBREFERENCE'] = $row['NBREFERENCE'];
				$currentProduct['isDEVISPRODUCT'] = $row['isDEVISPRODUCT'];
                $currentProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($row);
                $currentProduct['BOOSTED_BESTSELLER'] = $row['BOOSTED_BESTSELLER'];

				if (isset($row['NAVNOM'])) {
					$navnom = $row['NAVNOM'];
				} else {
					$navnom = $row['PRODNAVNOM'];
				}

				$currentProduct['NAVNOM'] = $this->verifyNavigationString($navnom, $row['NOM'], '');

				$currentProduct['NAVTITRE'] = $row['NAVTITRE'];
				$currentProduct['NAVDESC'] = $row['NAVDESC'];

				$isFirst = false;

				if (empty($metakeywords)) {
					$metakeywords .= $row['KEYWORDS_PROD'];
				} else {
					$metakeywords .= ','.$row['KEYWORDS_PROD'];
				}

				$currentProduct['isPROMO'] = $row['isPROMO'];
				$currentProduct['PRIX'] = $row['PRIX'];

				/*
				 * PRIX DEGRESSIF
				 */
				$currentProduct['isPRIXDEGRESSIF'] = $productChildQte->isPrixDegressifByProductID($row['ID']);
					
				/*
				 * CALCUL PROMO
				 */
				$idBrend = $row['BRENDID'];

				if (!in_array($idBrend, $listIdBrends, true)) {
					$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
					array_push($listIdBrends, $idBrend);
					if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
				}
				if ($row['isPROMO'] == 1) {
					$isRemise = false;
					if (in_array($idBrend, $listIdBrends, true)) {
						foreach ($listIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend) {
								$currentProduct['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
					if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
						$currentProduct['isPROMO'] = 0;
						if ($currentPromoAll['REMISEEURO'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
						}
						if ($currentPromoAll['REMISEPOUR'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
						}
					}
				}
				if (isset($user) && !empty($user)) {
					$userId = $user['id'];
					$codeIntern = $user['cintern'];
					$isRemise = false;

					if (!empty($codeIntern)) {
						if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
							array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
							if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
					if (!$isRemise) {
						if (!in_array($idBrend, $listUserIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
							array_push($listUserIdBrends, $idBrend);
							if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend, $listUserIdBrends, true)) {
							foreach ($listUserIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
				}


				if ($currentProduct['PRIX'] <= 0 ) { $currentProduct['PRIX'] = $row['PRIX']; }
 
				$currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($currentProduct['ID']);
					
				array_push($listProducts, $currentProduct);
			}
			return $result = array( 'PRODUCTS' => $listProducts, 'META_KEY' =>  $metakeywords);
		} catch (Zend_Exception $e) {
			$this->log('ComputeProductListToShow : '.$e->getMessage(),'err');
		}
		return $result = array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
	}

	private function getLastCharOf($str) { return $str{strlen($str)-1}; }

    private function ebusinessCategoryAction($id) {
         $currentUser = array();
		try {
		    $auth = Zend_Auth::getInstance();
		    $auth->setStorage($this->getSessionStorage());
		    $storage = $auth->getStorage()->read();
		    if ($auth->hasIdentity() && isset($storage['user'])) {
			    $currentUser = $storage['user'];
            }
        }
        catch (Zend_Exception $e) {
        }

        $category = new Category();
		$product = new Product();
        $productList = array();
		$listCat = array();
		$listCat = $category->getTreeCatsOfWithLevel($id, true);
                    
		if (!empty($listCat)) {
                    
            $this->checkForCategoryRedirection($listCat);
                        
			$this->view->listCat = $listCat;
			$breadcrumb = $category->getTreeInLineOf($id);
			$this->view->breadcrumb = $breadcrumb;
			$this->view->actualDesign = $this->showDesign($breadcrumb[0]['ID'], $breadcrumb[0]);

			if (empty($listCat['NAVTITRENOM'])) {
				$listCat['NAVTITRENOM'] = $listCat['NOM'];
			}
			if (empty($listCat['NAVDESCRIPTION'])) {
				$listCat['NAVDESCRIPTION'] = $listCat['DESCRIPTION'];
			}

			/* Referencement automatique
				$key = new KeyMap();
				$key->updateCatEntry($id);
				*/

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

			$this->view->metadescription = $filter->filter($listCat['NAVDESCRIPTION']);
			$this->view->title = $listCat['NAVTITRENOM'];
			//$isTri_metaKeyword = false;

			$annoncesleft = new AnnonceLeft();
			$this->view->listads = $annoncesleft->getAnnoncesByShow($id);
						
			if (!$listCat['SUBS']) {
				$triSql = 'BOOSTED_BESTSELLER ASC';
				switch ($this->_request->getParam('tri')) {
					case 1:
						$triSql = "PRIX ASC";
						break;
					case 2:
						$triSql = "PRIX DESC";
						break;
					case 3:
						$triSql = 'NOM ASC';
						break;
					case 4:
						$triSql = 'NOM DESC';
						break;
					case 5:
						$triSql = 'BOOSTED_BESTSELLER ASC';
						break;
										
				}
				$this->view->currentCategory =$listCat;
								
				//List of products
				$productList = $product->getProductsByIdCategory($id, $triSql);
								
				$resultProduct = $this->computeProductListToShow($productList, $currentUser);
				$this->view->listAllProducts = $resultProduct['PRODUCTS'];
                            
                if (!empty($listCat['KEYWORDS'])) {
                    $this->view->metakeywords = $listCat['KEYWORDS'];
                } else {                                
                    $this->view->metakeywords = $resultProduct['META_KEY'];
                }
								
				//Show product page
				$this->render('nosproduits');
			} else {
				$metakeywords = $listCat['KEYWORDS'];

                if (empty($metakeywords)) {
                    for ($index = 0; $index < sizeOf($listCat['SUBS']); $index++) {
                        if (empty($metakeywords)) {
                            $metakeywords .= $listCat['SUBS'][$index]['KEYWORDS'];
                        } else {
                            $metakeywords .= ','.$listCat['SUBS'][$index]['KEYWORDS'];
                        }
                    }
                }
				$this->view->metakeywords = $metakeywords;
                if ($this->FeatureProductShowBestSellerOnCategory) {
					$productList = $product->getAllProductsBestSellerByCatId($id);
					$resultProduct = $this->computeProductListToShow($productList, $currentUser);
					$this->view->listAllProductsBestSeller = $resultProduct['PRODUCTS'];
                } 
				$productList = $product->getAllTreeSubProductsByCatId($id);
				$resultProduct = $this->computeProductListToShow($productList, $currentUser);                             
				$this->view->listAllProducts = $resultProduct['PRODUCTS'];
			}
		} else {
			$this->log('Impossible de trouver la categorie : '.$this->getRequest()->getRequestUri(), 'warn');
			$this->_redirect('/');
		}
    }

    private function gallerieCategoryAction($id) {
		$annonce = new AnnonceCms(); 
        $this->view->listAllArticles = $annonce->getAnnoncesByShow($id);
        
		$annonceGallery = new AnnonceGallery(); 
        $this->view->listAllGalleries = $annonceGallery->getAnnoncesByShow($id);

        $category = new Category();  
		$currentCat = $category->fetchRow("ID = ".$id);
		
		$this->view->currentCat = $currentCat;
		
		$this->view->currentCatSubs = $category->getTreeCatsOfWithLevel($id, true);
		
		if (empty($currentCat['NAVTITRENOM'])) {
			$currentCat['NAVTITRENOM'] = $currentCat['NOM'];
		}
		if (empty($currentCat['NAVDESCRIPTION'])) {
			$currentCat['NAVDESCRIPTION'] = $currentCat['DESCRIPTION'];
		}
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

		$this->view->title = $currentCat['NAVTITRENOM'];
		$this->view->metadescription = $filter->filter($currentCat['NAVDESCRIPTION']);  
		$this->view->metakeywords = $currentCat['KEYWORDS']; 
    }

	public function categorieAction()
	{ 
		if ($this->getRequest()->getParam('c')) {
			$id = (int)$this->getRequest()->getParam('c');

			if ($id>0) {

				try {
                    if ($this->isSiteEbusiness) {
                        $this->ebusinessCategoryAction($id);
                    } 
                    if ($this->isSiteGallery) {
                        $this->gallerieCategoryAction($id);
                    } 
				} catch (Zend_Exception $e) {
					$this->log('Erreur pour trouver : '.$this->getRequest()->getRequestUri()." ".$e->getMessage(),'err');
					$this->_redirect('/');
				}
			} else {
				$this->_redirect('/');
			}
		}  else {
			$this->_redirect('/');
		}
	}
 
	public function rechercheAction () {
        $listFacetsSelected = array(); 
		try {
			$date = new Zend_Date();
			$date_start = $date->toString('YYYY-MM-dd HH:mm:ss');

			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringToLower())
			->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));

			$keyTemp = $filter->filter($this->getRequest()->getParam('key'));
			if ($keyTemp=='Rechercher') { $keyTemp = ''; }

			$title = 'Votre s�lection';
			$linksMenu = array();

			if (strlen($keyTemp) == 0) {
				$linksMenu[0]['NAVURL'] = '/produits/recherche';
				$linksMenu[0]['NAVNOM'] = $title;

			} else {
				$title .= ' : "'.$keyTemp.'"';
				$linksMenu[0]['NAVURL'] = '/produits/recherche?key='.$keyTemp;
				$linksMenu[0]['NAVNOM'] = 'Votre s�lection : '.$keyTemp;
			}

			$this->view->linksMenu = $linksMenu;
			$this->view->title = $title;
			$this->view->searchKey = $keyTemp;

			if (!empty($keyTemp) && strlen($keyTemp) >= 2 ) {
                
                $currentUser = array();
                try {
                    $auth = Zend_Auth::getInstance();
                    $auth->setStorage($this->getSessionStorage());
                    $storage = $auth->getStorage()->read();
                    if ($auth->hasIdentity() && isset($storage['user'])) {
                        $currentUser = $storage['user'];
                    }
                }
                catch (Zend_Exception $e) { }
 
                foreach ( $this->getRequest()->getParams() as $key => $value) {
                    if (Utils_Tool::startsWith($key, "facet_") ) {
                        $keys = explode("_", $key);
                        $idFacet = $keys[1]."_".$keys[2];
                        $listFacetsSelected[$idFacet] = $value; 
                    }
                }  
                
				$resultProduct = $this->computeProductListToShowFromEs($currentUser, $keyTemp, $listFacetsSelected);
                
                if (sizeof($resultProduct['PRODUCTS']) == 0) {
                    $listFacetsSelected = array(); 
					$this->log("Alternative search => Search word : ".$keyTemp,'info');
                    $product = new Product();
				    $productList = $product->getProductsBySearch($keyTemp);
                    
				    $resultProduct = $this->computeProductListToShow($productList, $currentUser); 
                }
                
                $currentFacets = array();
                if (isset($resultProduct['FACETS']) && !empty($resultProduct['FACETS'])) {
                    $currentFacets = $resultProduct['FACETS'];
                }
				$this->view->listSearchFacets =  $currentFacets;
				$this->view->listSearchPages =  $resultProduct['PRODUCTS'];
				$this->view->nbrProd = sizeof($resultProduct['PRODUCTS']);

				try {
					$date = new Zend_Date();
					$data = array (
								'VALUE' => $keyTemp,
								'DATEEND' => $date->toString('YYYY-MM-dd HH:mm:ss'),
								'IP' => $_SERVER['REMOTE_ADDR'],
								'DATESTART' => $date_start
					);

					$statsSearch = new StatsSearch();
					$statsSearch->insert($data);
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				}

			} else {
				$this->view->listSearchPages = array();
				$this->view->listSearchFacets = array();
				$this->view->nbrProd = 0;
			}

		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
        
        if ($this->getRequest()->isXmlHttpRequest()) {
		    $layout = Zend_Layout::getMvcInstance();
		    $layout->disableLayout();
        }
	}


	private function getFTFDSByIdProd($id) {
		$childFTFDS = new ProductChildFTFDS();
		$selectFTFDS = "SELECT pcftfds.ID_CHILD ID_CHILD ,pcftfds.URL URL
							FROM productchild_ftfds AS pcftfds 
						LEFT JOIN productchild AS pc ON pcftfds.ID_CHILD = pc.ID
						WHERE pc.IDPRODUCT = ".$id;

		$listFTFDS = $childFTFDS->getAdapter()->fetchAll($selectFTFDS);
		return $listFTFDS;
	}

	public function monpaniercleanupAction() {
		$userNamespace = $this->getSession();

		if (!isset($userNamespace->myObjectCaddy)) {
			$userNamespace->myObjectCaddy = new Caddy();
		}

		$caddy = $userNamespace->myObjectCaddy;
		$caddy->cleanUp();
		$userNamespace->myObjectCaddy = $caddy;
        $userNamespace->myObjectCaddyFidelite = new CaddyFidelite();
        
		$this->_forward('/monpaniertype');
	}

	public function monpaniertypeeditAction() {
		try {
			$linksMenu[0]['NAVURL'] = '/mon-panier-type-actualiser.html';
			$linksMenu[0]['NAVNOM'] = 'Mon Panier type';
			$this->view->linksMenu = $linksMenu;

			$this->view->title = 'Int�grer vos produits directement � votre panier';

			if ($this->isConnected()) {
				if ($this->_request->isPost()) {
					$params = $this->_request->getPost();
					if (isset($params['Child'],$params['Quantity'], $params['CaddyType'])) {
						$listChild = $params['Child'];
						$listQuantity = $params['Quantity'];
						$listQuantityMin = $params['QuantityMin'];
						$listCaddyType =  $params['CaddyType'];
						$listSelectedOption =  $params['selectedOption'];

						for ($i = 0; $i < sizeof($listChild); $i++) {
							if (isset($listChild[$i],$listQuantity[$i])) {
								$idchild = $listChild[$i];
								$qte = intval($listQuantity[$i]);
								$quantityMin = intval($listQuantityMin[$i]);
								$idCaddyType = intval($listCaddyType[$i]);
								$selectedOption = $listSelectedOption[$i];

								if ($qte > 0) {
									$qte = $this->computeQtyMin($qte, $quantityMin);
									if ($idCaddyType > 0 ) {
										$this->ajouterArticleCaddyType($idCaddyType, $qte, $selectedOption);
									} else {
										$this->ajouterArticle($idchild,$qte, 'N', $selectedOption);
									}
								} else {
									if ($idCaddyType > 0 ) {
										$this->supprimerArticleCaddyType($idCaddyType, $selectedOption);
									} else {
										$this->supprimerArticle($idchild, $selectedOption);
									}
								}
							}
						}
					}
				}
			}
		} catch (Zend_Exception $e) { $this->log($e->getMessage(),'err'); }
		$this->_redirect('/mon-panier.html');
	}

}
?>