<?php

class exportcustomers extends Module
{
		private $_postErrors = array();
		
	public $fieldnames=array(
		1=>'id_customer',
        2=>'id_shop_group',
        3=>'id_shop',
        4=>'id_gender',
		5=>'id_default_group',
        6=>'id_risk',
        7=>'company',
        8=>'siret',
        9=>'ape',
      	10=>'default_group_name',
		11=>'all_groups_id',
		12=>'all_groups_name',
		13=>'firstname',
		14=>'lastname',
		15=>'email',
		16=>'passwd',
		17=>'last_passwd_gen',
		18=>'birthday',
		19=>'newsletter',
		20=>'ip_registration_newsletter',
		21=>'newsletter_date_add',
		22=>'optin',
        23=>'website',
        24=>'outstanding_allow_amount',
        25=>'show_public_prices',
        26=>'max_payment_days',
        27=>'secure_key',
		28=>'note',
		29=>'active',
		30=>'is_guest',
		31=>'deleted',
		32=>'date_add',
		33=>'date_upd',
		34=>'id_addresses',
		35=>'addresses_all',
		);

	function __construct()
	{
		global $cookie;
		$this->_cookie = $cookie;
		$this->name = 'exportcustomers';
		$this->tab = 'export';
		$this->version = '1.1'; // compatible PS 1.5
       	$this->module_key= 'cee2cd4eea2b45476c466aecd6c7ed54';
	
		/* The parent construct is required for translations */
		parent::__construct();
		
		$this->page = basename(__FILE__, '.php');
		$this->displayName = $this->l('Customers Export');
		$this->description = $this->l('Export your Customers in CSV file.');
		
		$this->_directory = dirname(__FILE__).'/';
		$this->_filename = $this->_directory.strtolower(Language::getIsoById($this->_cookie->id_lang)).'customers.csv';
		$this->_filename_http = 'http://'.$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/exportcustomers/".strtolower(Language::getIsoById($this->_cookie->id_lang)).'products.csv';
	
		
	}

	function install()
	{
		if (!parent::install())
			return false;
			return true;
	}
	
	  function uninstall()
    {
        if (!parent::uninstall())	
		return false;
			return true;		
    }
	
		private function _postValidation()
	{
		@unlink($this->_filename);
		$fp = fopen($this->_filename, 'wb');
		fclose($fp);
		if (!file_exists($this->_filename))
		{
		$this->_html .='<div class="warning confirm">
  				<img src="../img/admin/warning.gif" alt="" title="" />
  				'.$this->l('Cannot write').' '.realpath($this->_filename).'
  			</div>';
		}
	}
	
	private function _addToFeed($str)
	{
		if(file_exists($this->_filename))
		{
			$fp = fopen($this->_filename, 'ab');
			fwrite($fp, $str, strlen($str));
			fclose($fp);
		}
	}
	


