<?php
/* **
 * @application PhpMyShopping
 * @part        Admin Boutique (AB)
 * @file        class.customer.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 Customer
 *
 * Gestion des donnees clients : ajout et modification
 */

require_once 'class.lib.php';

class Customer extends Lib
{
	public $nbAddress;




	/** ****************************************************************************************************
	 * Constructeur
	 *
	 * @access public
	 */
	public function __construct()
	{
	}




	/** ****************************************************************************************************
	 * Methode addCustomer
	 *
	 * @desc   Methode d'ajout de client dans la table Customer
	 * @param  array $data     Tableau contenant les donnees client
	 * @return int/string Retourne l'identifiant du client en cas de succes et faux en cas d'echec
	 * @access public
	 */
	public function addCustomer($data)
	{
        $this->log(__FILE__, array('methode' => __METHOD__));
		$data = array_map('trim', $data);

		/** -------------------------------------------------------------------------------------------
		 * Verrification de la non existance du client dans la table Customer
		 */
		$sql = 'SELECT ID_Customer FROM Customer WHERE Email = "'.strtolower($data['Email']).'"';
		$query = $this->query($sql);
		$nb_result = @mysql_num_rows($query);

		if ($nb_result > 0) {
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Adresse mail deja presente dans la table Customer'));
			return 'error';
			exit;
		} else {
			/** -------------------------------------------------------------------------------------------
			 * Remise en forme des donnees pour la table Customer
			 */
			$dataCu['ID_Gender'] = $data['ID_Gender'];
			$dataCu['FirstName'] = strtoupper($data['FirstName']);
			$dataCu['LastName']  = ucwords(strtolower($data['LastName']));
			$dataCu['Password']  = $data['Password'];
			$dataCu['Email']     = strtolower($data['Email']);
			$dataCu['Telephone'] = $data['Telephone'];
			$dataCu['Gsm']       = $data['Gsm'];

			if ((isset($data['Status'])) and ($data['Status'])) {
				$dataCu['Status'] = $data['Status'];
			}

			/**
			 * Insertion des donnees dans la table Customer
			 */
			$ID_Customer = $this->insert_sql('Customer', $dataCu, 'SHA1');
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Creation client', 'variable' => array('$ID_Customer' => $ID_Customer)));

			/** -------------------------------------------------------------------------------------------
			 * Gestion de la nouvelle ville
			 */
			if ($data['NewCityName']) {
				/**
				 * Si $data[NewCityName] contient une valeur on l'insere dans la table City
				 */
				$dataCi['ID_State'] = $data['ID_State'];
				$dataCi['CityName'] = ucwords($data['NewCityName']);
				$dataCi['PostCode'] = $data['PostCode'];

				/**
				 * Insertion des donnees dans la table City
				 */
				$ID_City = $this->insert_sql('City', $dataCi);
				$dataCaB['ID_City'] = $ID_City;
				$dataCaD['ID_City'] = $ID_City;
			} else {
				$dataCaB['ID_City'] = $data['B_ID_City'];
				$dataCaD['ID_City'] = $data['D_ID_City'];
			}

			/** -------------------------------------------------------------------------------------------
			 * Remise en forme des donnees pour la table CustomerAddress
			 */
			$dataCaB['ID_Customer'] = $ID_Customer;
			$dataCaB['ID_Gender']   = $data['B_ID_Gender'];
			$dataCaB['FirstName']   = strtoupper($data['B_FirstName']);
			$dataCaB['LastName']    = ucwords(strtolower($data['B_LastName']));
			$dataCaB['Street']      = $data['B_Street'];
			$dataCaB['AddressType'] = 'B';

			$dataCaD['ID_Customer'] = $ID_Customer;
			$dataCaD['ID_Gender']   = $data['D_ID_Gender'];
			$dataCaD['FirstName']   = strtoupper($data['D_FirstName']);
			$dataCaD['LastName']    = ucwords(strtolower($data['D_LastName']));
			$dataCaD['Street']      = $data['D_Street'];
			$dataCaD['AddressType'] = 'D';

			/**
			 * Insertion des donnees dans la table CustomerAddress
			 */
			$this->insert_sql('CustomerAddress', $dataCaB);
			$this->insert_sql('CustomerAddress', $dataCaD);
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Enregistrement adresses client', 'variable' => array('$ID_Customer' => $ID_Customer)));

			/** -------------------------------------------------------------------------------------------
			 * Envoi du mail de confirmation au client
			 */
			$domain         = $this->getParam('param', 'domain_name');
			$from           = $this->getParam('from', 'mail_0');
			$d['Gender']    = $this->getField('Gender', 'GenderName', 'ID_Gender', $dataCu['ID_Gender']);
			$d['FirstName'] = $dataCu['FirstName'];
			$d['ShopLink']  = 'http://'.$domain;
			$d['Login']     = $dataCu['Email'];
			$d['Password']  = $dataCu['Password'];

			$this->sendEmail(3, $dataCu['Email'], $from, $d);
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Envoi mail d\'infos au client', 'variable' => array('$ID_Customer' => $ID_Customer)));

