Current File : /home/karenpetzb/application/modules/backoffice/controllers/SupplierController.php
<?php
class Backoffice_SupplierController extends Modules_Backoffice_Controllers_MainController
{
	
	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Supplier";
		$this->isConnectedWithRole('isSupplier');
	}
	function indexAction()
	{
		$this->_forward('/list');
		
	}
	function searchAction()
	{
		 $this->view->titlePage = "Rechercher un Fournisseur";
		$adminNamespace = $this->getSession();	 
	    $this->view->messageSuccess = "";
		$this->view->messageError = "";
		
	    
	    if ($this->getRequest()->isPost()) {
			$post = $this->getRequest()->getPost();
			
			
			$recherche = '%'.$post['searchValue'].'%';
			
			$this->view->titlePage .= " : ".$post['searchValue']; 
			//Appel model pour listing
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			
			if ($post['searchType'] != 'BREND') {
	    		$select = $supplier->select()
	    				->where($post['searchType'].' LIKE ? ',$recherche)
	    				->order($post['searchType'].' ASC ');
	    		$listsuppliers = $supplier->fetchAll($select)->toArray();
			} else {
				$select = "SELECT s.*
					 FROM supplier AS s
						LEFT JOIN supplier_brend AS sb ON sb.IDSUPPLIER = s.ID";
						if (!empty($post['searchType'])) {
							$select .= " WHERE sb.".$post['searchType']." LIKE '".$recherche."' ";
						}
						
				$select .= " ORDER BY BREND ASC";
				$listsuppliers = $supplier->getAdapter()->fetchAll($select);
			}
			
			$this->view->listsupplierCount = count($listsuppliers);
			$this->view->listsupplier = $listsuppliers;
			
			if ($this->view->listsupplierCount == 0) {
				$this->view->messageError = "Aucun resultats";
			}
	    } 
	}
	function editbrendAction () {
		
		if ($this->getRequest()->isPost()) {
		 //get the form params
			$params = $this->getRequest()->getPost();
			//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())
					   -> addValidator(new Zend_Validate_StringLength(2));
	
            $isShowBrendPage = (int)$params['isshowbrendpage'];
                       
			//Refractor the params
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
			 		'IS_SHOW_BREND_PAGE' => $isShowBrendPage
			);
             
			$supplierBrend = new SupplierBrend();
			$supplier = new Supplier();
			
		 	if ($validator->isValid($dataBrend['BREND'])) {
		 		
			 	try {
			 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."' AND ID <> ".$params['idBrend']);
		 		 	
			 		if (!$isExistBrend) {
			 			$supplierBrend->update($dataBrend, 'ID = '.$params['idBrend']);
				 	 	$this->view->messageSuccess = "La marque a �t� modif�e";
			 		} else {
			 			$this->view->messageError = "La marque existe d�j�";
			 		}
			 	
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				    $this->view->messageError = "La marque existe d�j�";
		    	 	
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 	}
		 	$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
	
	
	function addbrendAction () {
		
		if ($this->getRequest()->isPost()) {
		 //get the form params
			$params = $this->getRequest()->getPost();
			//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())
					   -> addValidator(new Zend_Validate_StringLength(2));
	
				   
			//Refractor the params
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
			 		'IDSUPPLIER' => $filter->filter($params['id']),
					'URL' => ''
			);
			$supplierBrend = new SupplierBrend();
			$supplier = new Supplier();
			
		 	if ($validator->isValid($dataBrend['BREND'])) {
		 		
			 	try {
			 		
			 		
			 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."'");
		 		 	
			 		if (!$isExistBrend) {
			 			if (!empty($_FILES['picture']['name'])) {
			 				$url = $this->uploadNewPicsGetURL('picture');
					 	 	 if ($url != false) {
					 	 	 	$dataBrend['URL'] = $url;
					 	 	 }
			 			}
			 			
				 	 	 $supplierBrend->insert($dataBrend);
				 	 	$this->view->messageSuccess = "La marque a �t� ajout�e";
			 		} else {
			 			$this->view->messageError = "La marque existe d�j�";
			 		}
			 	
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				    $this->view->messageError = "La marque existe d�j�";
		    	 	
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 	}
		 	$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
	
	function delbrendAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		$supplier = new Supplier();
		$supplierBrend = new SupplierBrend();
		if ($this->getRequest()->isPost('delBrendForm')) {
		
			$params = $this->getRequest()->getPost();
			
			try {
				$product = new Product(); 	 
				
				$isExistProduct = $product->fetchRow("IDBREND = ".$params['idBrend']);
		 		 	
			 		if (!$isExistProduct) {
			    		$supplierBrend->delete('ID = '.$params['idBrend']);
			    		
			    		$this->view->messageSuccess = "La marque a �t� supprim�e";
			 		} else {
			 			$this->view->messageError = "La marque est utilis�e par un produit : <b>".$isExistProduct['NOM']."</b>";
			 		}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		 		$this->view->messageError = $e->getMessage();    
			}
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');
	}
function editAction()
    {
    	
		$this->view->titlePage = "Modifier un fournisseur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		 
		//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());
	
		$validatorEmail = new Zend_Validate_EmailAddress();
    	
		$supplier = new Supplier();	
		$supplierBrend = new SupplierBrend();

		if ($this->getRequest()->isPost() && $this->getRequest()->getPost('company')) {
		 	
			//get the form params
			$params = $this->_request->getPost();
			
			//Refractor the params
			$dataSupplier = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'PRENOM' => $filter->filter($params['prenom']),
			 		'COMPANY' => $filter->filter($params['company']),
			 		'ADDRESSE' => $filter->filter($params['address']),
			 		'CP' => $filter->filter($params['cp']),
			 		'VILLE' => $filter->filter($params['ville']),
			 		'EMAIL' => $filter->filter($params['email']),
			 		'TEL' => $filter->filter($params['tel']),
			 		'FAX' => $filter->filter($params['fax']),
			 		'DESCRIPTIONSHORT' => $filter->filter($params['descshort']),
			 		'DESCRIPTIONLONG' => $params['desclong']
			);
			
		 	if ($validator->isValid($dataSupplier['NOM']) &&
			 	$validator->isValid($dataSupplier['PRENOM']) &&
			 	$validator->isValid($dataSupplier['COMPANY']) &&
			 	$validatorEmail->isValid($dataSupplier['EMAIL']) 
		 	) {
		 		
			 	try {
			 		
			 	 $id = (int)$params['id'];
			 	 
			 	 if ( $id > 0) {
			 	 	
		 		 		$isExistSupplier = $supplier->fetchRow("COMPANY LIKE '".$dataSupplier['COMPANY']."' AND ID <> ".$id);
		 		 		
		 		 		if (!$isExistSupplier) {
				 	 		$url = $this->uploadNewPicsGetURL('picture');
					 		if ($url != false) {
						 		$dataSupplier['URL'] = $url;
						 		$supplier->update($dataSupplier,'ID = '.$id);
						 		 $this->view->messageSuccess = "Le fournisseur a �t� modifi�, l'image a �t� upload�e"; 
					 		} else {
					 			 $supplier->update($dataSupplier, 'ID = '.$id);
					 			 $this->view->messageSuccess = "Le fournisseur a �t� modifi�"; 
					 		}	
		 		 		}  else {
					 		 $this->view->messageError= "Le fournisseur existe d�j�"; 
		 		 		} 	
			 	 }
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		    	 	$this->view->populateFormSupplier = $dataSupplier;
			    
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorEmail->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
			   $this->view->populateFormSupplier = $dataSupplier;
		 	}
		 	
		 }
			 if ($this->getRequest()->getParam('id')) {
			 	$id = (int)$this->getRequest()->getParam('id');
			 }
	     	if ($this->getRequest()->isPost('addBrendForm') ||
				 $this->getRequest()->isPost('editSupplierForm') 
			 ) { 
				$params = $this->_request->getPost();
			 	$id = $params['id'];
			 }
		 	if ($id>0) {
		 		$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$id);
		 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$id)->toArray();
		 	}
    }
    
	function addAction()
    {
    	
		$this->view->titlePage = "Ajouter un fournisseur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		 if ($this->_request->isPost('addSupplierForm')) {
		 	
		 	//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());
			//valideurs pour FILE
			$validatorFile = new Zend_Validate();
			$validatorFile -> addValidator(new Zend_Validate_File_Exists())
					   -> addValidator(new Zend_Validate_File_IsImage());
					   
			$validatorEmail = new Zend_Validate_EmailAddress();
			 	   
			//get the form params
			$params = $this->_request->getPost();
			
			//Refractor the params
			$dataSupplier = array (
			 		'NOM' => $filter->filter($params['lastname']),
			 		'PRENOM' => $filter->filter($params['firstname']),
			 		'COMPANY' => $filter->filter($params['company']),
			 		'ADDRESSE' => $filter->filter($params['address']),
			 		'CP' => $filter->filter($params['cp']),
			 		'VILLE' => $filter->filter($params['ville']),
			 		'EMAIL' => $filter->filter($params['email']),
			 		'TEL' => $filter->filter($params['tel']),
			 		'FAX' => $filter->filter($params['fax']),
					'URL' => ''
			);
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
					'URL' => '',
					'IDSUPPLIER' => ''
			);
		 	if (
		 		$validator->isValid($dataBrend['BREND']) &&
		 		$validator->isValid($dataSupplier['NOM']) &&
			 	$validator->isValid($dataSupplier['PRENOM']) &&
			 	$validator->isValid($dataSupplier['COMPANY']) &&
			 	$validatorEmail->isValid($dataSupplier['EMAIL']) 
		 	) {
		 		 	try {
		 		 		$supplier = new Supplier();
		 		 		$supplierBrend = new SupplierBrend();
		 		 		
		 		 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."'");
		 		 		$isExistSupplier = $supplier->fetchRow("COMPANY LIKE '".$dataSupplier['COMPANY']."'");
		 		 		
		 		 		if (!$isExistBrend && !$isExistSupplier) {
					 		$url = $this->uploadNewPicsGetURL('picture');
					 		if ($url != false) {
						 		$dataBrend['URL'] = $url;
						 		$dataSupplier['URL'] = $url;
					 		}	
						 	 
					    	 $supplier->insert($dataSupplier);
					    	 
					    	 $lastid = $supplier->getAdapter()->lastInsertId();
					    	 $dataBrend['IDSUPPLIER'] = $lastid;
					    	 
					    	 
							 $supplierBrend->insert($dataBrend);
					    	
					    	 $this->view->messageSuccess = "Le fournisseur a �t� ajout�"; 
		 		 		} else {
		 		 			$this->view->messageError = "La marque ou le fournisseur existe d�j�"; 
					    	$this->view->populateFormSupplier = $dataSupplier;
					    	$this->view->populateFormBrend = $dataBrend;
		 		 		} 
				 	} catch (Zend_Exception $e) {
				 		
					$this->log($e->getMessage(),'err');
				    	$this->view->populateFormSupplier = $dataSupplier;
				    	$this->view->populateFormBrend = $dataBrend;
					}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorEmail->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorFile->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
			    $this->view->populateFormSupplier = $dataSupplier;
			    $this->view->populateFormBrend = $dataBrend;
		 	}
		 	
		 }
    }
    
	function listAction()
	{
	    $this->view->titlePage = "Gestion des fournisseurs";
	    $adminNamespace = $this->getSession();	
	    
	    //Gestion des tris
    	$table = 'COMPANY';
		$tri = 'ASC';
		
	    if ($this->_request->getParam('col')) 
	    {
	    	$adminNamespace->triSupplierCol = $this->_request->getParam('col');
	    	($adminNamespace->triSupplierSens == 'ASC') ? $adminNamespace->triSupplierSens = 'DESC' : $adminNamespace->triSupplierSens = 'ASC';
	    } 
		 if (isset($adminNamespace->triSupplierCol)) {
	    	$table = $adminNamespace->triSupplierCol;
	    	$tri = $adminNamespace->triSupplierSens;
	    }
	    
	    //Appel model pour listing
		$supplier = new Supplier();
		
		$sql = "SELECT s.ID ID, s.COMPANY COMPANY,s.NOM NOM, s.PRENOM PRENOM, s.ADDRESSE ADDRESSE, s.CP CP, s.VILLE VILLE, s.EMAIL EMAIL, s.TEL TEL, s.FAX FAX,
					 s.URL URL
				FROM supplier AS s
				ORDER BY ".$table." ".$tri;
    	$result = $supplier->getAdapter()->fetchAll($sql);
	    
    	$this->view->listsupplier = $result;
	    
	}
	
	function delAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$product = new Product();
					$supplier = new Supplier();
					$supplierBrend = new SupplierBrend();
					
					$sql = "
						SELECT DISTINCT p.NOM NOMPRODUCT , sb.BREND BREND 
						FROM product AS p
						LEFT JOIN supplier_brend AS sb ON sb.ID = p.IDBREND
						LEFT JOIN supplier AS s ON s.ID = sb.IDSUPPLIER
						WHERE s.ID = ".$id;
					$isExistProduct = $product->getAdapter()->fetchRow($sql);
		 		 		
	 		 		if (!$isExistProduct) {
	 		 			$supplier->delete('ID = '.$id);
	    		
	 		 			$supplierBrend->delete('IDSUPPLIER = '.$id);
	    				$this->view->messageSuccess = "Le fournisseur a �t� supprim�";
	 		 		} else {
	 		 			$this->view->messageError = "La marque : <b>".$isExistProduct['BREND']."</b> poss�de des produits : <b>".$isExistProduct['NOMPRODUCT']."</b>";
			 		
	 		 		}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			 		$this->view->messageError = $e->getMessage();    
				}
			}
		}
		$this->_forward('/list');	
		
	}
	