	function getContent()
	{
	
		set_time_limit(0);
		$id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
	
			if (!empty($_POST))
			{
			    if(isset($_POST['id_lang']))
					$id_lang=$_POST['id_lang'];
					$this->_filename = $this->_directory.strtolower(Language::getIsoById($id_lang)).'customers.csv';
					$this->_filename_http = 'http://'.$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/exportcustomers/".strtolower(Language::getIsoById($id_lang)).'customers.csv';
							
				$this->_postValidation();
			}
				$this->_html = '<h2>'.$this->displayName.'</h2>';

			if (isset($_POST['submitFields']))
			{
		
				if(!empty($_POST['whatfields']))
				{
					$fields=array();
					foreach($_POST['whatfields'] AS $fieldno)
					{
						$fields[]=$this->fieldnames[$fieldno];
					}
					
										
					if(!empty($_POST['groupBox']))
					{
					
						$groups=$_POST['groupBox'];
						$groupsString=implode(",", $groups);
					
				    $sql='SELECT * FROM '._DB_PREFIX_.'customer c
							LEFT JOIN '._DB_PREFIX_.'customer_group cg ON(cg.id_customer=c.id_customer)
							LEFT JOIN '._DB_PREFIX_.'group_lang gl ON (gl.id_group=cg.id_group AND gl.id_lang="'.$id_lang.'")
							WHERE cg.id_group IN ('.$groupsString.')
							GROUP BY c.id_customer';
					}
					else
					{
						$sql='SELECT * FROM '._DB_PREFIX_.'customer c
							LEFT JOIN '._DB_PREFIX_.'customer_group cg ON(cg.id_customer=c.id_customer)
							LEFT JOIN '._DB_PREFIX_.'group_lang gl ON (gl.id_group=cg.id_group AND gl.id_lang="'.$id_lang.'")
							GROUP BY c.id_customer';
					
					}					
							
							$customers=Db::getInstance()->executeS($sql);
		
						
					if(in_array("id_customer",$fields)) $this->_addToFeed('id_customer;');
                   	if(in_array("id_shop_group",$fields)) $this->_addToFeed('id_shop_group;');
                   	if(in_array("id_shop",$fields)) $this->_addToFeed('id_shop;');
             		if(in_array("id_gender",$fields)) $this->_addToFeed('id_gender;');
					if(in_array("id_default_group",$fields))	$this->_addToFeed('id_default_group;');
					if(in_array("default_group_name",$fields))	$this->_addToFeed('default_group_name;');
					if(in_array("all_groups_id",$fields))	$this->_addToFeed('all_groups_id;');
					if(in_array("all_groups_name",$fields))	$this->_addToFeed('all_groups_name;');
                  	if(in_array("id_risk",$fields))	$this->_addToFeed('id_risk;');
               		if(in_array("company",$fields))	$this->_addToFeed('company;');
                    if(in_array("siret",$fields))	$this->_addToFeed('siret;');
               		if(in_array("ape",$fields))	$this->_addToFeed('ape;');
               		if(in_array("firstname",$fields)) $this->_addToFeed('firstname;');
					if(in_array("lastname",$fields))	$this->_addToFeed('lastname;');
					if(in_array("email",$fields))	$this->_addToFeed('email;');
					if(in_array("passwd",$fields))	 $this->_addToFeed('passwd;');
					if(in_array("last_passwd_gen",$fields)) $this->_addToFeed('last_passwd_gen;');
					if(in_array("birthday",$fields)) $this->_addToFeed('birthday;');
					if(in_array("newsletter",$fields)) $this->_addToFeed('newsletter;');
					if(in_array("ip_registration_newsletter",$fields)) $this->_addToFeed('ip_registration_newsletter;');
					if(in_array("newsletter_date_add",$fields))	$this->_addToFeed('newsletter_date_add;');
					if(in_array("optin",$fields))	$this->_addToFeed('optin;');
                   	if(in_array("website",$fields))	$this->_addToFeed('website;');
               		if(in_array("outstanding_allow_amount",$fields))	$this->_addToFeed('outstanding_allow_amount;');
               		if(in_array("show_public_prices",$fields))	$this->_addToFeed('show_public_prices;');
               		if(in_array("max_payment_days",$fields))	$this->_addToFeed('max_payment_days;');
          			if(in_array("secure_key",$fields))	$this->_addToFeed('secure_key;');
					if(in_array("note",$fields))	$this->_addToFeed('note;');
					if(in_array("active",$fields)) $this->_addToFeed('active;');
					if(in_array("is_guest",$fields)) $this->_addToFeed('is_guest;');
					if(in_array("deleted",$fields)) $this->_addToFeed('deleted;');
					if(in_array("date_add",$fields)) $this->_addToFeed('date_add;');
					if(in_array("date_upd",$fields)) $this->_addToFeed('date_upd;');
					if(in_array("id_addresses",$fields)) $this->_addToFeed('id_addresses;');
					if(in_array("addresses_all",$fields)) $this->_addToFeed('addresses_all;');
					$this->_addToFeed("\n");
					
					foreach ($customers as $customer)
					{
							$sqlGroups='SELECT cg.id_group, gl.name FROM '._DB_PREFIX_.'customer_group cg
									LEFT JOIN '._DB_PREFIX_.'group_lang gl ON (gl.id_group=cg.id_group AND gl.id_lang="'.$id_lang.'")
									WHERE cg.id_customer="'.$customer['id_customer'].'"';
						
					  	$arrayGroups=Db::getInstance()->executeS($sqlGroups);
		
						$groups_id="";
						$groups_name="";
						foreach($arrayGroups as $group)
						{
							$groups_id=$groups_id.$group['id_group']."|";
							$groups_name=$groups_name.$group['name']."|";
						} 
		
						$groups_id=substr($groups_id,0,strlen($groups_id)-1);
						$groups_name=substr($groups_name,0,strlen($groups_name)-1);
						////////////
						$sqlAddresses='SELECT *, cl.name as country, s.name as state FROM '._DB_PREFIX_.'address a
										LEFT JOIN '._DB_PREFIX_.'country_lang cl ON (cl.id_country=a.id_country AND cl.id_lang="'.$id_lang.'")
										LEFT JOIN '._DB_PREFIX_.'state s ON (s.id_state=a.id_state)
										WHERE a.id_customer="'.$customer['id_customer'].'"';
										
			   	     	$arrayAddresses=Db::getInstance()->executeS($sqlAddresses);
		
						$addresses_id="";
						$addresses_all="";
						foreach($arrayAddresses as $address)
						{
							$addresses_id=$addresses_id.$address['id_address']."|";
							$addresses_all=$addresses_all.$address['firstname']." ".$address['lastname']." ".$address['address1']." ".$address['address2']." ".$address['postcode']." ".$address['city']." ".$address['country']." ".$address['state']." ".$address['phone']." ".$address['phone_mobile']."|";
						} 
		
						$addresses_id=substr($addresses_id,0,strlen($addresses_id)-1);
						$addresses_all=substr($addresses_all,0,strlen($addresses_all)-1);
                   		
							if(in_array("id_customer",$fields)) $this->_addToFeed('"'.$customer['id_customer'].'";');
                           	if(in_array("id_shop_group",$fields)) $this->_addToFeed('"'.$customer['id_shop_group'].'";');
                   	        if(in_array("id_shop",$fields)) $this->_addToFeed('"'.$customer['id_shop'].'";');
             	
							if(in_array("id_gender",$fields)) $this->_addToFeed('"'.$customer['id_gender'].'";');
							if(in_array("id_default_group",$fields))	$this->_addToFeed('"'.$customer['id_default_group'].'";');
							if(in_array("default_group_name",$fields))	$this->_addToFeed('"'.$customer['name'].'";');
							if(in_array("all_groups_id",$fields))	$this->_addToFeed('"'.$groups_id.'";');
							if(in_array("all_groups_name",$fields))	$this->_addToFeed('"'.$groups_name.'";');
                            if(in_array("id_risk",$fields))	$this->_addToFeed('"'.$customer['id_risk'].'";');
                       		if(in_array("company",$fields))	$this->_addToFeed('"'.$customer['company'].'";');
                            if(in_array("siret",$fields))	$this->_addToFeed('"'.$customer['siret'].'";');
                       		if(in_array("ape",$fields))	$this->_addToFeed('"'.$customer['ape'].'";');
                      		if(in_array("firstname",$fields)) $this->_addToFeed('"'.$customer['firstname'].'";');
							if(in_array("lastname",$fields))	$this->_addToFeed('"'.$customer['lastname'].'";');
							if(in_array("email",$fields))	$this->_addToFeed('"'.$customer['email'].'";');
							if(in_array("passwd",$fields))	 $this->_addToFeed('"'.$customer['passwd'].'";');
							if(in_array("last_passwd_gen",$fields)) $this->_addToFeed('"'.$customer['last_passwd_gen'].'";');
							if(in_array("birthday",$fields)) $this->_addToFeed('"'.$customer['birthday'].'";');
							if(in_array("newsletter",$fields)) $this->_addToFeed('"'.$customer['newsletter'].'";');
							if(in_array("ip_registration_newsletter",$fields)) $this->_addToFeed('"'.$customer['ip_registration_newsletter'].'";');
							if(in_array("newsletter_date_add",$fields))	$this->_addToFeed('"'.$customer['newsletter_date_add'].'";');
							if(in_array("optin",$fields))	$this->_addToFeed('"'.$customer['optin'].'";');
                           	if(in_array("website",$fields))	$this->_addToFeed('"'.$customer['website'].'";');
                       		if(in_array("outstanding_allow_amount",$fields))	$this->_addToFeed('"'.$customer['outstanding_allow_amount'].'";');
                       		if(in_array("show_public_prices",$fields))	$this->_addToFeed('"'.$customer['show_public_prices'].'";');
                       		if(in_array("max_payment_days",$fields))	$this->_addToFeed('"'.$customer['max_payment_days'].'";');
                 			if(in_array("secure_key",$fields))	$this->_addToFeed('"'.$customer['secure_key'].'";');
							if(in_array("note",$fields))	$this->_addToFeed('"'.$customer['note'].'";');
							if(in_array("active",$fields)) $this->_addToFeed('"'.$customer['active'].'";');
							if(in_array("is_guest",$fields)) $this->_addToFeed('"'.$customer['is_guest'].'";');
							if(in_array("deleted",$fields)) $this->_addToFeed('"'.$customer['deleted'].'";');
							if(in_array("date_add",$fields)) $this->_addToFeed('"'.$customer['date_add'].'";');
							if(in_array("date_upd",$fields)) $this->_addToFeed('"'.$customer['date_upd'].'";');
							if(in_array("id_addresses",$fields)) $this->_addToFeed('"'.$addresses_id.'";');
							if(in_array("addresses_all",$fields)) $this->_addToFeed('"'.$addresses_all.'";');
							$this->_addToFeed("\n");
			
			
					}
				
						
			
						if(file_exists($this->_filename))
						{
							$fp = fopen($this->_filename, 'rb');
							$fstat = fstat($fp);
							fclose($fp);
							
							$this->_html .= '<div class="conf confirm">
								<img src="../img/admin/ok.gif" alt="" title="" />
						  <p>'.$this->l('Your Customers file is online at the following address:').'<br /><a href="'.$this->_filename_http.'" target="_blanck"><b>'.$this->_filename_http.'</b></a></p><br />';
							$this->_html .= $this->l('Update:').' <b>'.date('m.d.y G:i:s', $fstat['mtime']).'</b><br /></div>';
						}
				}
				else 
				{
					$this->_html .='<div class="warning confirm">
					<img src="../img/admin/warning.gif" alt="" title="" />
					'.$this->l('Error : You have nothing selected').'
					</div>';
				}
		
			}
			$this->_html.='
			<fieldset class="width3" style="width:900px;">
				<legend><img src="../img/admin/asterisk.gif" />'.$this->l('Infos on the exported fields').'</legend>
					<br>'.$this->l('To open CSV : Choose UTF8 encodage').'<br>
					<br>'.$this->l('The fields are separated by semicolon (;)').'
					<br>'.$this->l('Fields with multiple fields are separated by comma (,)').'
					<br>'.$this->l('The text separator is double quotes (")').'
					<br>'.$this->l('The Groups are represented like that "x|y|z..."').'
					<br>'.$this->l('If a customers has got several addresses they will be represented like that "address1|address2..."').'</br>
					<br>'.$this->l('The address format is : firstname lastname address1 address2 zipcode city country state phone mobile phone').'
									
				
					
			</fieldset><br><br>';
			
				$this->_html.=$this->_displayForm();
	
			
			return $this->_html;
		
	
	}

	private function _displayForm()
	{
		$id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
	
		$form='
		<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Settings').'</legend>
	  <form method="post">
	  
	  ';
				$groups=Group::getGroups($id_lang);
					if (sizeof($groups))
					{
						
					$form.='<center><label>'.$this->l('Groups:').' </label></center>
					<table cellspacing="0" cellpadding="0" class="table" style="width: 29.5em;">
						<tr>
							<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'groupBox[]\', this.checked)" /></th>
							<th>'.$this->l('ID').'</th>
							<th>'.$this->l('Group name').'</th>
						</tr>';
						$irow = 0;
						foreach ($groups as $group)
						{
							
							$form.='<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
								<td>'.'<input type="checkbox" name="groupBox[]" class="groupBox" id="groupBox_'.$group['id_group'].'" value="'.$group['id_group'].'"/></td>
								<td>'.$group['id_group'].'</td>
								<td><label for="groupBox_'.$group['id_group'].'" class="t">'.$group['name'].'</label></td>
							</tr>';
						}
						
					$form.='</table><div class="margin-form" style="margin-top:10px">
					<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Check all customers groups you want to export (by default all groups)').'</p>
					</div>';
					} else
						$form.='<p>'.$this->l('No group created').'</p>';
			  
		         $form.=' <center><input type="submit" name="submitFields" value="'.$this->l('Submit').'" /><br><br>
		      <input type="button" onClick="checkDelBoxes(this.form,\'whatfields[]\',true)" value="'.$this->l('Select All').'" />
					<input type="button" onClick="checkDelBoxes(this.form,\'whatfields[]\', false)" value="'.$this->l('Unselect All').'" /><br><br></center>
				';
				
			  
			  
					
					
         $form.=' <center><table style="text-align: left; width: 900px;"><tr><td><br><span style="font-weight: bold; color: rgb(153, 0, 0);">'.$this->l('Choose the fields you want to export :').'<br><br></span></td><tr><td>';
     
    $compte=0;      		
		foreach($this->fieldnames as $key=>$name)
    {
			$selected='';
			if(isset($_POST['whatfields'])){
				if(in_array($key, $_POST['whatfields'])){
					$selected=' checked';
				}
			}
	
			if($compte<12)
			{
      $form.='	
			<label>'.$this->l($name).'</label>&nbsp<input type="checkbox" name="whatfields[]" id="field'.$key.'" value="'.$key.'"'.$selected.' />
			<br><br>	';
			$compte++;
			}
			else
			{
      $form.='</td><td>	<label>'.$this->l($name).'</label>&nbsp<input type="checkbox" name="whatfields[]" id="field'.$key.'" value="'.$key.'"'.$selected.' />
			<br><br>';
			$compte=1;
      }
		}
		
		$form.='</td></tr></table><br><br><center>
		 <input type="button" onClick="checkDelBoxes(this.form,\'whatfields[]\',true)" value="'.$this->l('Select All').'" />
					<input type="button" onClick="checkDelBoxes(this.form,\'whatfields[]\', false)" value="'.$this->l('Unselect All').'" /><br>
	  			<br><input type="submit" name="submitFields" value="'.$this->l('Submit').'" /></center>';
	
		$form.='</form></fieldset>';
		
		return $form;
	
	}

}