			if ($ID_Customer != false) {
                /**
                 * Auto-login
                 */
                /*$dataCu['Email'] = strtolower($_POST['Email']);
                $dataCu['Password'] = $_POST['Password'];
                $dataCu['IDC'] = $ID_Customer;
                $dataCu['IDB'] = $data['IDB'];
                $this->verrifIdentCustomer($dataCu);*/
                
				return $ID_Customer;
			} else {
				return 'error';
			}
		}
	}




	/** ****************************************************************************************************
	 * Methode createNewPassword
	 *
	 * @desc   Methode de modification du password d'un client
	 *         1. Verrification de l'existance du mail
	 *         2. Generation et modification du password dans la table Customer
	 *         3. Envoi du mail au client
	 * @param  string $mail
	 * @return bool Retourne vrais en cas de succes et faux en cas d'echec
	 * @access public
	 */
	public function createNewPassword($mail)
	{
		$this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Modif password client', 'variable' => array('$mail' => $mail)));
        /**
		 * Verrification de l'existance du mail dans la table Customer
		 *
		 * Retour possible :/adresse.php
		 *  0 -> Mail non existant
		 *  1 -> Mail existant mais non unique
		 *  2 -> Mail existant et unique
		 */
		$password = $this->password_generator();
		$verrif = $this->SQLquery('CALL CustomerChangePassword("'.$mail.'","'.$password.'")');
		$result = @mysqli_fetch_row($verrif);

		if ($result[0] == 0) {
			/**
			 * Mail inexistant
			 */
			return $result[0]; //false;
			exit;
		} else if ($result[0] == 1) {
			/**
			 * Mail existant mais non unique
			 */
			return $result[0]; //false;
			exit;
		} else {
			/**
			 * Mail existant et unique
			 */
			$subject = 'Modification de votre mot de passe';
			$body  = 'Veuillez trouver ci-dessous votre nouveau mot de passe :'."\r\n\r\n";
			$body .= '---------------------------'."\r\n\r\n";
			$body .= '  Identifiant  : '.$result[1]."\r\n";
			$body .= '  Mot de passe : '.$password."\r\n\r\n";
			$body .= '---------------------------'."\r\n\r\n";
			$body .= '';

			mail($mail, $subject, $body, 'From: '.$this->getParam('mail', 'from'));

			return $result[0]; //true;
		}

		$this->SQLclose();
	}




	/** ****************************************************************************************************
	 * Methode verrifIdentCustomer
	 *
	 * @desc   Verification de l'identification du client
	 * @param  array $data Tableau contenant le mail et le password du client
	 * @return bool
	 * @access public
	 */
	public function verrifIdentCustomer($data)
	{
        $v = array('$data[\'IDC\']' => $data['IDC'], '$data[\'IDB\']' => $data['IDB'], '$data[\'Email\']' => $data['Email'], '$data[\'Password\']' => $data['Password']);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Identification client', 'variable' => $v));

		if ($data['IDC']) {
			$IDC = $data['IDC'];
		} else {
			$IDC = 0;
		}

		if ($data['IDB']) {
			$IDB = $data['IDB'];
		} else {
			$IDB = 0;
		}

        $v = array('$IDC' => $IDC, '$IDB' => $IDB);
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'CALL CustomerVerrifIdent()', 'variable' => $v));
		$verrif = $this->SQLquery('CALL CustomerVerrifIdent("'.$data['Email'].'","'.$data['Password'].'","'.$IDC.'","'.$IDB.'")');
		$result = mysqli_fetch_row($verrif);

		if ($result[0] == 0) {
			/**
			 * Client inconnu ou incorrectement identifie
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Client inconnu ou incorrectement identifie'));

			return false;
			exit;
		} else {
			/**
			 * Client correctement identifie
			 * Suppression du client temporaire de la table Customer
			 */
            $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Client correctement identifie'));
			$this->delete_tuple('Customer', 'ID_Customer', $IDC, 'Email', 'logintemp');

			return $result[0];
		}
	}




	/** ****************************************************************************************************
	 * Methode viewCustomerAddress
	 *
	 * @desc   Affichage des infos concernant la ou les adresses du client
	 * @param  int $ID_Customer Identifiant du client
	 * @return string
	 * @access public
	 */
	public function viewCustomerAddress($ID_Customer)
	{
        $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Recuperation adresse client', 'variable' => array('$ID_Customer' => $ID_Customer)));

		$sqlAddress = 'SELECT ID_CustomerAddress, ca.FirstName AS CA_FirstName, ca.LastName AS CA_LastName, Street, AddressType,
							  ca.ID_Gender AS CA_ID_Gender, GenderName,
							  ca.ID_City AS CA_ID_City,
							  st.ID_State,
							  co.ID_Country,
							  cu.ID_Gender AS CU_ID_Gender, cu.Email, Telephone, Gsm, cu.FirstName AS CU_FirstName, cu.LastName AS CU_LastName
					   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
					   LEFT JOIN Gender AS ge ON ge.ID_Gender = ca.ID_Gender
					   LEFT JOIN Customer AS cu ON cu.ID_Customer = ca.ID_Customer
					   WHERE ca.ID_Customer = '.$ID_Customer;

		$queryAddress = $this->query($sqlAddress);
		$this->nbAddress = mysql_num_rows($queryAddress);

		while ($result = mysql_fetch_array($queryAddress)) {
			switch($result['AddressType']) {
			case 'B':
				/**
				 * Adresse de facturation
				 */
				$CustomerAddress['B'] = $result;
                $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Adresse type B'));
				break;

			case 'D':
				/**
				 * Adresse de livraison
				 */
				$CustomerAddress['D'] = $result;
                $this->log(__FILE__, array('methode' => __METHOD__, 'message' => 'Adresse type D'));
				break;
			}
		}

		return $CustomerAddress;
	}




	/** ****************************************************************************************************
	 * Methode pour la partie administration des clients de la boutique
	 **************************************************************************************************** */




	/** ****************************************************************************************************
	 * Methode customerList
	 *
	 * @desc   Affichage des infos client
	 * @return string
	 * @access public
	 */
	public function customerList()
	{
		$list = '
		<div class="heading">Liste des clients</div>
		<div id="list">
		<table class="list">
		  <tr>
			<th width="*%" align="left">Nom - pr&eacute;nom</th>
			<th width="*%" align="left">Email</th>
			<th width="*%" align="left">T&eacute;l&eacute;phone</th>
			<th width="*%" align="left">Portable</th>
			<th width="*%" align="center">Compte</th>
			<th width="1%">&nbsp;</th>
		  </tr>';

		/**
		 * Recuperation des donnees pour la creation de la liste
		 */
		$sql = 'SELECT cu.ID_Customer, GenderName, FirstName, LastName, Email, Status, Telephone, Gsm
				FROM Customer AS cu
				LEFT JOIN Gender AS ge ON ge.ID_Gender = cu.ID_Gender
				WHERE Email != "logintemp"
				ORDER BY FirstName, LastName ASC';

		$query = $this->query($sql);
		while ($result = mysql_fetch_array($query)) {
			if ($result['Status'] == 'A') {
				$status = '<b class="blue">Activ&eacute;</b>';
			} else {
				$status = '<b class="green">Non activ&eacute;</b>';
			}

			// <td class="center" width="1%"><a href="?C1=CL&C2=CL&C3=edit&ID_Customer='.$result['ID_Customer'].'"><img src="./images/update.png" alt="Modifier" title="Modifier" /></a></td>
			$list .= '
			<tr class="row2" onmouseover="this.className=\'highlight\'" onmouseout="this.className=\'row2\'">
			  <td align="left" nowrap="nowrap">'.$result['GenderName'].$result['FirstName'].' '.$result['LastName'].'</td>
			  <td align="left" nowrap="nowrap">&nbsp;'.$result['Email'].'&nbsp;</td>
			  <td align="left" nowrap="nowrap">&nbsp;'.$result['Telephone'].'&nbsp;</td>
			  <td align="left" nowrap="nowrap">&nbsp;'.$result['Gsm'].'&nbsp;</td>
			  <td align="center" nowrap="nowrap">'.$status.'</td>
			  <td class="center" width="1%"><a href="?C1=CL&C2=CL&C3=delete_confirm&ID_Customer='.$result['ID_Customer'].'"><img src="./images/delete.png" alt="Effacer" title="Effacer" /></a></td>
			</tr>';
		}

		$list .= '
		</table>
		</div>';

		return $list;
	}




	/** ****************************************************************************************************
	 * Methode customerDelete
	 *
	 * @desc   Suppresion d'un client
	 * @param  int $ID_Customer Identifiant du client
	 * @return bool
	 * @access public
	 */
	public function customerDelete($ID_Customer)
	{
		/**
		 * Suppression du client
		 */
		$sqlOrders = 'DELETE FROM Customer WHERE ID_Customer = '.$ID_Customer;

		if (!$this->query($sqlOrders)) {
			return false;
		}

		return true;
	}








}
