<?php
/* **
 * @application PhpMyShopping
 * @part        Admin Boutique
 * @file        class.shop.php
 * @path        ./admin/include/
 * @author      Stephane DINE <stephane@phpmyshopping.org>
 * @site        http://www.phpmyshopping.org
 * @license     http://www.php.net/license/3_0.txt  PHP License 3.0
 *
 * PHP version 5
 *
 * Classe Shop
 */

require_once 'class.lib.php';

class Shop extends Lib
{
	/**
	 * Largeur de l'image affichee dans le formulaire de modification d'une categorie
	 * @access public
	 */
	//public $ImgCatWA;

	/**
	 * Hauteur de l'image affichee dans le formulaire de modification d'une categorie
	 * @access public
	 */
	//public $ImgCatHA;

	/**
	 * Attribut des produits
	 * @access public
	 */
	public $ProductName;
	public $ProductDescription;
	public $ProductPrice;
	public $ProductRemiseType;
	public $ProductRemise;
	public $ProductStock;
	public $ProductIdCat;
	public $ProductIdSubCat;
	public $CategoryName;
	public $SubCategoryName;
	public $NbImage;
	//public $CategoryImage;
	public $metatags_charset = 'utf-8'; //'iso-8859-1';
	public $basket_total     = 0;
	public $orderWeightSum   = 0;
	public $orderPriceArray;
	public $orderTaxProductArray;




	/** ****************************************************************************************************
	 * Constructeur
	 */
	public function __construct($nbmax = 0)
	{
		$this->nbmax = $nbmax;
	}




	/** ****************************************************************************************************
	 * Methode checkSession
	 *
	 * @desc   Verrification de l'existance des variables de session $ID*
	 *         Si inexistances ou non affectees, creation de celles-ci
	 * @param  array $session Variables de sessiosn a verrifier
	 * @access public
	 * @return
	 */
	public function checkSession()
	{
		/**
		 * Verrification des variables de session IDC et IDB
		 */
		if (((!isset($_SESSION['IDC'])) or (!$_SESSION['IDC'])) and ((!isset($_SESSION['IDB'])) or (!$_SESSION['IDB']))) {
			/**
			 * $_SESSION['IDC'] nook
			 * $_SESSION['IDB'] nook
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => '$_SESSION[\'IDC\'] nook - $_SESSION[\'IDB\'] nook'));
			$result = $this->createTempCustomer();
			$_SESSION['IDC'] = $result['ID_Customer'];
			$_SESSION['IDB'] = $result['ID_Basket'];
		}

		/**
		 * Verrification de la variable de session IDC
		 */
		if ((!isset($_SESSION['IDC'])) or (!$_SESSION['IDC'])) {
			/**
			 * $_SESSION['IDC'] nook
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => '$_SESSION[\'IDC\'] nook'));
			$result = $this->createTempCustomer();
			$_SESSION['IDC'] = $result['ID_Customer'];
			$_SESSION['IDB'] = $result['ID_Basket'];
		}

		/**
		 * Verrification de la variable de session IDB
		 */
		if ((!isset($_SESSION['IDB'])) or (!$_SESSION['IDB'])) {
			/**
			 * $_SESSION['IDB'] nook
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => '$_SESSION[\'IDB\'] nook'));
			$_SESSION['IDB'] = $this->createBasket($_SESSION['IDC']);
		}

        /**
         * Verrification de la variable de session IDI
         */
        if ((!isset($_SESSION['IDI'])) or (!$_SESSION['IDI'])) {
            /**
             * $_SESSION['IDB'] nook
             */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => '$_SESSION[\'IDI\'] nook'));
            $_SESSION['IDI'] = 0;
        }

        $this->log(__FILE__, array('methode' => __METHOD__, 'variable' => array('$_SESSION[\'IDC\']' => $_SESSION['IDC'], '$_SESSION[\'IDB\']' => $_SESSION['IDB'], '$_SESSION[\'IDI\']' => $_SESSION['IDI'])));
	}




	/** ****************************************************************************************************
	 * Methode getCompanyName
	 *
	 * @desc   Retourne le nom de la societe a laquelle appartient la boutique ainsi que les champs
	 *         ApeCode et SirenCode
	 * @return string
	 * @access public
	 */
	public function getCompanyName()
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$query = $this->query('SELECT CompanyName FROM Shop');
		$result = mysql_fetch_array($query);
		$result_array = array_map('htmlentities', $result);

		return $result_array;
	}