function uploadNewPicsGetURL($nomTemp) {
		if(!empty($_FILES[$nomTemp]) && !empty($_FILES[$nomTemp]['name'])) {
			$nomOrigine = $_FILES[$nomTemp]['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
			    $this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {    
			    // Copie dans le repertoire du script avec un nom
			    $repertoireDestination = 'items/supplier/';
				$this->checkDirectoryExist($repertoireDestination);

				$nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
                $fileoriginal = $repertoireDestination.$nomDestination;
			
			    if (move_uploaded_file($_FILES[$nomTemp]["tmp_name"],$fileoriginal)) {
			    	 	//Resize picture
                        $info = getimagesize($fileoriginal) ;
                        list($width_old, $height_old) = $info;
                        $maxwidth = $this->FeaturePictureResizeWidth;
                        $maxheight = $this->FeaturePictureResizeHeight;
                            
                        if ($width_old > $maxwidth || $height_old > $maxheight) {     
                            Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                        }  
                        
						$data = array (
					 		'URL' => $fileoriginal
						);
			        	return $data['URL'];
			    	 
			    } else {
			        return false;
			    }
			}
		}
		
		return false;
	}

	
	function setpictureAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			try {
				$data = array (
				 		'URL' => $params['picture']
					);
					if ((int)$params['idSelected']>0) {
						$supplierBrend->update($data,'ID = '.$params['idSelected']);
		    			$this->view->messageSuccess = "L'image de la marque a �t� modifi�e";
					} else {
						$this->view->messageError = "Vous devez selectionner une marque";
					}
				
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			 		$this->view->messageError = $e->getMessage();    
			}
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
		
	}

	function erasepictureAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			$product = new Product();
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			try {
				$sql = "
						SELECT DISTINCT p.NOM NOMPRODUCT , sb.BREND BREND 
						FROM product AS p
						LEFT JOIN supplier_brend AS sb ON sb.ID = p.IDBREND
						LEFT JOIN supplier AS s ON s.ID = sb.IDSUPPLIER
						WHERE sb.URL = '".$params['picture']."'";
				$isExistProduct = $product->getAdapter()->fetchRow($sql);
		 		 		
					
				if (!$isExistProduct) {
					unlink($params['picture']);
					$data = array (
			 		'URL' => ''
					);
					$supplierBrend->update($data,"URL = '".$params['picture']."'");
		    		
		    		$this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";	
				} else {	
					$this->view->messageError = "La marque : <b>".$isExistProduct['BREND']."</b> poss�de des produits : <b/>".$isExistProduct['NOMPRODUCT']."</b>";
			 		
				}
				
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		 		$this->view->messageError = $e->getMessage();    
			}
		
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
}
?>