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

class CommandeController  extends Modules_Default_Controllers_MainController
{
	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}

	public function indexAction()
	{
		$this->_redirect('/mon-panier.html');
	}
	public function livraisonAction()
	{
		$this->view->title = 'Livraison';
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {

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

			if (isset($myFacture) && $myFacture->isFactureValid(1)) {

				$this->view->etapeCommande = 3;
				$this->view->linksMenu = $this->generateLinksMenu(3);

				$dataLiv = array();

				if (isset($usernamespace->addresseLiv) && !empty($usernamespace->addresseLiv)) {
					$dataLiv = $usernamespace->addresseLiv;
				} else {
					$raisonsocial = "";
					if ($storage['user']['type'] == "Professionnel") {
						$raisonsocial = $storage['user']['raisonsocial'];
					} else {
						$raisonsocial = $storage['user']['prenom']." ".$storage['user']['nom'];
					}
					$dataLiv = array('raisonsocial' => $raisonsocial,
                                  'adresse' => $storage['user']['adresse'], 
                                  'adressecomplete' => $storage['user']['adressecomplete'], 
                                  'cp' => $storage['user']['cp'], 
                                  'ville' => $storage['user']['ville'], 
                                  'pays' => $storage['user']['pays'],
                                  'type' => $storage['user']['type']);
					$usernamespace->addresseLiv = $dataLiv;
				}

				$this->view->adresseLiv = $dataLiv;
					
			} else {
				$this->_redirect('/mon-panier.html');
			}
		}  else {
			$this->_redirect('/mon-panier-connexion.html');
		}
	}
	public function ajaxlivraisonAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {

			$usernamespace = $this->getSession();
			$myFacture = $usernamespace->myFactureValidate;
			if (isset($myFacture) && $myFacture->isFactureValid(1)) {
				if ($this->getRequest()->isPost()) {
					$filter = new Zend_Filter();
					$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim())
					->addFilter(new Zend_Filter_HtmlEntities(ENT_COMPAT, 'UTF-8')); //for mootools

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

					$livuser_raisonsocial = $filter->filter(strtoupper($this->getRequest()->getPost('livuser_raisonsocial')));

					$adresse_type = $this->getRequest()->getPost('address_type');
					if ($adresse_type == 'new') {
						$livuser_adresse = $filter->filter($this->getRequest()->getPost('livuser_adresse'));
						$livuser_cp = $filter->filter($this->getRequest()->getPost('livuser_cp'));
						$livuser_ville = $filter->filter($this->getRequest()->getPost('livuser_ville'));
						$livuser_pays = $filter->filter($this->getRequest()->getPost('livuser_pays'));
						$livuser_adressecomplete = $filter->filter($this->getRequest()->getPost('livuser_adressecomplete'));
					} else {
						$livuser_adresse = $filter->filter($this->getRequest()->getPost('livuser_adresse_old'));
						$livuser_cp = $filter->filter($this->getRequest()->getPost('livuser_cp_old'));
						$livuser_ville = $filter->filter($this->getRequest()->getPost('livuser_ville_old'));
						$livuser_pays = $filter->filter($this->getRequest()->getPost('livuser_pays_old'));
						$livuser_adressecomplete = $filter->filter($this->getRequest()->getPost('livuser_adresse_old'));
					}

					if ($validator->isValid($livuser_raisonsocial) &&
					$validator->isValid($livuser_adresse) &&
					$validator->isValid($livuser_ville) &&
					$validator->isValid($livuser_pays) &&
					$validator->isValid($livuser_cp)
					) {
						$dataLiv = array(
	                                  'raisonsocial' =>$livuser_raisonsocial, 
	                                  'adresse' => $livuser_adresse, 
									  'adressecomplete' => $livuser_adressecomplete,
	                                  'cp' => $livuser_cp, 
	                                  'ville' => $livuser_ville, 
	                                  'pays' => $livuser_pays, 
	                                  'type' => $storage['user']['type']);
							
						$usernamespace->addresseLiv = $dataLiv;
						$this->view->adresseLiv = $dataLiv;
						$this->view->messageSuccess = "Votre adresse a �t� modifi�e";
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError =  $this->getErrorValidator($errorCode);
						}
					}
				}
			}
		}
		$this->_forward('ajaxlivraison','ajax');
	}

	public function connexionAction() {
		$this->view->title = 'Connexion';
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {
			$this->_redirect('/mon-panier-livraison.html');
		} else {
			$this->view->linksMenu = $this->generateLinksMenu(2);
		}
	}

	public function ajaxconnexionAction() {
		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())
			-> addValidator(new Zend_Validate_StringLength(4));

			$login = $filter->filter($this->getRequest()->getPost('connexion_login'));
			$mdp = $filter->filter($this->getRequest()->getPost('connexion_mdp'));

			if ($validator->isValid($login) && $validator->isValid($mdp)) {
				$this->view->messageSuccess = $this->connectMe($login, $mdp);
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('ajaxvalue','ajax');
	}

	public function ajaxenregistrementAction() {
		$isAdd = false;
		if ($this->getRequest()->isPost()) {

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

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

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

			$validatorTel = new Zend_Validate();
			$validatorTel -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(10));

			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());
 
			$validatorEmail = new Zend_Validate_EmailAddress();

			$adduser_login = $filter->filter($this->getRequest()->getPost('adduser_login'));
			$adduser_mdp = $filter->filter($this->getRequest()->getPost('adduser_mdp'));
			$adduser_mdp2 = $filter->filter($this->getRequest()->getPost('adduser_mdp2'));

			$adduser_civility = $filter->filter($this->getRequest()->getPost('adduser_civility'));
			$adduser_nom = $filterMaj->filter($this->getRequest()->getPost('adduser_nom'));
			$adduser_prenom = $filter->filter($this->getRequest()->getPost('adduser_prenom'));
             
			$adduser_fct = $filter->filter($this->getRequest()->getPost('adduser_fct'));
			$adduser_tel = $filter2->filter($this->getRequest()->getPost('adduser_tel'));
			$adduser_fax = $filter2->filter($this->getRequest()->getPost('adduser_fax'));
			$adduser_email = $adduser_login;// $filter->filter($this->getRequest()->getPost('adduser_email'));


			$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
			$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
			$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
			$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
			$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
			$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
			$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));

			$adresse_type = $this->getRequest()->getPost('address_type');
			if ($adresse_type == 'new') {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
				$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
				$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));
			} else {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp_old'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville_old'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays_old'));
				$adduser_departement = '';
				$adduser_region = '';
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
			}

			$adduser_raisonsocial = $filterMaj->filter($this->getRequest()->getPost('adduser_raisonsocial'));
			$adduser_siret = $filterMaj->filter($this->getRequest()->getPost('adduser_siret'));
			$adduser_numidfisc = $filterMaj->filter($this->getRequest()->getPost('adduser_numidfisc'));
			$adduser_codeape = $filterMaj->filter($this->getRequest()->getPost('adduser_codeape'));
			$adduser_sectactivite = $filterMaj->filter($this->getRequest()->getPost('adduser_sectactivite'));

			$adduser_comm = $filter->filter($this->getRequest()->getPost('adduser_comm'));

			$adduser_newsletter = $filter->filter($this->getRequest()->getPost('adduser_newsletter'));

			$typeUser = $filter->filter($this->getRequest()->getPost('adduser_typeuser'));

			$date = new Zend_Date();
			$dateinsc = $date->toString('YYYY-MM-dd HH:mm:ss');

			$data = array(
                                  'LOGIN' => utf8_decode($adduser_login), 
                                  'MDP' => md5($adduser_mdp), 
                                  'ROLE' => 0, 
                                  'NOM' => utf8_decode($adduser_nom), 
                                  'PRENOM' => utf8_decode($adduser_prenom),
                                  'CIVILITE' => $adduser_civility, 
                                  'FONCTION' => utf8_decode($adduser_fct), 
                                  'RAISONSOCIAL' => utf8_decode($adduser_raisonsocial), 
                                  'ADRESSE' => utf8_decode($adduser_adresse), 
                                  'CP' => utf8_decode($adduser_cp), 
                                  'VILLE' => utf8_decode($adduser_ville), 
                                  'DEPARTEMENT' => utf8_decode($adduser_departement), 
                                  'REGION' => utf8_decode($adduser_region), 
								  'ADRESSECOMPLETE' => utf8_decode($adduser_adressecomplete),
                                  'PAYS' => utf8_decode($adduser_pays), 
                                  'EMAIL' => utf8_decode($adduser_email), 
                                  'TEL' => $adduser_tel, 
                                  'FAX' => $adduser_fax, 
                                  'SIRET' => utf8_decode($adduser_siret), 
								  'NUMIDFISC' => utf8_decode($adduser_numidfisc),
                                  'CODEAPE' => utf8_decode($adduser_codeape), 
                                  'SECTACTIVITE' => utf8_decode($adduser_sectactivite), 
                                  'COMMENTAIRE' => utf8_decode($adduser_comm),  
                                  'TYPE' => $typeUser, 
                                  'DATEINSC' => $dateinsc);

			$isTypeOk = false;
			if ($validator2->isValid($typeUser)) {
				$isTypeOk = true;
			}

			$errorType = 0;
			if ($validator->isValid($adduser_mdp) && $validator->isValid($adduser_mdp2) &&
			$validator2->isValid($adduser_civility) &&
			$validator2->isValid($adduser_nom) && $validator2->isValid($adduser_adresse) &&
			$validator2->isValid($adduser_prenom) && $validator2->isValid($adduser_ville) &&
			$validator2->isValid($adduser_pays) &&
			$validatorEmail->isValid($adduser_login) && $validator2->isValid($adduser_cp)
			) {
				if ($isTypeOk) {
					if ($typeUser == "Professionnel") {
						if ($validator2->isValid($adduser_raisonsocial) &&
						$validator2->isValid($adduser_siret) &&
						$validator2->isValid($adduser_numidfisc) &&
						$validator2->isValid($adduser_codeape)) {

						} else { 
							$errorType = 3;
							foreach ($validator2->getErrors() as $errorCode) {
								$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
							}
						}
					}
				} else {
					$errorType = 2;
					$this->view->messageSuccess =  "Vous devez choisir entre Particulier et Professionnel. ";
				}
			} else {
				$errorType = 1; 
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
				foreach ($validator2->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
			}


			if ($errorType == 0) {
				if ($validatorTel->isValid($adduser_tel)) {
					if ($adduser_mdp2 == $adduser_mdp) {

						try {
							$user = new User();

							$isExistLogin = $user->fetchRow("LOGIN = '".$adduser_login."'");

							if (!$isExistLogin) {

								$isExistEmail = $user->fetchRow("EMAIL = '".$adduser_email."'");
								if (!$isExistEmail) {
									$isAdd = $user->insert($data);
									$this->log("Nouveau client : ".$adduser_email,'info');
									if ($adduser_newsletter) {
										$user_newsletter = new UserNewsletter();
										$code = md5($dateinsc.'_'.$adduser_email);
											
										$isExistNL = $user_newsletter->fetchRow("EMAIL = '".$adduser_email."'");

										if(!$isExistNL) {
											$dataNL = array(
						 	 					'EMAIL' => $adduser_email,
						 	 					'DATEINS' => $dateinsc,
						 	 					'CODE' => $code
											);
											$user_newsletter->insert($dataNL);
										}
									}

									$this->view->messageSuccess = $this->connectMe($adduser_login, $adduser_mdp);
								} else {
									$this->view->messageSuccess =  "L'email est d�j� utilis�.";
								}
							} else {
								$this->view->messageSuccess =  "L'identifiant existe d�j�";
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->messageSuccess =  "Une erreur est survenue, v�rifier vos informations.";
						}
					} else {
						$this->view->messageSuccess =  "V�rifier votre mot de passe";
					}
				} else {
					$this->view->messageSuccess =  "V�rifier votre num�ro de t�l�phone";
				}
			}
		}
		$this->_forward('ajaxvalue','ajax');
	}


	private function computeBill($statut,$reference,$id,$facture,$addresseLiv, $user) {
		$fact_raisonsociale = $user['prenom']." ".strtoupper($user['nom']);
		if ($user['type'] == "Professionnel") {
			$fact_raisonsociale = $user['raisonsocial'];
		} 
		$USER_MODEPAIEMENT_LABEL = " Paiement s�curis� en ligne";
		switch ($user['modepaiement']) {
			case 1 : $USER_MODEPAIEMENT_LABEL = " Paiement s�curis� en ligne"; break;
			case 2 : $USER_MODEPAIEMENT_LABEL = " Contre remboursement";break;
			case 3 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 30 jours";break;
			case 4 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 45 jours";break;
			case 5 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 60 jours";break;
			case 6 : $USER_MODEPAIEMENT_LABEL = " A r�ception de la facture";break;
		}
        
        if($statut == 10) {
            $USER_MODEPAIEMENT_LABEL = "Devis";
        }

		$data = array (
						'REFERENCE' => $reference, 
						'PRIXTOTALHTHR' => $facture->total_HT_HR,
						'PRIXREMISEEUR' => $facture->total_remise,
						'PRIXTOTALHT' => $facture->total_HT,
						'PRIXFRAISPORT' => $facture->total_frais_port,
						'PRIXFRAISPORTPOUR' => $facture->total_frais_port_pour,
						'PRIXTOTALHTFP' => $facture->total_HT_FP,
						'PRIXTOTALTTC' => $facture->total_TTC,
						'PRIXTOTALTVA' => $facture->total_TVA,
						'DATESTART' => $facture->date_start, 
						'IDUSER' => $user['id'],
						'STATUT' => $statut,
						'LIV_RAISONSOCIAL' => $addresseLiv['raisonsocial'],
						'LIV_ADRESSE' => $addresseLiv['adresse'],
						'LIV_CP' => $addresseLiv['cp'],
						'LIV_VILLE' => $addresseLiv['ville'],
						'LIV_PAYS' => $addresseLiv['pays'],
						'FACT_RAISONSOCIAL' => $fact_raisonsociale,
						'FACT_ADRESSE' => $user['adresse'],
						'FACT_CP' => $user['cp'],
						'FACT_VILLE' => $user['ville'],
						'FACT_PAYS' => $user['pays'],
						'USER_NOM' =>$user['nom'],
						'USER_PRENOM' =>$user['prenom'],
						'USER_TEL' =>$user['tel'],
						'USER_FAX' =>$user['fax'],
						'USER_NUMCOMPTE' =>$user['numcompte'],
						'USER_EMAIL' =>$user['email'],
						'USER_MODEPAIEMENT' =>$user['modepaiement'],
						'USER_TYPE' =>$user['type'],
						'USER_MODEPAIEMENT_LABEL' =>$USER_MODEPAIEMENT_LABEL,
						'CADDY' => $facture->facture_lines,
						'INFOLIV' => $facture->livraison,
						'CODEREDUCTION' => $facture->code_reduction,
						'ID_COMMAND' => $id
		);
        $data['CADDYFIDELITE'] = array();
        if($statut != 10) {
            $data['CADDYFIDELITE'] = $facture->facture_fidelite_lines;
        } else {
            $facture->facture_fidelite_lines = array();            
        }
		return $data;
	}
 
	public function validationAction()
	{
		try {
			$this->view->title = 'Confirmation de votre commande';
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			if ($auth->hasIdentity() && isset($storage['user'])) {
				
				$this->view->user = $storage['user'];

				$usernamespace = $this->getSession();
				$addresseLiv = $usernamespace->addresseLiv;
				$facture = $usernamespace->myFactureValidate;

				if ($this->isExisteArray($addresseLiv) && $facture->isFactureValid(2)) {
					$this->view->etapeCommande = 4;
					$this->view->linksMenu = $this->generateLinksMenu(4); 
					$usernamespace->myFactureValidate = $facture;

					$data = $this->insertNewCommand(0,'Validating','',$facture, $addresseLiv,$storage['user']);
					$usernamespace->commandAdded = $data;

					$facture = $this->computeBill(0,$data['REFERENCE'],$data['ID'],$facture, $addresseLiv, $storage['user']);
					$this->view->facture = $facture;

					$promo = new PromoCalculator();
					$this->view->isCommandValid = $promo->isCommandValid($facture['PRIXTOTALHT']);

				} else {
					$this->_redirect('/mon-panier.html');
				}
			}  else {
				$this->_redirect('/connectez-vous.html');
			}
		} catch (Zend_Exception $e) {
			$this->log("Erreur : validationAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}

	private function isExisteArray($array) {
		if (isset($array) && sizeof($array) > 0) {
			return true;
		} else {
			return false;
		}
	}
	public function paiementAction() {
		try {

			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$ispaiementOk = false;
            $sendmail = true;
			
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$modepaiement = $storage['user']['modepaiement']; 
				$payment_status = 'Pending';
				$txn_id = '';
				
				$type_paiement = '';
				$type = 0;
				$type_prefix = 'Mode de paiement : ';
				switch ($modepaiement) {
					case 1 :
						$type_paiement = $type_prefix.'Paiement s�curis� en ligne';
						$ispaiementOk = true;
                        $sendmail = false;
						if ($this->ipnPaypalListenerValidate()) {
							$payment_status = $this->_request->getParam('payment_status');
							$txn_id = $this->_request->getParam('txn_id');
						} 
						break;
					default :
						$ispaiementOk = false;
						break;
				}
				
				if ((int)$this->getRequest()->getParam('type') > 0) {
					$type = (int)$this->getRequest()->getParam('type'); 
					switch ($type) {
						case 1 : 
							$ispaiementOk = true; 
							$type_paiement = $type_prefix.'Par ch�que';
							break;
						case 2 : 
							$ispaiementOk = true; 
							$type_paiement = $type_prefix.'Par virement';
							break;
						case 3 : 
							$ispaiementOk = true; 
							switch ($modepaiement) { 
								case 2 : $type_paiement = $type_prefix."Contre remboursement";break;
								case 3 : $type_paiement = $type_prefix."Paiement diff�r� - 30 jours";break;
								case 4 : $type_paiement = $type_prefix."Paiement diff�r� - 45 jours";break;
								case 5 : $type_paiement = $type_prefix."Paiement diff�r� - 60 jours";break;
								case 6 : $type_paiement = $type_prefix."A r�ception de la facture";break;
							} 
							break; 
					}
				} 
			} else {
			    $this->log("Erreur : paiementAction() No user",'warn');
            }

			if ($ispaiementOk) {
			    $this->log("Erreur : paiementAction() Paiement Ok",'warn');
				$this->finishandclosepaiement($payment_status, $txn_id, $type_paiement, $type, $sendmail);				
			}  else {
			    $this->log("Erreur : paiementAction() Redirect Home",'warn');
				$this->_redirect('/');
			}

		}catch (Zend_Exception $e) {
			$this->log("Erreur : paiementAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}

	private function sendMailCommande($facture, $to) {


		$view = new Zend_View();
		$view->addScriptPath('../application/modules/default/views/scripts/commande/');
		$view->assign("facture",$facture);
		$view->assign("baseUrl", "http://".$this->site_actualshort);
		$view->assign("baseUrl_SiteCommerceUrl", $this->baseUrl_SiteCommerceUrl);
		$view->assign("serviceClient_Mail", $this->serviceClient_Mail);
		
		$view->assign("siteName", $this->siteName);
		$view->assign("site_addresse3_title", $this->site_addresse3_title);
		$view->assign("site_addresse3_address", $this->site_addresse3_address);
		$view->assign("site_addresse3_cp", $this->site_addresse3_cp);
		$view->assign("site_addresse", $this->site_addresse);
		$view->assign("site_actualshort", $this->site_actualshort);
		
		$view->assign("site_rib_numbers", $this->site_rib_numbers);
		$view->assign("site_rib_iban", $this->site_rib_iban);
		$view->assign("site_rib_bic", $this->site_rib_bic);
		$view->assign("site_rib_bankname", $this->site_rib_bankname);

		$body = $view->render("facture_mail.phtml");

		$from =  $this->serviceClient_Mail;

		if ($facture['STATUT'] == 1) { $objet = "Votre commande : ".$facture['REFERENCE']; } else {$objet = "Votre devis : ".$facture['REFERENCE'];}

		$mail = new Zend_Mail();
		$mail->setBodyHtml($body);
		$mail->setFrom($from, $this->siteName);
		$mail->addTo($to);
		$mail->setSubject($objet);
		try {
			$mail->send();
			$this->log("L'email de commande a �t� envoy� a : ".$to,'info');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	private function referencegen() {
		$chaine ="mnoTUzS5678kVvwxy9WXYZRNCDEFrslq41GtuaHIJKpOPQA23LcdefghiBMbj0";
		srand((double)microtime()*1000000);
		for($i=0; $i<10; $i++){
			@$pass .= $chaine[rand()%strlen($chaine)];
		}
		return $pass;
	}

	private function generateLinksMenu($etapeCommande){
		$linksMenu = array();
		switch ($etapeCommande) {
			case 2 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-connexion.html';
				$linksMenu[1]['NAVNOM'] = 'Identification';
				break;

			case 3 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-livraison.html';
				$linksMenu[1]['NAVNOM'] = 'Livraison';
				break;

			case 4 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-livraison.html';
				$linksMenu[1]['NAVNOM'] = 'Livraison';
				$linksMenu[2]['NAVURL'] = '/mon-panier-validation.html';
				$linksMenu[2]['NAVNOM'] = 'Validation';
				break;

		}

		return $linksMenu;
	}
    
	private function updateCommandFidelite($id, $facture) {
        $commandFidelite = new CommandFidelite();
        $commandFidelite->delete('IDCOMMAND = '.$id); 
		foreach ($facture->facture_fidelite_lines as $row) {
			$dataCaddyFidelite = array (
						'IDFIDELITE' => $row->fidelite_id,
						'NBPOINT' => $row->fidelite_nbpoint,                  
						'NOM' => $row->fidelite_nom,
						'IDCOMMAND' => $id
			);
			$commandFidelite->insert($dataCaddyFidelite);
		}
    }

	private function updateCommand($id, $payment_status,$txn, $statut) {

		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $payment_status,
			'TXN_ID' => $txn,
			'STATUT' => $statut
			);
			$command->update($data,'ID = '.$id);
            
            if ($statut != 10 && $this->carte_fidelite_enabled) {
                 $facture = $command->getCommandAsFacture($id);
			     $commandProduct = new CommandProduct();
			     $productChild = new ProductChild();
                 foreach($facture['CADDY'] as $row) {
                    $child = $productChild->fetchRow('ID = '.$row['ID']);
                    $dataProd = array(
			            'POINTFIDELITE' => $child['POINTFIDELITE'],
			            'POINTFIDELITESUM' => $child['POINTFIDELITE'] * $row['QUANTITY']
			        );
			        $commandProduct->update($dataProd,'ID = '.$row['IDLINE']);
                }
            }
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}

	private function updateCommandByID($id, $payment_status,$txn, $statut) {
		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $payment_status,
			'TXN_ID' => $txn,
			'STATUT' => $statut
			);
			$command->update($data,'ID = '.$id);

			$currentCommand = $command->fetchRow('ID = '.$id);
			if (isset($currentCommand) && !empty($currentCommand) && !empty($currentCommand['CODEREDUCTION'])) {
				$codeReduction = new CodeReduction();
				$date = new Zend_Date();
				$data = array(
					"isACTIF" => 0,
					"NOM" => $currentCommand['USER_NOM'],
					"PRENOM" => $currentCommand['USER_PRENOM'],
					"IDUSER" => $currentCommand['IDUSER'],
					"ID" => $id,
					"DATEUSE" => $date->toString('YYYY-MM-dd HH:mm:ss')
				);
				$codeReduction->update($data,"CODE = '".$currentCommand['CODEREDUCTION']."'");
			}

		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande ID : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}


	private function updateCommandByIDUNVERIFIED($id, $paymentStat) {
		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $paymentStat,
			'STATUT' => 1
			);
			$command->update($data,'ID = '.$id);
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande ID : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}

	private function deleteNewCommand($id) {
		try {
			$command = new Command();
			$commandProduct = new CommandProduct();

			$commandProduct->delete('IDCOMMAND = '.$id);
			$command->delete('ID = '.$id);
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la suppression de la commande : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}


	private function insertNewCommand($statut,$payment_status,$txn, $myFacture, $addresseLiv, $user) {
		$command = new Command();
		$fact_raisonsociale = $user['prenom']." ".strtoupper($user['nom']);
		if ($user['type'] == "Professionnel") {
			$fact_raisonsociale = $user['raisonsocial'];
		}
		$codereduction = "";
		$codereductioneuro = 0;
		$livnom = "";
		if (isset($myFacture->code_reduction) && !empty($myFacture->code_reduction)) {
			$codereductioneuro = $myFacture->code_reduction['EURO'];
			$codereduction = $myFacture->code_reduction['CODE'];
		}
		if (isset($myFacture->livraison) && !empty($myFacture->livraison)) {
			$livnom = $myFacture->livraison['NOMLIV'];
		}
			
		$data = array (
						'REFERENCE' => 'REF-'.$this->referencegen(),
						'PRIXTOTALHTHR' => $myFacture->total_HT_HR,
						'PRIXREMISEEUR' => $myFacture->total_remise,
						'PRIXTOTALHT' => $myFacture->total_HT,
						'PRIXFRAISPORT' => $myFacture->total_frais_port,
						'PRIXFRAISPORTPOUR' => $myFacture->total_frais_port_pour,
						'PRIXTOTALHTFP' => $myFacture->total_HT_FP,
						'PRIXTOTALTTC' => $myFacture->total_TTC,
						'DATESTART' => $myFacture->date_start,
						'STATUT' => $statut,
						'PAYMENT_STATUS' => $payment_status,
						'TXN_ID' => $txn,
						'IDUSER' => $user['id'],
						'LIV_RAISONSOCIAL' => $addresseLiv['raisonsocial'],
						'LIV_ADRESSE' => $addresseLiv['adresse'],
						'LIV_CP' => $addresseLiv['cp'],
						'LIV_VILLE' => $addresseLiv['ville'],
						'LIV_PAYS' => $addresseLiv['pays'],
						'FACT_RAISONSOCIAL' => $fact_raisonsociale,
						'FACT_ADRESSE' => $user['adresse'],
						'FACT_CP' => $user['cp'],
						'FACT_VILLE' => $user['ville'],
						'FACT_PAYS' => $user['pays'],
						'USER_NOM' =>$user['nom'],
						'USER_PRENOM' =>$user['prenom'],
						'USER_TEL' =>$user['tel'],
						'USER_FAX' =>$user['fax'],
						'USER_EMAIL' =>$user['email'],
						'USER_NUMCOMPTE' =>$user['numcompte'],
						'USER_MODEPAIEMENT' =>$user['modepaiement'],
						'USER_MODEPAIEMENT_TYPE' => 0,
						'LIV_NOM' =>$livnom,
						'CODEREDUCTIONEURO' => $codereductioneuro,
						'CODEREDUCTION' => $codereduction
		);

		$command->insert($data);

		$lastID = $command->getAdapter()->lastInsertId($command,'ID');

		$date = new Zend_Date();
		$myReference = $this->lpad_zero($lastID, 5)."-".$date->toString('YY');
		$dataRef = array ( 'REFERENCE' => $myReference );
		$command->update($dataRef,"ID = ".$lastID);
			
		$commandProduct = new CommandProduct();
		$userCaddyType = new UserCaddyType();

		foreach ($myFacture->facture_lines as $row) {
			$dataCaddy = array (
						'CHILDID' => $row->item_id,
						'CHILDREF' => $row->item_reference,
						'CHILDisPROMO' => $row->item_isPromo,
						'CHILDisDEVIS' => $row->item_isDevis,
						'CHILDPRIX' => $row->item_prix,
						'CHILDQUANTITY' => $row->item_qte,
						'CHILDPROMOPRIX' => $row->getPrixAfterRemise(),
						'CHILDPRIXTOTAL' => $row->getPrixTotalHT(true),
						'CHILDPRIXREMISE' => $row->getPrixRemise(),
						'CHILDREMISEPRIXTAUXE' => $row->remise_euro,
						'CHILDREMISEPRIXTAUXP' => $row->remise_pour,
						'PRODUCTID' => $row->product_id,
						'IDCOMMAND' => $lastID,
						'SELECTEDOPTION' => $row->item_selectedOption,
                        'POINTFIDELITE' => 0,
                        'POINTFIDELITESUM' => 0
			);
			$userCaddyType->addNewUserItem($row->item_reference, $user['id']);
			$commandProduct->insert($dataCaddy);
		}

		$dataReturn = array(
			'REFERENCE' => $myReference,
			'ID' => $lastID
		);
		return $dataReturn;
	}

	public function paypalipnvalidationtestAction() {
		$resultPaypal = $this->ipnPaypalListener();
		$this->_redirect('/');
	}

	public function paypalipnvalidationAction() {
		$resultPaypal = $this->ipnPaypalListener();
		$this->_redirect('/');
	}

	private function sendMail($body, $from, $to, $objet) {
		$mail = new Zend_Mail();
		$mail->setBodyHtml($body);
		$mail->setFrom($from, $this->siteName.' : PAYPAL');
		$mail->addTo($to);
		$mail->setSubject($objet);
		try {
			$mail->send();
			$this->log("L'email a �t� envoy� a : ".$to,'info');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	private function ipnPaypalListener() {
		
		$idCommand = $this->_request->getParam('item_number');
		if (empty($idCommand)) {
			$idCommand = $this->_request->getParam('custom');			
		}
		
		$dataIPN = array(
			'transaction_subject' => $this->_request->getParam('transaction_subject'),
			'txn_type' => $this->_request->getParam('txn_type'),
			'payment_date' => $this->_request->getParam('payment_date'),
			'last_name' => $this->_request->getParam('last_name'),
			'residence_country' => $this->_request->getParam('residence_country'),
			'pending_reason' => $this->_request->getParam('pending_reason'),
			'item_name' => $this->_request->getParam('item_name'),
			'payment_gross' => $this->_request->getParam('payment_gross'),
			'payment_currency' => $this->_request->getParam('mc_currency'),
			'business' => $this->_request->getParam('business'),
			'payment_type' => $this->_request->getParam('payment_type'),
			'protection_eligibility' => $this->_request->getParam('protection_eligibility'),
			'payer_status' => $this->_request->getParam('payer_status'),
			'verify_sign' => $this->_request->getParam('verify_sign'),
			'txn_id' => $this->_request->getParam('txn_id'),
			'payer_email' => $this->_request->getParam('payer_email'),
			'tax' => $this->_request->getParam('tax'),
			'test_ipn' => $this->_request->getParam('test_ipn'),
			'first_name' => $this->_request->getParam('first_name'),
			'receiver_email' => $this->_request->getParam('receiver_email'),
			'quantity' => $this->_request->getParam('quantity'),
			'payer_id' => $this->_request->getParam('payer_id'),
			'receiver_id' => $this->_request->getParam('receiver_id'),
			'item_number' => $idCommand,
			'payment_status' => $this->_request->getParam('payment_status'),
			'handling_amount' => $this->_request->getParam('handling_amount'),
			'shipping' => $this->_request->getParam('shipping'),
			'payment_amount' => $this->_request->getParam('mc_gross'),
			'custom' => $this->_request->getParam('custom'),
			'charset' => $this->_request->getParam('charset'),
			'notify_version' => $this->_request->getParam('notify_version'),
			'merchant_return_link' => $this->_request->getParam('merchant_return_link')
		);

		// read the post from PayPal system and add 'cmd'
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}
		
		$this->log('PAYPAL : IPN INCOMING : req : '.$req,'info');

		// post back to PayPal system to validate
		$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

		//If testing on Sandbox use:
		$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

		$notify_email = $this->reglement_Mail;

		if (!$fp) {
			return false;
		} else {
			fputs ($fp, $header . $req);
			while (!feof($fp)) {
				$res = fgets ($fp, 1024);
				if (strcmp ($res, "VERIFIED") == 0) {
					if ($this->isTxnidUnique($dataIPN)) {

						if ($dataIPN['payment_status'] == 'Completed' && $dataIPN['receiver_id'] == $this->paypal_business) {
							$paypal_payment = new PaypalPaiement();
							$paypal_payment->insert($dataIPN);

							$this->updateCommandByID($idCommand,$dataIPN['payment_status'],$dataIPN['txn_id'],1);
		                    $this->log('PAYPAL : IPN-VERIFIED : res : '.$res.' : req : '.$req,'info');
							$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED');

				            $command = new Command();                            
                            $facture = $command->getCommandAsFacture($idCommand);
                            $this->finishandclosepaiementsendmail($facture, $idCommand, true, "Mode de paiement : Paiement s�curis� en ligne", 0);
                            
							return true;

						} else {
							$this->updateCommandByIDUNVERIFIED($idCommand, 'Incorrect');
							$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED INCORRECT');
							$this->log('PAYPAL : IPN-VERIFIED INCORRECT : res : '.$res.' : req : '.$req,'warn');
						}
					} else {
						$this->updateCommandByIDUNVERIFIED($idCommand, 'Duplicated');
						$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED DUPLICATED TRANSACTION');
						$this->log('PAYPAL : IPN-VERIFIED DUPLICATED TRANSACTION : res : '.$res.' : req : '.$req,'warn');
					}

				} else if (strcmp ($res, "INVALID") == 0) {
					$this->updateCommandByIDUNVERIFIED($idCommand, 'Invalid');
					$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-INVALID');
					$this->log('PAYPAL : IPN-INVALID : res : '.$res.' : req : '.$req,'warn');
				}

			}
			fclose ($fp);
		}
		return false;
	}
    
    private function finishandclosepaiementsendmail($facture, $idCommand, $sendmail, $type_paiement, $type) {
		$command = new Command();
		$dataTemp = array(
				'USER_MODEPAIEMENT_LABEL' => $type_paiement,
				'USER_MODEPAIEMENT_TYPE' => $type
		);
		$command->update($dataTemp,'ID = '.$idCommand);
        
        if ($sendmail) {
            $facture['USER_MODEPAIEMENT_LABEL'] = $type_paiement;
		    $facture['USER_MODEPAIEMENT_TYPE'] = $type;                
		    $this->sendMailCommande($facture,$this->devisCommande_Mail);
		    $this->sendMailCommande($facture,$facture['USER_EMAIL']);
        }                
	    /*
        if (isset($this->ekomi_email) && !empty($this->ekomi_email)) {
		    $this->sendMailCommande($factureDevis,$this->ekomi_email);
        }*/                
    }

	private function ipnPaypalListenerValidate() {
	
		$idCommand = $this->_request->getParam('item_number');
		if (empty($idCommand)) {
			$idCommand = $this->_request->getParam('custom');			
		}
		
		$dataIPN = array(
			'transaction_subject' => $this->_request->getParam('transaction_subject'),
			'txn_type' => $this->_request->getParam('txn_type'),
			'payment_date' => $this->_request->getParam('payment_date'),
			'last_name' => $this->_request->getParam('last_name'),
			'residence_country' => $this->_request->getParam('residence_country'),
			'pending_reason' => $this->_request->getParam('pending_reason'),
			'item_name' => $this->_request->getParam('item_name'),
			'payment_gross' => $this->_request->getParam('payment_gross'),
			'payment_currency' => $this->_request->getParam('mc_currency'),
			'business' => $this->_request->getParam('business'),
			'payment_type' => $this->_request->getParam('payment_type'),
			'protection_eligibility' => $this->_request->getParam('protection_eligibility'),
			'payer_status' => $this->_request->getParam('payer_status'),
			'verify_sign' => $this->_request->getParam('verify_sign'),
			'txn_id' => $this->_request->getParam('txn_id'),
			'payer_email' => $this->_request->getParam('payer_email'),
			'tax' => $this->_request->getParam('tax'),
			'test_ipn' => $this->_request->getParam('test_ipn'),
			'first_name' => $this->_request->getParam('first_name'),
			'receiver_email' => $this->_request->getParam('receiver_email'),
			'quantity' => $this->_request->getParam('quantity'),
			'payer_id' => $this->_request->getParam('payer_id'),
			'receiver_id' => $this->_request->getParam('receiver_id'),
			'item_number' => $idCommand,
			'payment_status' => $this->_request->getParam('payment_status'),
			'handling_amount' => $this->_request->getParam('handling_amount'),
			'shipping' => $this->_request->getParam('shipping'),
			'payment_amount' => $this->_request->getParam('mc_gross'),
			'custom' => $this->_request->getParam('custom'),
			'charset' => $this->_request->getParam('charset'),
			'notify_version' => $this->_request->getParam('notify_version'),
			'merchant_return_link' => $this->_request->getParam('merchant_return_link')
		);

		$notify_email = $this->reglement_Mail;

		// read the post from PayPal system and add 'cmd'
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}

		$this->log('PAYPAL : IPN INCOMING : req : '.$req,'info');
		
		// post back to PayPal system to validate
		$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

		//If testing on Sandbox use:
		$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

		if (!$fp) {
			return false;
		} else {
			fputs ($fp, $header . $req);
			while (!feof($fp)) {
				$res = fgets ($fp, 1024);
				if (strcmp ($res, "VERIFIED") == 0) {
					if (!$this->isTxnidUnique($dataIPN)) {
						if ($dataIPN['payment_status'] == 'Completed' && $dataIPN['receiver_id'] == $this->paypal_business) {
							return true;
						}
					}
				} else if (strcmp ($res, "INVALID") == 0) {
					return false;
				}
			}
			fclose ($fp);
		}
		return false;
	}
	private function isTxnidUnique($data) {
		$paypal_payment = new PaypalPaiement();
		$row = $paypal_payment->fetchRow("txn_id = '".$data['txn_id']."'");
		if($row) { return false; } else { return true; }
	}


	public function devisAction() {
		$this->view->title = 'Confirmation de votre devis';
			
		try {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$usernamespace = $this->getSession();
				$addresseLiv = $usernamespace->addresseLiv;
				$facture = $usernamespace->myFactureValidate;
				if ($this->isExisteArray($addresseLiv) && $facture->isFactureValid(2) && isset($usernamespace->commandAdded)) {

					$dataReturn = $usernamespace->commandAdded;
					$this->updateCommand($dataReturn['ID'],'Pending','',10);

					if (isset($facture->code_reduction) && !empty($facture->code_reduction)) {
						$codeReduction = new CodeReduction();
						$date = new Zend_Date();
						$data = array(
						"isACTIF" => 0,
						"NOM" => $storage['user']['nom'],
						"PRENOM" => $storage['user']['prenom'],
						"IDUSER" => $storage['user']['id'],
						"REFERENCE" => $dataReturn['REFERENCE'],
						"DATEUSE" => $date->toString('YYYY-MM-dd HH:mm:ss')
						);
						$codeReduction->update($data,"CODE = '".$facture->code_reduction['CODE']."'");
					}

					$factureDevis = $this->computeBill(10,$dataReturn['REFERENCE'],$dataReturn['ID'], $facture,$addresseLiv, $storage['user']);
					$this->view->facture = $factureDevis;
                    
                    $command = new Command();                            
                    $facture = $command->getCommandAsFacture($dataReturn['ID']);
					$this->sendMailCommande($facture,$this->devisCommande_Mail);
					$this->sendMailCommande($facture,$facture['USER_EMAIL']);
                    
					$this->view->linksMenu = $this->generateLinksMenu(4);
					$usernamespace->addresseLiv = array();
					$usernamespace->myFactureValidate = array();

					unset($usernamespace->addresseLiv);
					unset($usernamespace->myFactureValidate);
					unset($usernamespace->commandAdded);

					$usernamespace->myObjectCaddy =array();
					unset($usernamespace->myObjectCaddy);
                    
				    $usernamespace->myObjectCaddyFidelite = array();
				    unset($usernamespace->myObjectCaddyFidelite);
				} else { $this->_redirect('/'); }
			} else { $this->_redirect('/connectez-vous.html'); }
		} catch (Zend_Exception $e) {
			$this->log('Erreur : devisAction() : '.$e->getTraceAsString(),'err');
			$this->_redirect('/');
		}
	}

	private function lpad_zero($chaine,$taille) {
		return str_pad($chaine,$taille,"0",STR_PAD_LEFT);
	}
	
	private function finishandclosepaiement($payment_status, $txn_id, $type_paiement, $type, $sendmail) {
		if (!isset($this->site_rib_numbers)) {
			$this->initVariables();
		}
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();
		
		if ($auth->hasIdentity() && isset($storage['user'])) {
		
			$usernamespace = $this->getSession();
			$addresseLiv = $usernamespace->addresseLiv;
			$myFacture = $usernamespace->myFactureValidate;
		
			if ($this->isExisteArray($addresseLiv) && $myFacture->isFactureValid(2) && isset($usernamespace->commandAdded)) {
		
				$this->view->title = 'Confirmation de votre commande';
		
				$data = $usernamespace->commandAdded;
				$this->updateCommand($data['ID'],$payment_status,$txn_id,1);
                
				$this->updateCommandFidelite($data['ID'], $myFacture);
        
				$facture = $this->computeBill(1,$data['REFERENCE'],$data['ID'], $myFacture,$addresseLiv,$storage['user']);
                
                $facture['USER_MODEPAIEMENT_LABEL'] = $type_paiement;
		        $facture['USER_MODEPAIEMENT_TYPE'] = $type; 
                $this->view->facture = $facture;
                
				$command = new Command();                            
                $factureMail = $command->getCommandAsFacture($data['ID']);
                $this->finishandclosepaiementsendmail($factureMail, $data['ID'], $sendmail, $type_paiement, $type);
                            
				$this->view->linksMenu = $this->generateLinksMenu(4);
		
				$this->log("Nouvelle commande : ".$data['REFERENCE'],'info');
				$this->view->verifMessage = 1;
		
				$usernamespace->addresseLiv = array();
				$usernamespace->myFactureValidate = array();
		
				unset($usernamespace->addresseLiv);
				unset($usernamespace->myFactureValidate);
				unset($usernamespace->commandAdded);
		
				$usernamespace->myObjectCaddy = array();
				unset($usernamespace->myObjectCaddy);
                
				$usernamespace->myObjectCaddyFidelite = array();
				unset($usernamespace->myObjectCaddyFidelite);
			} else {
				$this->_redirect('/mon-panier.html');
			}
		}   else {
			$this->_redirect('/connectez-vous.html');
		}
	}
	public function citelispaiementAction() {
		require_once('../library/citelis/configuration/identification.php');
		require_once('../library/citelis/configuration/options.php');
		require_once('../library/citelis/lib/lib_debug.php');
				
		$array = array();
		$payline = new paylineSDK(MERCHANT_ID, ACCESS_KEY, PROXY_HOST, PROXY_PORT, PROXY_LOGIN, PROXY_PASSWORD, PRODUCTION);
		$payline->returnURL = RETURN_URL;
		$payline->cancelURL = CANCEL_URL;
		$payline->notificationURL = NOTIFICATION_URL;
		
		// PAYMENT
		$array['payment']['amount'] = $_POST['amount'];
		$array['payment']['currency'] = PAYMENT_CURRENCY;
		$array['payment']['action'] = PAYMENT_ACTION;
		$array['payment']['mode'] = PAYMENT_MODE;
		
		// ORDER
		$array['order']['ref'] = $_POST['ref'];
		$array['order']['amount'] = $_POST['amount'];
		$array['order']['currency'] = PAYMENT_CURRENCY;
		
		// CONTRACT NUMBERS
		$array['payment']['contractNumber'] = CONTRACT_NUMBER;
		$contracts = explode(";",CONTRACT_NUMBER_LIST);
		$array['contracts'] = $contracts;
		$secondContracts = explode(";",SECOND_CONTRACT_NUMBER_LIST);
		$array['secondContracts'] = $secondContracts;
		
		// EXECUTE
		$result = $payline->doWebPayment($array);
		
		if(isset($result) && $result['result']['code'] == '00000'){		
			//Sauvegarde du token
			$usernamespace = $this->getSession();
			$usernamespace->commandAddedLastTokenCitelis = $result["token"];
			$this->_redirect($result["redirectURL"]);
		} elseif(isset($result)) {
			$this->log("Erreur commande citelis : ".$result['result']['code']. ' '.$result['result']['longMessage'],'err');
			$this->_redirect('/mon-panier-validation.html');
		}
	}
	
	public function paiementcitelisAction() {
		try {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$ispaiementOk = false;
				
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$usernamespace = $this->getSession();
				$this->log("Token recu : ".$this->_request->getParam("token"). ' / Token sauvegard� : '.$usernamespace->commandAddedLastTokenCitelis,'info');
				if ($usernamespace->commandAddedLastTokenCitelis == $this->_request->getParam("token")) {				
					$ispaiementOk = true;
				}
			}

			if ($ispaiementOk) {
				$this->finishandclosepaiement("Pending",$this->_request->getParam("token"), "Mode de paiement : Paiement s�curis� en ligne", 0, true);
			 	$this->render('paiement');
			}  else {
				$this->_redirect('/');
			}
	
		}catch (Zend_Exception $e) {
			$this->log("Erreur : paiementcitelisAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}
	
	public function citelisipnvalidationAction() {
		$this->ipnCitelisListener();
		$this->_redirect('/');
	}
	
	private function ipnCitelisListener() { 
		require_once('../library/citelis/configuration/identification.php');
		require_once('../library/citelis/configuration/options.php');
		require_once('../library/citelis/lib/lib_debug.php');
		try {	
			// GET TOKEN
			$token = $this->_request->getParam("token");
			if(isset($token)){
				$this->log("WebPaymentDetailsRequest - Token : ".$token,'info');
				$array = array();
				$payline = new paylineSDK(MERCHANT_ID, ACCESS_KEY, PROXY_HOST, PROXY_PORT, PROXY_LOGIN, PROXY_PASSWORD, PRODUCTION);
					
				$array['token'] = $token;
	    		$array['version'] = '3';
				// EXECUTE
				$result = $payline->getWebPaymentDetails($array);
				if(isset($result)){
					$command = new Command();
					$currentCommand = $command->fetchRow('TXN_ID = "'.$token.'"');
					$idCommand = $currentCommand["ID"];
					
					$output = print_a($result, 1, true);
					if ($result['result']['code'] == "00000" || $result['result']['code'] == "01001" ) {
						$this->updateCommandByID($idCommand,"Completed", $token,1);
						
						$this->log('CITELIS : IPN-VERIFIED : res : '.$output,'info');
						$this->sendMail($output." \n", $notify_email, $notify_email, 'CITELIS : IPN-VERIFIED');
					} else {
						$this->updateCommandByIDUNVERIFIED($idCommand, 'Incorrect');
						$this->log('CITELIS : IPN-VERIFIED INCORRECT : res : '.$output,'warn');
						$this->sendMail($output." \n"." \n", $notify_email, $notify_email, 'CITELIS : IPN-VERIFIED INCORRECT');
					}
				} else {
					$this->log("WebPaymentDetailsRequest - No results",'info');
				}
			} else {
				$this->log("WebPaymentDetailsRequest - Token Missing ",'info');
			}
		} catch (Zend_Exception $e) {
			$this->log('Erreur : ipnCitelisListener() : '.$e->getTraceAsString(),'err');
		}
  	}
}?>