	/** ****************************************************************************************************
	 * Methode listCategory
	 *
	 * @desc   Genere la liste des categories pour une boutique
	 * @return array
	 * @access public
	 */
	public function listCategory()
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$sql = 'SELECT cat.ID_Category, CategoryName
				FROM Category AS cat
				LEFT JOIN Product AS pro ON cat.ID_Category = pro.ID_Category
				WHERE cat.Status = "E"
				AND pro.Status = "E"
				AND (DateEnd > CONCAT(DATE(NOW()), \' \', TIME(NOW())) OR DateEnd LIKE "0%")
				GROUP BY CategoryName';

		$query = $this->query($sql);

		while ($result = mysql_fetch_array($query)) {
			$data[] = array('ID_Category'  => $result['ID_Category'],
							'CategoryName' => htmlentities($this->myutf8_decode($result['CategoryName'])),
							'CategoryLink' => $this->rewriteUrl('index.php?C='.$result['ID_Category']),
							'SubCategory'  => $this->listSubCategory($result['ID_Category']));
		}

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode listSubCategory
	 *
	 * @desc   Genere la liste des sous-categories d'une categorie donnee
	 * @param  int $ID_Category Identifiant de la categorie
	 * @return array
	 * @access public
	 */
	public function listSubCategory($ID_Category)
	{
        $this->log(__FILE__, array('methode' => __METHOD__, 'variable' => array('$ID_Category' => $ID_Category)));

		$sql = 'SELECT scat.ID_SubCategory, SubCategoryName
				FROM SubCategory AS scat
				LEFT JOIN Product AS pro ON pro.ID_SubCategory = scat.ID_SubCategory
				WHERE pro.ID_Category = '.$ID_Category.'
				AND scat.Status = "E"
				AND pro.Status = "E"
				AND (DateEnd > CONCAT(DATE(NOW()), \' \', TIME(NOW())) OR DateEnd LIKE "0%")
				GROUP BY SubCategoryName';

		$query = $this->query($sql);

		while ($result = @mysql_fetch_array($query)) {
			$data[] = array('ID_SubCategory'  => $result['ID_SubCategory'],
							'SubCategoryName' => htmlentities($this->myutf8_decode($result['SubCategoryName'])),
							'SubCategoryLink' => $this->rewriteUrl('index.php?C='.$ID_Category.'&SC='.$result['ID_SubCategory']));
		}

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode listProductCategory
	 *
	 * @desc   Genere la liste des produits pour une categorie donnee
	 * @param  int $ID_Category    Identifiant de la categorie
	 * @param  int $ID_SubCategory Identifiant de la sous-categorie
	 * @return array
	 * @access public
	 */
	public function listProductCategory($debut, $ID_Category = 0, $ID_SubCategory = 0)
	{
        $this->log(__FILE__, array('methode' => __METHOD__, 'variable' => array('$debut' => $debut, '$ID_Category' => $ID_Category, '$ID_SubCategory' => $ID_SubCategory)));

		if ($ID_Category > 0) {
			$addSqlCat = 'AND pr.ID_Category = '.$ID_Category;
		}

		if ($ID_SubCategory > 0) {
			$addSqlSCat = 'AND pr.ID_SubCategory = '.$ID_SubCategory;
		}

		/**
		 * Selection des donnees du produit
		 */
		$sqlProduct = '
		SELECT
			ID_Product,
			pr.ID_Category,
			ProductName,
			ProductStock,
			pr.NbImage,
			CalculPrixTTC(ProductPrice, TaxValue) AS ProductPrice,
			CalculPrixTTC((ProductPrice - SalePrice), TaxValue) AS ProductPrice_RemisePrixFixe,
			CalculPrixTTC((ProductPrice - ROUND(((ProductPrice / 100) * SalePrice), 2)), TaxValue) AS ProductPrice_RemisePoucentage,
			CategoryName,
			SalePriceType,
			SalePrice
		FROM Product AS pr
		LEFT JOIN Tax AS tx ON pr.ID_Tax = tx.ID_Tax
		LEFT JOIN Category AS ct ON pr.ID_Category = ct.ID_Category
		LEFT JOIN SubCategory AS sc ON pr.ID_SubCategory = sc.ID_SubCategory
		WHERE pr.Status = "E"
		AND ct.Status = "E"
		AND sc.Status = "E"
		'.$addSqlCat.'
		'.$addSqlSCat.'
		AND (
		  pr.DateEnd > CONCAT(DATE(NOW()), \' \', TIME(NOW()))
		  OR pr.DateEnd LIKE "0%"
		)
		AND (
		  (
			ManageStock = "1"
			AND ProductStock > 0
			AND EmptyStockSale = "0"
		  )
		  OR
		  (
			(ManageStock = "0" OR ManageStock = "1")
			AND ProductStock >= 0
			AND EmptyStockSale = "1"
		  )
		)
		AND pr.ID_Tax = tx.ID_Tax
		ORDER BY pr.DateAdded DESC
		LIMIT '.$debut.', '.$this->nbmax;

		$queryProduct = $this->query($sqlProduct);

		while ($resultProduct = @mysql_fetch_array($queryProduct)) {
			if (strlen($resultProduct['ProductName']) > 25) {
				$productName = htmlentities($this->myutf8_decode(substr($resultProduct['ProductName'], 0, 20))).'...';
			} else {
				$productName = htmlentities($this->myutf8_decode($resultProduct['ProductName']));
			}

			/**
			 * Image du produit
			 */
			if ($resultProduct['NbImage'] > 0) {
				$id_p       = $resultProduct['ID_Product'];
				$im_n       = substr($resultProduct['NbImage'], 0, 1);
				$pr_n       = $resultProduct['ProductName'];
				$imgName    = $this->printImage('./images/product_big/', $id_p.'_'.$im_n);
				$imgProduct = '<a href="./images/product_big/'.$imgName['name'].'" class="lightwindow page-options" title="'.$resultProduct['ProductName'].'"><i></i><img src="./images/product_mini/'.$imgName['name'].'" alt="'.$pr_n.'" title="'.$pr_n.'" /></a>';
			} else {
				$imgProduct = '<img src="./tpl/template/images_shop/no_photo.jpg" alt="" title="Pas de photo" />';
			}

			/**
			 * Definition du type de remise et calcul du prix
			 */
			switch($resultProduct['SalePriceType']) {
			case '0': /* Aucune remise */
				$salePrice = '0';
				break;

			case '1': /* Remise en % sur le prix HT */
				$salePrice = number_format($resultProduct['ProductPrice_RemisePoucentage'], 2, ',', '');
				break;

			case '2': /* Remise en euros sur le prix HT */
				$salePrice = number_format($resultProduct['ProductPrice_RemisePrixFixe'], 2, ',', '');
				break;
			}

			$data_product[] = array('ID_Category'  => $resultProduct['ID_Category'],
									'ID_Product'   => $resultProduct['ID_Product'],
									'ProductName'  => $productName,
									'ProductPrice' => number_format($resultProduct['ProductPrice'], 2, ',', ''),
									'Remise'       => $salePrice,
									'ProductLink'  => $this->rewriteUrl('detail_article.php?C='.$resultProduct['ID_Category'].'&P='.$resultProduct['ID_Product']),
									'ProductImage' => $imgProduct);
		}

		return $data_product;
	}




	/** ****************************************************************************************************
	 * Methode nbProductToShop
	 *
	 * @desc   Retourne le nombre de produits d'une boutique
	 * @param  int $ID_Category Identifiant de la categorie
	 * @return int Nombre de produits
	 * @access public
	 */
	public function nbProductToShop($ID_Category = 0, $ID_SubCategory = 0)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		if ((isset($ID_Category)) and ($ID_Category > 0)) {
			$addSqlCat = 'AND Product.ID_Category = '.$ID_Category;
		} else {
			$addSqlCat = '';
		}

		if ($ID_SubCategory > 0) {
			$addSqlSCat = 'AND Product.ID_SubCategory = '.$ID_SubCategory;
		} else {
			$addSqlSCat = '';
		}

		$sql = 'SELECT COUNT(Product.ID_Product) AS NbProduct
				FROM Product
				LEFT JOIN Category ON Product.ID_Category = Category.ID_Category
				LEFT JOIN SubCategory ON Product.ID_SubCategory = SubCategory.ID_SubCategory
				WHERE Product.Status = "E"
				AND Category.Status = "E"
				AND SubCategory.Status = "E"
				'.$addSqlCat.'
				'.$addSqlSCat.'
				AND (
					DateEnd > CONCAT(DATE(NOW()), \' \', TIME(NOW()))
					OR DateEnd = "0000-00-00 00:00:00"
				)
				AND (
				  (
					ManageStock = "1"
					AND ProductStock > 0
					AND EmptyStockSale = "0"
				  )
				  OR
				  (
					(ManageStock = "0" OR ManageStock = "1")
					AND ProductStock >= 0
					AND EmptyStockSale = "1"
				  )
				)';

		$query = $this->query($sql);
		$result = @mysql_fetch_array($query);

		return $result['NbProduct'];
	}




	/** ****************************************************************************************************
	 * Methode createTempCustomer
	 *
	 * @desc   Creation d'un client temporaire et initialisation d'un panier vide
	 * @return array/bool Identifiant du client et du panier venant d'etre cree
	 * @access public
	 */
	public function createTempCustomer()
	{
		/**
		 * Ajout des donnees dans les tables Customer et CustomertoShop
		 */
		$dataCustomer['Password'] = $this->password_generator();
		$ID_Customer = $this->insert_sql('Customer', $dataCustomer, 'SHA1');
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Creation du client '.$ID_Customer));

		/**
		 * Creation du panier du client
		 */
		$ID_Basket = $this->createBasket($ID_Customer);

		if (($ID_Customer != false) and ($ID_Basket != false)) {
			return array('ID_Customer' => $ID_Customer, 'ID_Basket' => $ID_Basket);
		} else {
			return false;
		}
	}




	/** ****************************************************************************************************
	 * Methode createBasket
	 *
	 * @desc   Creation du panier du client
	 * @param  int $ID_Customer Identifiant du client
	 * @return int/bool Identifiant du panier venant d'etre cree
	 * @access public
	 */
	public function createBasket($ID_Customer)
	{
		$dataBasket['ID_Customer'] = $ID_Customer;
		$ID_Basket = $this->insert_sql('Basket', $dataBasket);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Creation du panier '.$ID_Basket, 'variable' => array('$ID_Customer' => $ID_Customer)));

		if ($ID_Basket != false) {
			return $ID_Basket;
		} else {
			return false;
		}
	}




	/** ****************************************************************************************************
	 * Methode checkProduct
	 *
	 * @desc   Verification de la dispo produit avant ajout au panier
	 * @param  int $ID_Basket   Identifiant du panier
	 * @param  int $ID_Customer Identifiant du client
	 * @param  int $ID_Product  Identifiant du produit
	 * @return bool
	 * @access public
	 */
	public function checkProduct($ID_Basket, $ID_Product, $Quantity)
	{
        $v = array('$ID_Basket' => $ID_Basket, '$ID_Product' => $ID_Product, '$Quantity' => $Quantity);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Verification dispo produit', 'variable' => $v));

		/**
		 * Recuperation d'infos sur le produit concerne
		 */
		$sqlProduct    = 'SELECT ProductStock, ManageStock, EmptyStockSale FROM Product WHERE ID_Product = '.$ID_Product;
		$queryProduct  = $this->query($sqlProduct);
		$resultProduct = mysql_fetch_array($queryProduct);

		if ($resultProduct['ManageStock'] == '0') {
			/**
			 * Pas de gestion du stock
			 */
			$this->addProductInBasket($ID_Basket, $ID_Product, $Quantity);

			return true;
		} else {
			/**
			 * Gestion du stock -> on verifie donc si on peut vendre quand le stock est a 0
			 */
			if ($resultProduct['EmptyStockSale'] == '0') {
				/**
				 * Pas autorise si le stock est epuise
				 * -> on verifie que la quantite commandee ne depasse pas celle qui est en stock
				 */

				/**
				 * On recupere la quantite deja commandee presente dans le panier
				 */
				$sqlBasket = 'SELECT Quantity FROM BasketDetail WHERE ID_Basket = '.$ID_Basket.' AND ID_Product = '.$ID_Product;
				$querybasket = $this->query($sqlBasket);
				$resultBasket = mysql_fetch_array($querybasket);

				if (mysql_num_rows($querybasket) > 0) {
					$productQuantity = $resultBasket['Quantity'] + $Quantity;
				} else {
					$productQuantity = $Quantity;
				}

				if ($resultProduct['ProductStock'] >= $productQuantity) {
					$this->addProductInBasket($ID_Basket, $ID_Product, $Quantity);

					return true;
				} else {
					return false;
				}
			} else {
				/**
				 * Vente autorise
				 */
				$this->addProductInBasket($ID_Basket, $ID_Product, $Quantity);

				return true;
			}
		}
	}




	/** ****************************************************************************************************
	 * Methode addProductInBasket
	 *
	 * @desc   Ajout du produit dans la table Basket et BasketDetail
	 * @param  int $ID_Basket   Identifiant du panier
	 * @param  int $ID_Customer Identifiant du client
	 * @param  int $ID_Product  Identifiant du produit
	 * @return bool
	 * @access public
	 */
	public function addProductInBasket($ID_Basket, $ID_Product, $Quantity)
	{
        $v = array('$ID_Basket' => $ID_Basket, '$ID_Product' => $ID_Product, '$Quantity' => $Quantity);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Ajout/modif du produit dans le panier', 'variable' => $v));

		/**
		 * Verrification si l'article commande n'est pas deja present dans
		 * la table BasketDetail, si c'est le cas on change la valeur du
		 * champ Quantity, sinon on passe a l'etape suivante
		 */
		$sqlVerrifQty = 'SELECT ID_BasketDetail, Quantity
						 FROM BasketDetail AS bd
						 LEFT JOIN Basket AS bs ON bd.ID_Basket = bs.ID_Basket
						 WHERE bs.ID_Basket = '.$ID_Basket.'
						 AND bd.ID_Product = '.$ID_Product.';';
		$queryVerrifQty = $this->query($sqlVerrifQty);

		if (mysql_num_rows($queryVerrifQty) > 0) {
			/**
			 * Mise a jour de la quantite pour l'article commande
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Mise a jour quantite produit'));
			$qty = mysql_fetch_array($queryVerrifQty);
			$sqlUpdateQty = 'UPDATE BasketDetail
							 SET Quantity = ('.$qty['Quantity'].' + '.$Quantity.')
							 WHERE ID_BasketDetail = '.$qty['ID_BasketDetail'];
			$this->query($sqlUpdateQty);
		} else {
			/**
			 * Ajout des donnees dans la table BasketDetail
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Ajout produit'));
			$data['ID_Basket']  = $ID_Basket;
			$data['ID_Product'] = $ID_Product;
			$data['Quantity']   = $Quantity;
			$ID_BasketDetail = $this->insert_sql('BasketDetail', $data);
		}

		return true;
	}




	/** ****************************************************************************************************
	 * Methode deleteProductInBasket
	 *
	 * @desc   Supprime un produit du panier
	 * @param  int $ID_Basket  Identifiant du panier
	 * @param  int $ID_Product Identifiant du produit
	 * @return bool
	 * @access public
	 */
	public function deleteProductInBasket($ID_Basket, $ID_Product)
	{
        $v = array('$ID_Basket' => $ID_Basket, '$ID_Product' => $ID_Product);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Suppression du produit du panier', 'variable' => $v));

		$this->delete_tuple('BasketDetail', 'ID_Basket', $ID_Basket, 'ID_Product', $ID_Product);
	}




	/** ****************************************************************************************************
	 * Methode basketDetail
	 *
	 * @desc   Retourne le contenu du panier dont l'identifiant est donne en parametre
	 * @param  int $ID_Basket Identifiant du panier
	 * @return array|string
	 * @access public
	 */
	public function basketDetail($ID_Basket)
	{
        $v = array('$ID_Basket' => $ID_Basket);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Contenu du panier', 'variable' => $v));

		/**
		 * Recuperation des donnees pour la creation de la liste
		 */
		$sql = 'SELECT ID_BasketDetail,
					   bad.ID_Product AS ID_Product,
					   Quantity,
					   Weight,
					   ProductName,
					   Reference,
					   ManageStock,
					   ProductStock,
					   EmptyStockSale,
					   NbImage,
					   SalePriceType,
					   CalculPrixTTC(ProductPrice, TaxValue) AS ProductPriceUnit,
					   CalculPrixTTC((ProductPrice - ROUND(((ProductPrice / 100) * SalePrice), 2)), TaxValue) AS ProductPrice_RemisePoucentage,
					   CalculPrixTTC((ProductPrice - SalePrice), TaxValue) AS ProductPrice_RemisePrixFixe,
					   (CalculPrixTTC(ProductPrice, TaxValue) * Quantity) AS ProductPriceQte,
					   (CalculPrixTTC((ProductPrice - ROUND(((ProductPrice / 100) * SalePrice), 2)), TaxValue) * Quantity) AS ProductPriceQte_RemisePoucentage,
					   (CalculPrixTTC((ProductPrice - SalePrice), TaxValue) * Quantity) AS ProductPriceQte_RemisePrixFixe,
					   (ROUND(((ProductPrice / 100) * TaxValue), 2) * Quantity) AS TaxProduct,
					   (ROUND((((ProductPrice - ROUND(((ProductPrice / 100) * SalePrice), 2)) / 100) * TaxValue), 2) * Quantity) AS TaxProduct_RemisePoucentage,
					   (ROUND((((ProductPrice - SalePrice) / 100) * TaxValue), 2) * Quantity) AS TaxProduct_RemisePrixFixe
				FROM BasketDetail AS bad
				LEFT JOIN Product AS pro ON bad.ID_Product = pro.ID_Product
				LEFT JOIN Tax AS tax ON pro.ID_Tax = tax.ID_Tax
				WHERE bad.ID_Basket = '.$ID_Basket;

		$query = $this->query($sql);

		if (@mysql_num_rows($query) > 0) {
			/**
			 * Le panier contient au moins un produit
			 */
			$cpt = 0;

			while ($resultProduct = mysql_fetch_array($query)) {
				if ($resultProduct['ManageStock'] == '0') {
					/**
					 * Pas de gestion du stock
					 */
					$nbLoop = 20;
				} else {
					/**
					 * Gestion du stock
					 */
					if ($resultProduct['EmptyStockSale'] == '1') {
						$nbLoop = 20;
					} else {
						$nbLoop = $resultProduct['ProductStock'] + 1;
					}
				}

				/**
				 * D?finition du type de remise et calcul du prix
				 */
				switch($resultProduct['SalePriceType']) {
				case '0': /* Aucune remise */
					$priceUnit = number_format($resultProduct['ProductPriceUnit'], 2, ',', '');
					$priceQte  = $resultProduct['ProductPriceQte'];
					$tax = $resultProduct['TaxProduct'];

					break;

				case '1': /* Remise en % sur le prix HT */
					$priceUnit = number_format($resultProduct['ProductPrice_RemisePoucentage'], 2, ',', '');
					$priceQte  = $resultProduct['ProductPriceQte_RemisePoucentage'];
					$tax = $resultProduct['TaxProduct_RemisePoucentage'];

					break;

				case '2': /* Remise en euros sur le prix HT */
					$priceUnit = number_format($resultProduct['ProductPrice_RemisePrixFixe'], 2, ',', '');
					$priceQte  = $resultProduct['ProductPriceQte_RemisePrixFixe'];
					$tax = $resultProduct['TaxProduct_RemisePrixFixe'];

					break;
				}


				$priceArray[$cpt]  = $priceQte;
				$weightArray[$cpt] = $resultProduct['Weight'];
				$TaxProduct[$cpt]  = $tax;
				$cpt++;

				if ($resultProduct['NbImage'] > 0) {
					$imgNameArray = $this->printImage('./images/product_big/', $resultProduct['ID_Product'].'_'.substr($resultProduct['NbImage'], 0, 1));
					$imgName = $imgNameArray['name'];
				} else {
					$imgName = '&nbsp;';
				}

				$data[] = array('ID_Product'      => $resultProduct['ID_Product'],
								'ID_BasketDetail' => $resultProduct['ID_BasketDetail'],
								'Reference'       => $resultProduct['Reference'],
								'ProductName'     => $resultProduct['ProductName'],
								'PriceUnit'       => $priceUnit,
								'PriceQte'        => number_format($priceQte, 2, ',', ''),
								'LoopQte'         => $this->makeSelectLoop($nbLoop, $resultProduct['Quantity']),
								'NbImage'         => $resultProduct['NbImage'],
								'ImgName'         => $imgName,
								'Quantity'        => $resultProduct['Quantity']);
			}

			$this->basket_total         = number_format(array_sum($priceArray), 2, ',', '');
			$this->orderTaxProductArray = number_format(array_sum($TaxProduct), 2, ',', '');
			$this->orderPriceArray      = $priceArray;

			/**
			 * Somme du poids des articles pour le calcul des frais d'envoi
			 */
			if (array_sum($weightArray)) {
				$this->orderWeightSum = array_sum($weightArray);
			}

			return $data;
		} else {
			/**
			 * Le panier ne contient aucuns produits
			 */
			return 'empty';
		}
	}




	/** ****************************************************************************************************
	 * Methode basketStateDetail
	 *
	 * @desc   Affiche le contenu du panier avec le nom de l'article et la quantite commandee
	 * @param  int $ID_Basket Identifiant du panier
	 * @return array|string
	 * @access public
	 */
	public function basketStateDetail($ID_Basket)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		/**
		 * Recuperation des donnees pour la creation de la liste des articles du panier
		 */
		$sql = 'SELECT bd.ID_Product, Quantity, ProductName
				FROM BasketDetail AS bd
				LEFT JOIN Product AS po ON po.ID_Product = bd.ID_Product
				WHERE ID_Basket = '.$ID_Basket;

		$query = $this->query($sql);

		while ($resultProduct = mysql_fetch_array($query)) {
			/**
			 * Tranconnage du nom du produit si celui-ci depasse le nombre de caracteres definis
			 */
			if (strlen($resultProduct['ProductName']) > 25) {
				$productName = substr($resultProduct['ProductName'], 0, 25).'...';
			} else {
				$productName = $resultProduct['ProductName'];
			}

			$data[] = array('ProductName' => $productName, 'Quantity' => $resultProduct['Quantity']);
		}

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode orderDetail
	 *
	 * @desc   Affiche le detail de la commande
	 * @param  int $ID_Basket Identifiant du panier
	 * @return string
	 * @access public
	 */
	public function orderDetail($ID_Basket)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		/**
		 * Recuperation des donnees pour la creation de la liste des articles du panier
		 */
		$cpt = 0;
		$sql = 'SELECT ID_BasketDetail, bd.ID_Product AS ID_Product, Quantity, Weight, ProductName, Reference,
					   CalculPrixTTC(ProductPrice, TaxValue) AS ProductPriceUnit,
					   (CalculPrixTTC(ProductPrice, TaxValue) * Quantity) AS ProductPriceQte
				FROM BasketDetail AS bd
				LEFT JOIN Product AS pr ON bd.ID_Product = pr.ID_Product
				LEFT JOIN Tax AS tx ON pr.ID_Tax = tx.ID_Tax
				WHERE bd.ID_Basket = '.$ID_Basket;

		$query = $this->query($sql);

		if (mysql_num_rows($query) > 0) {
			/**
			 * Le panier contient au moins un produit
			 */
			while ($resultProduct = mysql_fetch_array($query)) {
				$priceUnit         = number_format($resultProduct['ProductPriceUnit'], 2, ',', ' ');
				$priceQte          = $resultProduct['ProductPriceQte'];
				$priceArray[$cpt]  = $priceQte;
				$weightArray[$cpt] = $resultProduct['Weight'];
				$cpt++;

				/**
				 * Affichage des donnees
				 */
				$data[] = array('Reference'   => $resultProduct['Reference'],
								'ProductName' => $resultProduct['ProductName'],
								'Price'       => $priceUnit,
								'Quantity'    => $resultProduct['Quantity'],
								'PriceLine'   => number_format($priceQte, 2, ',', ''));
			}

			if (array_sum($weightArray)) {
				$this->orderWeightSum = array_sum($weightArray);
			}

			$this->orderPriceArray = $priceArray;
		}

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode orderCostDatail
	 *
	 * @desc   Affichage des frais d'envois
	 * @param  int $ID_Basket   Identifiant du panier
	 * @param  int $ID_Customer Identifiant du client
	 * @return string
	 * @access public
	 */
	public function orderCostDatail($ID_Basket, $ID_Customer)
	{
		$v = array('$ID_Basket' => $ID_Basket, '$ID_Customer' => $ID_Customer);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Affichage des frais d\'envois', 'variable' => $v));

        /**
		 * Affichage du total de la commande et des frais d'envois avec les formules disponibles
		 */
			$sqlFrais = 'SELECT MIN(Weight), Cost, CarrierName, PackageName, pac.ID_Package AS ID_Package
						 FROM Cost AS cos
						 LEFT JOIN Package AS pac ON pac.ID_Package = cos.ID_Package
						 LEFT JOIN Zone AS zon ON zon.ID_Zone = pac.ID_Zone
						 LEFT JOIN Carrier AS car ON car.ID_Carrier = zon.ID_Carrier
						 LEFT JOIN CountryToZone AS ctz ON ctz.ID_Zone = zon.ID_Zone
						 WHERE Weight >= '.$this->orderWeightSum.'
						 AND ctz.ID_Country IN (
							 SELECT co.ID_Country
							 FROM CustomerAddress AS ca
							 LEFT JOIN City AS ci ON ci.ID_City = ca.ID_City
							 LEFT JOIN State AS st ON st.ID_State = ci.ID_State
							 LEFT JOIN Country AS co ON co.ID_Country = st.ID_Country
							 WHERE AddressType = "D"
							 AND ca.ID_Customer = '.$ID_Customer.'
						 )
						 AND ctz.ID_Zone IN (
							 SELECT zon.ID_Zone
							 FROM Zone AS zon
							 LEFT JOIN Carrier AS car ON car.ID_Carrier = zon.ID_Carrier
						 )
						 AND car.Status = "1"
						 AND zon.Status = "1"
						 AND pac.Status = "1"
						 AND cos.Status = "1"
						 GROUP BY PackageName
						 ORDER BY CarrierName, PackageName, Cost ASC';

			$queryFrais = $this->query($sqlFrais);
			$cpt = 0;

			if (mysql_num_rows($queryFrais) > 0) {
				/**
				 * Lignes de frais touvees pour cette commande
				 */
				while ($resFrais = mysql_fetch_array($queryFrais)) {
					$CostOption .= '<option value="'.number_format($resFrais['Cost'], 2, ',', '').'">'.$resFrais['CarrierName'].' :: '.$resFrais['PackageName'].' - '.number_format($resFrais['Cost'], 2, ',', '').' &euro;&nbsp;</option>';
					$cpt++;
				}
			} else {
				/**
				 * Aucunes lignes de frais pour cette commande
				 */
				$CostOption = '<option value="0">Pas de frais d\'envois definis</option>';
				$fraisExpArray = 0;
			}

			$totalTtc = number_format(array_sum($this->orderPriceArray), 2, ',', '');
			$totalBasket = $totalTtc;

			$data = array('TotalTTC'    => $totalTtc,
						  'CostOption'  => $CostOption,
						  'TotalBasket' => $totalBasket);

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode createCustomer
	 *
	 * @desc   Creation d'un client suite a l'enregistrement de celui-ci depuis la page register.php
	 * @param  int $data Donnees retournees par le formulaire sous forme de tableau
	 * @return bool Retourne vrais si aucunes erreurs dans la creation du client
	 * @access public
	 */
	public function createCustomer($data)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		/**
		 * Remise en forme des donnees et preparation du nouveau tableau
		 * et enregistrement des donnees dans la table Customer
		 */
		$dataCu['ID_Gender']     = $data['ID_Gender'];
		$dataCu['FirstName']     = strtoupper($data['FirstName']);
		$dataCu['LastName']      = ucwords($data['LastName']);
		$dataCu['Email']         = strtolower($data['Email']);
		$dataCu['UserName']      = $data['UserName'];
		$dataCu['Password']      = $data['Password'];
		$dataCu['DateLastVisit'] = date('Y-m-d H:i:s');

		$ID_Customer = $this->insert_sql('Customer', $dataCu);

		/**
		 * Preparation du nouveau tableau de donnees et
		 * enregistrement de l'adresse dans la table CustomerAddress
		 */
		$dataAd['ID_Customer'] = $ID_Customer;
		$dataAd['ID_City']     = $data['ID_City'];
		$dataAd['Street']      = $data['Street'];

		$ID_CustomerAddress = $this->insert_sql('CustomerAddress', $dataAd);

		/**
		 * Enregistrement du client pour la boutique
		 */
		$sql = 'INSERT INTO CustomerToShop VALUES ('.$ID_Customer.', '.$_SESSION['IDS'].')';
		$this->query($sql);

		/**
		 * Ajout des donnees dans la table Basket
		 */
		$dataBa['ID_Customer'] = $ID_Customer;
		$ID_Basket = $this->insert_sql('Basket', $dataBa);

		if (($ID_Customer == true) and ($ID_CustomerAddress == true) and ($ID_Basket == true)) {
			$_SESSION['IDC'] = $ID_Customer;
			$_SESSION['IDB'] = $ID_Basket;
			return true;
		} else {
			return false;
		}
	}




	/** ****************************************************************************************************
	 * Methode defineCategoryAttribut
	 *
	 * @desc   Definition des attributs d'une categorie dont l'identifiant est donne en parametre
	 * @param  int $ID_Category Identifiant de la categorie
	 * @access public
	 */
	public function defineCategoryAttribut($ID_Category)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$sql = 'SELECT CategoryName, CategoryName FROM Category WHERE ID_Category = '.$ID_Category.' AND Status = "E"';
		$result = mysql_fetch_array($this->query($sql));
		$this->CategoryName = htmlentities($this->myutf8_decode($result['CategoryName']));
	}




	/** ****************************************************************************************************
	 * Methode defineSubCategoryAttribut
	 *
	 * @desc   Definition des attributs d'une sous-categorie dont l'identifiant est donne en parametre
	 * @param  int $ID_SubCategory identifiant de la sous-categorie
	 * @access public
	 */
	public function defineSubCategoryAttribut($ID_SubCategory)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$sql = 'SELECT SubCategoryName, SubCategoryName FROM SubCategory WHERE ID_SubCategory = '.$ID_SubCategory.' AND Status = "E"';
		$result = mysql_fetch_array($this->query($sql));
		$this->SubCategoryName = htmlentities($this->myutf8_decode($result['SubCategoryName']));
	}




	/** ****************************************************************************************************
	 * Methode defineProductAttribut
	 *
	 * @desc   Definition des attributs d'un produit dont l'identifiant est donne en parametre
	 * @param  int    $ID_Product Identifiant du produit
	 * @return string Retourne le chemin du template selectionne
	 * @access public
	 */
	public function defineProductAttribut($ID_Product)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$sql = 'SELECT cat.ID_Category,
					   cat.CategoryName,
					   scat.ID_SubCategory,
					   scat.SubCategoryName,
					   Reference,
					   ProductName,
					   ProductDescription,
					   ProductStock,
					   pro.NbImage,
					   ManageStock,
					   EmptyStockSale,
					   SalePriceType,
					   CalculPrixTTC(ProductPrice, TaxValue) AS ProductPrice,
					   CalculPrixTTC((ProductPrice - SalePrice), TaxValue) AS ProductPrice_RemisePrixFixe,
					   CalculPrixTTC((ProductPrice - ROUND(((ProductPrice / 100) * SalePrice), 2)), TaxValue) AS ProductPrice_RemisePoucentage
				FROM Product AS pro
				LEFT JOIN Tax AS tax ON pro.ID_Tax = tax.ID_Tax
				LEFT JOIN Category AS cat ON pro.ID_Category = cat.ID_Category
				LEFT JOIN SubCategory AS scat ON pro.ID_SubCategory = scat.ID_SubCategory
				WHERE ID_Product = '.$ID_Product.'
				AND cat.Status = "E"
				AND pro.Status = "E"';
		$result = mysql_fetch_array($this->query($sql));

		if (($result['ManageStock'] == '1') and ($result['EmptyStockSale'] == '0')) {
			/**
			 * Gestion du stock - Pas de vente hors stock
			 */
			$nbLoop = $result['ProductStock'] + 1;
		} elseif (($result['ManageStock'] == '1') and ($result['EmptyStockSale'] == '1')) {
			/**
			 * Gestion du stock - Vente hors stock authorizee
			 */
			$nbLoop = 11;
		} else {
			/**
			 * pas de gestion du stock
			 */
			$nbLoop = 11;
		}

		/**
		 * D?finition du type de remise et calcul de celle-ci
		 */
		switch($result['SalePriceType']) {
		case '0': /* Aucune remise */
			$salePrice = '';

			break;

		case '1': /* Remise en % sur le prix HT */
			$salePrice = number_format($result['ProductPrice_RemisePoucentage'], 2, ',', '');

			break;

		case '2': /* Remise en euros sur le prix HT */
			$salePrice = number_format($result['ProductPrice_RemisePrixFixe'], 2, ',', '');

			break;
		}

		$this->ProductStock       = $this->makeSelectLoop($nbLoop);
		$this->ProductName        = htmlentities($this->myutf8_decode($result['ProductName']));
		$this->ProductDescription = nl2br(htmlentities($this->myutf8_decode($result['ProductDescription'])));
		$this->ProductPrice       = number_format($result['ProductPrice'], 2, ',', ' ');
		$this->ProductRemiseType  = $result['SalePriceType'];
		$this->ProductRemise      = $salePrice;
		$this->NbImage            = $result['NbImage'];
		$this->ProductIdCat       = $result['ID_Category'];
		$this->CategoryName       = htmlentities($this->myutf8_decode($result['CategoryName']));
		$this->ProductIdSubCat    = $result['ID_SubCategory'];
		$this->SubCategoryName    = htmlentities($this->myutf8_decode($result['SubCategoryName']));
	}




	/** ****************************************************************************************************
	 * Methode menuTop
	 *
	 * @desc   Creation de la barre de menu horizontale
	 * @return array Retourne un tableau contenant le lien, le titre du lien et le nom affiche dans l'onglet
	 * @access public
	 */
	public function menuTop()
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		$sql = 'SELECT MenuContact, MenuConditionVente, MenuPaiement, MenuSav, MenuLivraison FROM Shop';
		$query = $this->query($sql);
		$result = mysql_fetch_array($query);

		if ($result['MenuContact'] == 1) {
			$menu[] = array('href' => 'contact.php', 'title' => 'Contact', 'name' => 'Contact');
		}

		if ($result['MenuConditionVente'] == 1) {
			$menu[] = array('href' => 'infos.php?p=c', 'title' => 'Conditions de vente', 'name' => 'Conditions de vente');
		}

		if ($result['MenuPaiement'] == 1) {
			$menu[] = array('href' => 'infos.php?p=p', 'title' => 'Paiement', 'name' => 'Paiement');
		}

		if ($result['MenuSav'] == 1) {
			$menu[] = array('href' => 'infos.php?p=s', 'title' => 'service apr&egrave;s vente', 'name' => 'SAV');
		}

		if ($result['MenuLivraison'] == 1) {
			$menu[] = array('href' => 'infos.php?p=l', 'title' => 'Livraison', 'name' => 'Livraison');
		}

		return $menu;
	}




	/** ****************************************************************************************************
	 * Methode basketState
	 *
	 * @desc   Donne le nombre de produits presents dans le panier
	 * @param  int $ID_Basket Identifiant du panier
	 * @return int Retourne le nombre d'items dans le panier, sinon 0
	 * @access public
	 */
	public function basketState($ID_Basket = 0)
	{
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Nombre de produit dans le panier', 'variable' => array('$ID_Basket' => $ID_Basket)));

		if ($ID_Basket > 0) {
			$sql = 'SELECT COUNT(ID_BasketDetail) AS NbProduct FROM BasketDetail WHERE ID_Basket = '.$ID_Basket;
			$query = $this->query($sql);
			$result = mysql_fetch_array($query);

			if ($result['NbProduct'] > 0) {
				$nb_product = $result['NbProduct'];
			} else {
				$nb_product = 0;
			}
		} else {
			$nb_product = 0;
		}

		return $nb_product;
	}




	/** ****************************************************************************************************
	 * Methode viewPaymentType
	 *
	 * @desc   Retourne les modes de paiements disponibles pour la boutique avec leur codes
	 * @return array
	 * @access public
	 */
	public function viewPaymentType()
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		/**
		 * Selection des modes de paiements
		 */
		$sql = 'SELECT ID_PaymentType, PaymentType, PaymentCode, LineText FROM PaymentType WHERE Status = "1"';
		$query = $this->query($sql);

		while ($result = mysql_fetch_array($query)) {
			$data[] = array('ID_PaymentType' => $result['ID_PaymentType'],
							'PaymentCode'    => $result['PaymentCode'],
							'PaymentType'    => $result['PaymentType'],
                            'LineText'       => $result['LineText']);
		}

		return $data;
	}




	/** ****************************************************************************************************
	 * Methode sendDataContactByMail
	 *
	 * @desc   Methode permettant d'envoyer au proprietaire de la boutique les donnees saisies
	 *         dans le formulaire de contact par le client
	 * @param  array $data Donnees du formulaire de contact
	 * @return bool Retourne vrais en cas de succes et faux en cas d'echec
	 * @access public
	 */
	public function sendDataContactByMail($data)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));

		/**
		 * Recuperation du mail de l'admin de la boutique
		 */
		$sql    = 'SELECT Email FROM ShopAdmin';
		$query  = $this->query($sql);
		$result = mysql_fetch_array($query);

		/**
		 * Envoi des donnees au proprietaire de la boutique
		 */
		$subject = '[BOUTIQUE] - Demande d\'infos / question';
		$body  = 'Bonjour,'."\r\n\r\n";
		$body .= 'Sujet de la demande : '.$data['Sujet']."\r\n";
		$body .= 'Nom du client / demandeur : '.strtoupper($data['Nom'])."\r\n";
		$body .= 'Email : '.strtolower($data['Email'])."\r\n";
        $body .= 'Telephone : '.$data['Telephone']."\r\n";
		$body .= 'Commantaire / Question :'."\r\n\r\n".$this->myutf8_decode($data['Commentaires'])."\r\n";
		$body .= '';

		mail($result['Email'], $subject, $body, 'From: '.$this->mailFrom);

		return true;
	}




	/** ****************************************************************************************************
	 * Methode searchProduct
	 *
	 * @desc   Methode permettant de lancer une recherche dans la table Product
	 * @param  string $text    Donnees pour la recherche
	 * @return array / bool
	 * @access public
	 */
	public function searchProduct($text)
	{
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Recherche de produit', 'variable' => array('$text' => $text)));

		$text = trim($text);

		$sql = 'SELECT ID_Product, p.ID_Category AS ID_Category, ProductName, ProductDescription, NbImage,
                       CalculPrixTTC(ProductPrice, TaxValue) AS ProductPrice
				FROM Product AS p
				LEFT JOIN Category AS c ON p.ID_Category = c.ID_Category
                LEFT JOIN Tax AS t ON p.ID_Tax = t.ID_Tax
				WHERE p.Status = "E"
				AND (
					ProductName LIKE "%'.$text.'%"
					OR ProductDescription LIKE "%'.$text.'%"
					OR ProductName LIKE "%'.$this->remplace_car($text).'%"
					OR ProductDescription LIKE "%'.$this->remplace_car($text).'%"
					OR LOWER(ProductName) LIKE LOWER("%'.$text.'%")
					OR LOWER(ProductDescription) LIKE LOWER("%'.$text.'%")
					OR LOWER(ProductName) LIKE LOWER("%'.$this->remplace_car($text).'%")
					OR LOWER(ProductDescription) LIKE LOWER("%'.$this->remplace_car($text).'%")
				)';

		$query = $this->query($sql);

		if (@mysql_num_rows($query) > 0) {
			while ($result = mysql_fetch_array($query)) {
				/**
				 * Tranconage du nom de l'article si trop long
				 */
				if (strlen($result['ProductName']) > 100) {
					$productName = substr($result['ProductName'], 0, 100).'...';
				} else {
					$productName = $result['ProductName'];
				}

				/**
				 *
				 */
				if (strlen($result['ProductDescription']) > 255) {
					$productDescription = substr($result['ProductDescription'], 0, 255).'...';
				} else {
					$productDescription = $result['ProductDescription'];
				}

				/**
				 * Recuperation de l'image de l'article si existante
				 */
				if ($result['NbImage'] > 0) {
					$id_p       = $result['ID_Product'];
					$im_n       = substr($result['NbImage'], 0, 1);
					$pr_n       = $result['ProductName'];
					$imgName    = $this->printImage('./images/product_big/', $id_p.'_'.$im_n);
					$imgProduct = '<a href="./images/product_big/'.$imgName['name'].'" class="lightwindow page-options" title="'.$result['CategoryName'].'" caption="'.$pr_n.'"><i></i><img src="./images/product_mini/'.$imgName['name'].'" alt="'.$pr_n.'" title="'.$pr_n.'" /></a>';
				} else {
					$imgProduct = '&nbsp;';
				}

				$data[] = array('ID_Product'         => $result['ID_Product'],
								'ID_Category'        => $result['ID_Category'],
								'ProductName'        => $productName,
								'ProductDescription' => $productDescription,
								'ProductLink'        => $this->rewriteUrl('detail_article.php?C='.$result['ID_Category'].'&P='.$result['ID_Product']),
								'ProductImage'       => $imgProduct,
                                'ProductPrice'       => $result['ProductPrice']);
								//'ProductDescription' => wordwrap($productDescription, 120, "<br />\n"),
			}

			return $data;
		} else {
			return false;
		}
	}






}
?>
