<?php

/*
 Building : Add the HEADER 
 
 Methodes :
 1 - We will get the stats from prestashop (prestashop user) to bill the client. Here, Zugara is using a license, ex . $99 for 150user
 2 - We need to redirect the client to Zugara website. IF the client don't have an account, he'll need to create one, ELSE, he will use his login and password.<br />
	Then, we will use SOAP to get the data from Zugara server and the Wss Module
 3 - We will need to hook at the product page
*/

require_once(dirname(__FILE__)."/classes/NtTable.php");
require_once(dirname(__FILE__)."/classes/WssSc.php");

// NT UPDATES DEFINES
if (!defined('UPDATE_URL'))
	define('UPDATE_URL', 'http://updates.nemesis-tech.com');
if (!defined('OS'))
	define('OS', 'prestashop');
	
// ZUGARA DEFINES
	//ADMIN PAGE URL
if (!defined('_ZUGARA_CREATE_ACCOUNT_URL_'))
	define('_ZUGARA_CREATE_ACCOUNT_URL_', 'http://prestashop.webcamsocialshopper.com/site/registration');	
if (!defined('_ZUGARA_ADMIN_PAGE_'))
	define('_ZUGARA_ADMIN_PAGE_', 'http://prestashop.webcamsocialshopper.com/index.php');
if (!defined('_ZUGARA_PASS_FORGOTTEN_'))
	define('_ZUGARA_PASS_FORGOTTEN_', 'http://prestashop.webcamsocialshopper.com/index.php/site/forgot');	
if (!defined('_ZUGARA_SUPPORT_PAGE_'))
	define('_ZUGARA_SUPPORT_PAGE_', 'http://prestashop.webcamsocialshopper.com/index.php/support');
if(!defined('_ZUGARA_HELP_LINK_'))
	define('_ZUGARA_HELP_LINK_', 'http://prestashop.webcamsocialshopper.com/support');
	// IMG FOLDER
if(!defined('_ZUGARA_IMG_DIR_'))
	define('_ZUGARA_IMG_DIR_', 'wss');
if (!defined('_CAN_LOAD_FILES_'))
	exit;

class WebcamSocialShopper 	extends Module
{

	public		function __construct()
	{
		$this->name = 'webcamsocialshopper';
		$this->tab 	= 'front_office_features';
		$this->version = '1.0';
		$this->author = 'Zugara & Nemesis tech';
		$this->module_key = '229584fda68ba92405aa7c649de703a2';
		$this->status = WssSc::getAccountStatus();
		$this->lang = $this->getIsoLang();
		
		parent::__construct();

		$this->displayName = $this->l('Webcam Social Shopper');
		$this->description = $this->l('WSS allows your shoppers to \"hold\" clothing up in front of themselves so they can.');
		$this->_html = '';
		if (!Module::isInstalled('ganalytics'))
		{
      		$this->warning = '<img src="'._PS_ADMIN_IMG_.'warn2.png"/><span id="labelSeeMoreWSS" style="margin-left:20px;">'.$this->l('Google Analytics not configured').'</span>';
    	}
	}

	public		function install()
	{
		if(!parent::install()
		 OR !$this->registerHook('extraLeft')
		 OR !$this->registerHook('header')) 
			return false;
		if (!$this->setWsdl())
			return false;
		if (!Db::getInstance()->Execute("CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."product_image` (
			  `id_product` int(11) DEFAULT NULL,
				`image_name` text,
				`name_product` text,
				`display` int
			  ) ENGINE=MyISAM DEFAULT CHARSET=utf8;"))
        return (false);
    Configuration::updateValue('WSS_IMG_NUMBER', 0);
		return true;
	}
	
	
	public 		function uninstall()
	{
		if (!parent::uninstall())
			return false;
		if (!Db::getInstance()->Execute("DROP TABLE "._DB_PREFIX_."product_image"))
     		return false;
		return true;
	}
	
	public 		function setWsdl()
	{
		$xml = '<?xml version="1.0"?>
				<definitions name="WssDefinition" 
				 targetNamespace="urn:WssTargetNamespace"
				 xmlns:tns="urn:WssTns"   
				 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
				 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
				 xmlns="http://schemas.xmlsoap.org/wsdl/">
				 <message name="WssRequest">
				  <part name="reqParam" type="xsd:string"/>
				 </message>
				 <message name="WssResponse">
				  <part name="resParam" type="xsd:integer"/>
				 </message>
				 <portType name="WssPortType">
				  <operation name="deactivateWSSAccount">
				   <input message="tns:WssRequest"/>
				   <output message="tns:WssResponse"/>
				  </operation>
				 </portType>
				 <binding name="WssBinding" type="tns:WssPortType">
				  <soap:binding style="rpc"
				   transport="http://schemas.xmlsoap.org/soap/http"/>
				  <operation name="deactivateWSSAccount">
				   <soap:operation soapAction=""/>
				   <input>
					<soap:body use="encoded"
					 namespace="urn:WssInputNamespace"
					 encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
				   </input>
				   <output>
					<soap:body use="encoded"
					 namespace="urn:WssOutputNamespace"
					 encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
				   </output>
				  </operation>
				 </binding>
				 <service name="WssService">
				  <documentation>Deactivate WSS Module from PrestaShop Back Office.
				  </documentation>
				  <port name="WssPort" binding="tns:WssBinding">
				   <soap:address
				  location="';
  
				  $newXml .= $xml.'http://'.$_SERVER['HTTP_HOST']._MODULE_DIR_.'webcamsocialshopper/server.php?wsdl"/>
					</port>
				   </service>
				  </definitions>';
				  
		if ($fd = @fopen(dirname(__FILE__).'/wss.wsdl', 'w'))
			{
				if (!@fwrite($fd, $newXml))
				 return false;
				if (!@fclose($fd))
					return false;//$this->_html .= $this->displayError($this->l('Can\'t close the editor file.'));
			}
		else
		 $this->_html .= "XML ERror";
		return true;
	}
	
	public		function getContent()
	{	
	$this->_html .= '<h2>'.$this->displayName.'</h2>';
	$this->_html .= '<style>
			.ca_button_left
			{
			 height:22px;
			 width:32px;
			 background: url('.$this->_path.'img/bg_button_left_ca.png) no-repeat;
			 float:left;
			}
			
			.sp_button_left
			{
			 height:22px;
			 width:32px;
			 background: url('.$this->_path.'img/bg_button_left_sp.png) no-repeat;
			 float:left;
			}
			
			.ap_button_left
			{
			 height:22px;
			 width:32px;
			 background: url('.$this->_path.'img/bg_button_left_ap.png) no-repeat;
			 float:left;
			}
			
			.pl_button_left
			{
			 height:22px;
			 width:32px;
			 background: url('.$this->_path.'img/bg_button_left_pl.png) no-repeat;
			 float:left;
			}
			
			
			.button_center
			{
				height:22px;
				background:url('.$this->_path.'img/bg_button.png) repeat-x;
				width:auto;
				float:left;
				color:#1C78AD;
				font-family:Arial, Helvetica, sans-serif;
				font-size:14px;
				padding-top:3px;
				padding-right:12px;
			}
			.button_right
			{
			 height:22px;
			 width:4px;
			 margin-right:5px;
			 background: url('.$this->_path.'img/bg_button_right.png) no-repeat;
			 float:left;
			}
			
			</style>';
	switch ($this->status['0']['status'])
		{
			//0 - Success (Account exist from Zugara DB)
			case 0:
				//Account configuration
				$this->setAccount();
						
				//Images configuration
				$this->setImg();
		
				//Asset configuration (Background and Watermark)
				$this->setAssets();	
        	break;
			//100 - Account doesnt exist
   			case 100:
				//Display the account status and the link to create the account. 
				$this->createAccount();
        	break;
			//101 - Unknow error
    		case 101:
        		echo $this->l('Un unknow error occured. Please contact our support');
        	break;
		}
		
		// NT Updates
		$this->setNTUpdates();	
		return $this->_html;
	}
		
	public 		function 	createAccount()
	{
		$this->_html .= '<fieldset><legend><img src="'.$this->_path.'img/cfg-account.gif" alt="Webcam Social Shopper" title="wss" /> '.$this->l('WSS Create Account').'</legend>
		<form name="wssCaform" method="POST" action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'">
		<div class="conf">
			<img alt="" src="'._PS_ADMIN_IMG_.'ok2.png'.'">'.$this->l('Thank you for having downloading Webcam Social Shopper.').'
			</div>
		
		<label for="status">'.$this->l('Status ').':</label>
		<div class="margin-form">	
		'.$this->l(''.$this->status['0']['message']).'
		</div>

		<div class="margin-form">
			<a href="'._ZUGARA_CREATE_ACCOUNT_URL_.'?domain='.$_SERVER['HTTP_HOST'].'&email='.Configuration::get('PS_SHOP_EMAIL').'&lang='.$this->lang.'&business_name='.Configuration::get('PS_SHOP_NAME').'&module='._MODULE_DIR_.'&image_dir='.$this->_path.'img/" title="'.$this->l('Create your Zugara account').'" target="_blank">
			<div class="ca_button_left">
			</div>
			<div class="button_center">'.$this->l('Create your account').'</div>
			<div class="button_right"></div>
			</a>
			
			<a href="'._ZUGARA_HELP_LINK_.'" target="_blank" title="'.$this->l('Help and support').'">
			<div class="sp_button_left">
			</div>
			<div class="button_center">'.$this->l('Support').'</div>
			<div class="button_right"></div>
			</a>
		<p>
		</div>
		';
		$this->_html .= '</form></fieldset><br/>';
		
	}
	
	
	public		function 	getIsoLang()
	{
		global $cookie;

		if (!isset($cookie) OR !is_object($cookie))
			$cookie->id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
		$query = 'SELECT iso_code FROM '._DB_PREFIX_.'lang WHERE id_lang='.$cookie->id_lang.'';
		return (Db::getInstance()->getValue($query));
	}
	
	public		function	setAccount()
	{
		/* ACCOUNT DAYS LEFT */
		if (isset($this->status['0']['Days']))
			$daysleft = ($this->status['0']['Days'] > 1) ? $this->l('days left') : $this->l('day left');
		
		/* ACCOUNT STATUS */
		if (isset($this->status['0']['Days']))
			$status = ($this->status['0']['Days']) ? $this->status['0']['StoreLicenseTypeName'].' - '.$this->l($this->status['0']['Days']).' '.$daysleft
			:	$this->l($this->status['0']['StoreLicenseTypeName']);
		else
			$status = $this->l($this->status['0']['StoreLicenseTypeName']);
		
		/* GOOGLE ANALYTICS NEEDS TO BE INSTALLED AND CONFIGURED TO USE WSS */
		if (Module::isInstalled($this->name))
			$gai = Configuration::get('GANALYTICS_ID');
		else
		 	$this->_html .= '<div class="warn">
      <img src="'._PS_ADMIN_IMG_.'/warn2.png'.'"/><span id="labelSeeMoreWSS" style="margin-left:20px;">'.$this->l('Google analytics not installed. Configure Google Analytics.').'</span>
      </div>';
		if (Tools::getValue('gai'))
		{
			Configuration::updateValue('GANALYTICS_ID', Tools::getValue('gai'));
			$gai = Configuration::get('GANALYTICS_ID');
		}
		$this->_html .= '<fieldset><legend><img src="'.$this->_path.'img/cfg-account.gif" alt="Webcam Social Shopper" title="wss" /> '.$this->l('WSS Account configuration').'</legend>
		<form name="wssIdform" method="POST" action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'">';
                if (!Module::isInstalled('ganalytics')){
                    $this->_html .= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png"/><span id="labelSeeMoreWSS" style="margin-left:20px;">'.$this->l('Google Analytics not configured').'</span></div>';
                }
		$this->_html .= '<label>'.$this->l('Account status').' :</label>
		<div class="margin-form">'.$status.'
		</div>
		<label for="gai">'.$this->l('Google Analytics ID').' :</label>
		<div class="margin-form">		
		<input type="text" name="gai" id="gai" value="'.$gai.'"/>
		<input type="submit" id="wssidform" class="button" name="submitwssId" value="'.$this->l('Save').'"/>
		</div>

		<label>'.$this->l('Usefull links').' :</label>
		<div class="margin-form">		
		<p>
		
		
		<a href="'._ZUGARA_ADMIN_PAGE_.'" title="'.$this->l('Go to Zugara admin page').'" target="_blank">
			<div class="ap_button_left">
			</div>
			<div class="button_center">'.$this->l('Go to Admin page').'</div>
			<div class="button_right"></div>
			</a>
			
			<a href="'._ZUGARA_PASS_FORGOTTEN_.'" title="'.$this->l('Password forgotten').'" target="_blank">
			<div class="pl_button_left">
			</div>
			<div class="button_center">'.$this->l('Password lost?').'</div>
			<div class="button_right"></div>
			</a>
			
			<a href="'._ZUGARA_HELP_LINK_.'" target="_blank" title="'.$this->l('Help and support').'">
			<div class="sp_button_left">
			</div>
			<div class="button_center">'.$this->l('Support').'</div>
			<div class="button_right"></div>
			</a>
		</p>
		</div>
		';
		$this->_html .= '</form></fieldset><br/>';
    
	}
	
	public function setImg()
	{
		if (Tools::isSubmit('display'))
		{
      $dis = Db::getInstance()->getValue('SELECT display FROM '._DB_PREFIX_.'product_image WHERE id_product='.Tools::getValue('display'));
      if ($dis == 0)
        Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> 1),'UPDATE', 'id_product='.Tools::getValue('display').'');
      else
        Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> 0),'UPDATE', 'id_product='.Tools::getValue('display').'');
		}
		if (Tools::isSubmit('submitDel'))
		{
      	$images = Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'product_image WHERE id_product='.Tools::getValue('deleteProduct'));
	 	 //SOAP - DELETE ALL GARMENT : Delete all garments for the product ID.
		$res = array();
		$res = WssSc::deleteGarmentColor(Tools::getValue('deleteProduct'), '');
		if($res['0'] == 0)
		 {
		 $this->_html .= 
			'<div class="conf">
			<img alt="" src="'._PS_ADMIN_IMG_.'ok2.png'.'">'.$this->l('Garments has been deleted with succès.').'
			</div>';
		 }
		else
		$this->_html .= 
		'<div class="warn">
			  <img src="'._PS_ADMIN_IMG_.'/warn2.png'.'"/><span id="deleteonegarmentWSS" style="margin-left:20px;">'.$this->l('Error code: ').'['.$res['0'].'] - '.$this->l('An error occured when deleting image').' '.$this->l('Please contact our Support').'</span>
		</div>';  
		foreach ($images as $image)
			{
			unlink(dirname(__FILE__).'/img/'.$image['image_name'].'.png');
			} 
			Db::getInstance()->delete(_DB_PREFIX_.'product_image', 'id_product='.Tools::getValue('deleteProduct'));
			}
		 
		if (!Tools::getValue('inputProduct'))
		{
			
		$this->_html .= NtTable::includeSortTabLib();
		$this->_html .= '<fieldset><legend><img src="'.$this->_path.'img/cfg-products.gif" alt="Webcam Social Shopper" title="wss" /> '.$this->l('Product configuration').'</legend>
		
						
						<form name="wssform" method="POST" action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'">
						<div style="color:#7F7F7F;font-size:0.85em;">
						<div id="divproducts" style="font-size:1.1em;font-weight:bold;margin-top:4px;"></div>
							<input type="hidden" name="inputProduct" id="inputProduct" value=""/>
							<input type="hidden" name="nameProduct" id="nameProduct" value="" />
							
							<script type="text/javascript">
								var formProduct;
								var products = new Array();
							</script>
							 
							<link rel="stylesheet" type="text/css" href="'.__PS_BASE_URI__.'css/jquery.autocomplete.css" />
							<script type="text/javascript" src="'.__PS_BASE_URI__.'js/jquery/jquery.autocomplete.js"></script>
							
							<div id="ajax_choose_product" style="padding:6px; padding-top:2px; width:600px;">
								<p class="clear">'.$this->l('Begin typing the first letters of the product name, then select the product from the drop-down list:').'</p>
								<label style="color:black;text-align:left;width:auto;font-size:1.1em; margin-right:3px">'.$this->l('Please select a product').' : </label>
								<input type="text" value="" id="product_autocomplete_input" />						
							</div>
							<div class="clear"></div>
							<center><input style="visibility:hidden" id="submitproduct" type="submit" name="submitproduct" value="'.$this->l('Add product tab').'" class="button" /></center>
							<script type="text/javascript">
								urlToCall = null;
								/* function autocomplete */
								$(function() {
									$(\'#product_autocomplete_input\')
										.autocomplete(\'ajax_products_list.php\', {
											minChars: 1,
											autoFill: true,
											max:20,
											matchContains: true,
											mustMatch:true,
											scroll:false,
											cacheLength:0,
											formatItem: function(item) {
												return item[1]+\' - \'+item[0];
											}
										}).result(function(event, data, formatted) {
											if (data == null)
												return false;
											var productId = data[1];
											var productName = data[0];
											
											var $divproducts = $(\'#divproducts\');
											var $inputProduct = $(\'#inputProduct\');
											var $nameProduct = $(\'#nameProduct\');
											$divproducts.html($divproducts.html() + productName + \' <br />\');
											$nameProduct.val($nameProduct.val() + productName );
											$inputProduct.val($inputProduct.val() + productId );
												$(this).parents().find(\'#submitproduct\').trigger(\'click\');;
  });
								});
							</script>
							</form>
				</div>
				';
				$products = Db::getInstance()->ExecuteS('SELECT id_product, name_product, COUNT(image_name) as nbImage, display FROM '._DB_PREFIX_.'product_image GROUP BY id_product');
			if ($products)
			{
      $aArray = new NtTable();
      
      $aData = array();
      $anb_image = array();
      $adisplay = array();
      $anumbertodisplay = array();
      $anotdisplay = array();
      foreach($products as $product)
      {
        $anumberdisplay = Db::getInstance()->getValue('SELECT COUNT(`image_name`) FROM '._DB_PREFIX_.'product_image WHERE display=0 AND id_product='.
          $product['id_product']);
        $anumbernotdisplay = Db::getInstance()->getValue('SELECT COUNT(`image_name`) FROM '._DB_PREFIX_.'product_image WHERE display=1 AND id_product='.
          $product['id_product']);
        $anumbertodisplay[$product['id_product']] = $anumberdisplay;
        $anotdisplay[$product['id_product']] = $anumbernotdisplay;
        $aData[$product['id_product']] = $product['name_product'];
        $anb_image[$product['id_product']] = $product['nbImage'];
        if ($product['display'] == 0)
          $img = _PS_ADMIN_IMG_."enabled.gif";
        else
          $img = _PS_ADMIN_IMG_."disabled.gif";
        $adisplay[$product['id_product']] = '<span style="visibility:hidden">'.$product['display'].'</span><input type=submit name="display" value="'.$product['id_product'].'" 
        style="font-size:0px;width:18px; height:16px;background-color:transparent;background-image: url('.$img.') ;cursor: pointer;border:0;" />';
      }
      $aArray->setField(array($this->l('Product name') => $aData ,$this->l("Number of garments") => $anb_image, $this->l('Enabled') =>$anumbertodisplay ,
        $this->l('Disabled') => $anotdisplay,
      $this->l('Display') => $adisplay));
      $aArray->setEvent(array(_PS_ADMIN_IMG_.'details.gif', 'inputProduct', 17, 18));
      $aArray->setEvent(array(_PS_ADMIN_IMG_.'delete.gif', 'tryDelProduct', 16, 16));
      $aArray->setEventTitle($this->l('Actions'));
      $this->_html .= '<style type="text/css">.NtTable{border-collapse:collapse; border-width:1px; 
 		border-style:solid; 
		border-color:black;} .NtTh, .NtEvent , .NtTd {border-collapse:collapse; border-width:1px;
		border-style:solid; 
 		border-color:#DEDEDE;
 		} .NtTh {background-color:#F4E6C9;cursor:pointer;
 		text-decoration:underline;padding:11px 1px 11px 1px!important;} .NtTable {width:700px}</style>';
 		if (Tools::isSubmit('tryDelProduct'))
		{
		$productToDel = Db::getInstance()->getValue('SELECT name_product FROM '._DB_PREFIX_.'product_image WHERE id_product='.Tools::getValue('tryDelProduct'));
      $this->_html .= '<div class="warn"><h4>'.$this->l('you are deleting:').' '.$productToDel.'?</h4><form method=post action="'.$_SERVER['REQUEST_URI'].'"> <input type="hidden" name="deleteProduct" value='.Tools::getValue('tryDelProduct').' />
      <input class=button type="submit" name="submitDel" value="'.$this->l('Clic to delete').'" /></form></div>';
		}
      $this->_html .= $aArray->getContent();
      }
      else
       $this->_html .= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png">'.$this->l('There is 1 warning').'<span style="margin-left:20px;">'.$this->l('No garment confidured').' 
				'.$this->l('Please search a product in shearch form above.').'</div>';
      $this->_html .= '</fieldset><br/>';
		}
		else if (Tools::getValue('inputProduct'))
			{
        if(!($name = Db::getInstance()->getValue('SELECT name_product FROM '._DB_PREFIX_.'product_image WHERE name_product!="" AND id_product='.Tools::getValue('inputProduct'))))
          $name = Tools::getValue('nameProduct');
		  
		 
		  $this->_html .= "";
				$this->_html .= '<fieldset><legend><img src="'.$this->_path.'img/cfg-products.gif" alt="Webcam Social Shopper" title="wss" /> '.$this->l('Select images').'</legend>
				';
				$this->_html .= '<div><a href="'.$_SERVER['REQUEST_URI'].'" style="text-decoration:underline;color:blue;margin-bottom:10px;" > '.
				$this->l('Back to the product selection').' </a></div><br/>';
				$this->_html .= '<div style="font-size:20px; color: red;padding:3px 3px 3px 3px;">'.$this->l('You are customizing: ').$name.'</div><div style="width:1px;height:10px;"></div>';
				$this->_html .= '<link href="'._MODULE_DIR_.$this->name.'/css/fileuploader.css" rel="stylesheet" type="text/css">
				<div id="file-uploader">		
		<noscript>			
			<p>'.$this->l('Please enable JavaScript to use file uploader.').'</p>
		</noscript>         
	</div>
    
    <script src="'._MODULE_DIR_.$this->name.'/js/fileuploader.js" type="text/javascript"></script>
    <script>        
        function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById(\'file-uploader\'),
                action: \''._MODULE_DIR_.$this->name.'/upload.php\',
                debug: true,
                params: {nameProduct: \''.$_POST['nameProduct'].'\', idProduct: \''.$_POST['inputProduct'].'\' }
            });
           
        }
        window.onload = createUploader;     
    </script>';
    if (Tools::isSubmit("deleteImgWss") && Tools::isSubmit('checkbimg'))
			{
				
        $checkbox = Tools::getValue('checkbimg');
          foreach ($checkbox as $image_name)
          {
			if(!($name = Db::getInstance()->getValue('SELECT name_product FROM '._DB_PREFIX_.'product_image WHERE name_product!="" AND id_product='.Tools::getValue('inputProduct'))))
         	 $name = Tools::getValue('nameProduct');
			// SOAP - DELETE ONE COLOR of GARMENT: delete only one color for the garment (not all of them)
			$res = array();
			$res = WssSc::deleteGarmentColor($_POST['inputProduct'], $image_name.'.png');
			$success = 0;
			if($res['0'] == 0)
             {
			   Db::getInstance()->Execute("DELETE FROM "._DB_PREFIX_."product_image WHERE image_name='".$image_name."'");
			  unlink(dirname(__FILE__).'/img/'.$image_name.'.png');
			  $success  = 1;
			 }
			 else
			  {
				  $this->_html .= '<div class="error">
				  <img src="'._PS_ADMIN_IMG_.'/error.png'.'"/><span id="deleteonegarmentWSS" style="margin-left:20px;">'.$this->l('Error code: ').'['.$res['0'].'] - '.$this->l('Unable to delete image ').$image_name.'.png '.$this->l('Please contact our Support').'</span>
				  </div>';	
			  }
		  }
		  if($success == 1)
			 $this->_html .= 
			'<div class="conf">
			<img alt="" src="'._PS_ADMIN_IMG_.'ok2.png'.'">'.$this->l('Garment has been deleted with succès.').'
			</div>';
      }
     if (Tools::isSubmit('displayalone') && Tools::getValue('displayalone'))
     {
        if (Db::getInstance()->getValue('SELECT display FROM '._DB_PREFIX_.'product_image WHERE image_name="'.Tools::getValue('displayalone').'"') == 0)
          Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> '1'),'UPDATE', 'image_name="'.Tools::getValue('displayalone').'"');
        else
          Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> '0'),'UPDATE', 'image_name="'.Tools::getValue('displayalone').'"');
     }
     if (Tools::isSubmit("displayImgWss") && Tools::isSubmit('checkbimg'))
			{
        $checkbox = Tools::getValue('checkbimg');
        $query = "";
        $count = 0;
        foreach ($checkbox as $image_name)
          $count++;
        $i = 0;
        foreach ($checkbox as $image_name)
          {
            $query .= 'image_name="'.$image_name.'"';
            $i++;
            if ($i < $count)
              $query  .= ' OR ';
          }
        $aimage_products = Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'product_image WHERE '.$query.'');
        $inumberDisplay = Db::getInstance()->getValue('SELECT COUNT(`image_name`) FROM '._DB_PREFIX_.'product_image WHERE display=0 AND ('.$query.')');
        $inumberNotDisplay = Db::getInstance()->getValue('SELECT COUNT(`image_name`) FROM '._DB_PREFIX_.'product_image WHERE display=1 AND ('.$query.')');
        $query = "";
        $query2 = "";
        $icountDisplay = 0;
        $icountNotDisplay = 0;
        foreach ($aimage_products as $aimage_product)
        {
          $i++;
          if ($aimage_product['display'] == "0")
          {
            $icountDisplay++;
            $query .= 'image_name="'.$aimage_product['image_name'].'"';
            if ($icountDisplay < $inumberDisplay)
              $query .= ' OR ';
          }
          else
          {
            $icountNotDisplay++;
            $query2 .= 'image_name="'.$aimage_product['image_name'].'"';
            if ($icountNotDisplay < $inumberNotDisplay)
              $query2 .= ' OR ';
          }
           
        }
        if ($query != "")
          Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> '1'),'UPDATE', $query);  
        if ($query2 != "")
          Db::getInstance()->autoExecute(_DB_PREFIX_.'product_image', array("display"=> 0),'UPDATE', $query2);
      }
      
      $aproducts = Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'product_image WHERE id_product='.$_POST['inputProduct']);
			
			$this->_html .= '<form method=post action="'.$_SERVER['REQUEST_URI'].'"><div class="wssDisplayProduct" id="wssDisplayProduct"><div><input type="submit" name="deleteImgWss" value="'
        .$this->l("Delete").'" style="padding:1px 4px 1px 4px; margin-right:4px;font-size:10px" class="button"><input type="submit" name="displayImgWss" value="'
        .$this->l("Enabled/Disabled").'" style="padding:1px 4px 1px 4px;font-size:10px" class="button">
		<span class="button" style="cursor:pointer;margin:0;font-size:10px" id="checkAll">'.$this->l("Check all").'</span>
		<span class="button" style="cursor:pointer;margin:0;display:none;font-size:10px" id="unCheckAll">'.$this->l("UnCheck all").'</span>
        </div><input type=hidden name=inputProduct value="'.$_POST['inputProduct'].'"/>
        <input type=hidden name=submitproduct value="submit"/><input type=hidden name=nameProduct value="'.$_POST['inputProduct'].'">'; 
			foreach ($aproducts as $aproduct)
			{
        $this->_html .= '<div style="float:left;margin-top:5px;margin-left:15px"><span style="display:inline-block;position:relative;left:-205px;top:3px"><input class="checkAll" type="checkbox" name="checkbimg[]" value="'.$aproduct["image_name"].'" id="'
        .$aproduct["image_name"].'"/></span>';
        $sstatus = "";
        $simg = "";
        if ($aproduct['display'] == 0)
          $simg = _PS_ADMIN_IMG_.'/enabled.gif';
        else
          $simg = _PS_ADMIN_IMG_.'/disabled.gif';
        $this->_html .= '<span style="display:inline-block;position:relative;left:-20px;top:3px"><input type=submit name="displayalone" value="'.$aproduct['image_name'].'" 
        style="font-size:0px;width:18px; height:16px;background-color:transparent;background-image: url('.$simg.') ;cursor: pointer;border:0;" /></span>
		<script>
			$(function () {
				$("#checkAll").click(function () {
						$(".checkAll").attr("checked", true);
						$("#checkAll").hide();
						$("#unCheckAll").show();
				});
				$("#unCheckAll").click(function () {
						$(".checkAll").attr("checked", false);
						$("#unCheckAll").hide();
						$("#checkAll").show();
				});
		});
		</script>';
		
        $this->_html .= '<label for="'
        .$aproduct["image_name"].'"><span style="float:left;"><img src="'.$this->_path.'img/'.$aproduct["image_name"].'.png" width="50%" /></span></label></div>';
        
			}
			$this->_html .= '</div></form>';
      $this->_html .= '</fieldset><br/>';
        
			}
	}
	
	
	public		function setAssets()
	{
		// ASSETS NAMES
	$bg_name = "background.png";
	$watermark_name = "watermark.png";
		if (Tools::isSubmit('submitwssassets'))
		{
      if (isset($_FILES["assetbg"]) AND isset($_FILES['assetbg']['tmp_name']) AND file_exists($_FILES['assetbg']['tmp_name']))
      {
    
        if (filesize($_FILES['assetbg']['tmp_name']) > 75000)
        {
          $this->_html.= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png"/>'.$this->l('There is a warning').'<span id="labelSeeMoreWss" style="margin-left:20px;">'.$this->l('Image size is higher than 75kb').'</div>';
        }
        else
        {
         if ($bg_name != "" AND file_exists(dirname(__FILE__).'img/'.$bg_name))
			unlink(dirname(__FILE__).'/img/'.$bg_name);

        if (!move_uploaded_file($_FILES["assetbg"]["tmp_name"], dirname(__FILE__).'/img/'.$bg_name))
			$this->_html.= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png"/><span id="labelSeeMoreWSS" style="margin-left:20px;">'.$this->l('Error while file transfer').'</div>';
        else{
			chmod(dirname(__FILE__).'/img/'.$bg_name, 0704);
			}
        }
      }
      if (isset($_FILES["assetwm"]) AND isset($_FILES['assetwm']['tmp_name']) AND file_exists($_FILES['assetwm']['tmp_name']))
      {
    
        if (filesize($_FILES['assetwm']['tmp_name']) > 75000)
        {
          $this->_html.= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png"/>'.$this->l('There is a warning').'<span id="labelSeeMoreWss" style="margin-left:20px;">'.$this->l('Image size is higher than 75kb').'</div>';
        }
        else
        {
 
        if ($watermark_name != "" AND file_exists($this->_path.'img/'.$watermark_name))
          unlink(dirname(__FILE__).'/img/'.$watermark_name);
        if (!move_uploaded_file($_FILES["assetwm"]["tmp_name"], dirname(__FILE__).'/img/'.$watermark_name))
        $this->_html.= '<div class="warn"><img src="'._PS_ADMIN_IMG_.'warn2.png"/><span id="labelSeeMoreWSS" style="margin-left:20px;">'.$this->l('Error while file transfer').'</div>';
        else
          chmod(dirname(__FILE__).'/img/'.$watermark_name, 0704);
        }
      }
		}
		$this->_html .= '<fieldset><legend><img src="'.$this->_path.'img/cfg-account.gif" alt="Webcam Social Shopper" title="wss" /> '.$this->l('Assets configuration').'</legend>
		<div style="float:right;width:250px;">
                  '.$this->l(' Background Image – “Add your store’s logo to the WSS module background.  Click “Choose File” and select a .png image file that is smaller than 250 wide by 100 high.  Images with a white or transparent background are recommended.  This image will be aligned to the bottom right corner of the module.”').'       
				  <br/><br/><br/>
				  '.$this->l('Watermark Image – “Add your store’s logo to photos taken in WSS.  When users share their photos, friends and family will see your branding.  Click “Choose File” and select a .png image file that is smaller than 250 wide by 100 high.  Images with a transparent background are recommended.  This image will overlay the user’s photo in the bottom right corner.”').'
		
		</div>
		<form name="wssIdform" method="POST" action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" enctype="multipart/form-data">
		<div style="display:block; width:550px;">
		<label for="assetbg" style="float:left">'.$this->l('Select a background').' :</label>
		<input style="float:left"type="file" name="assetbg" id="assetbg" />
		';
      $this->_html .= '<div style="width:150px;height:150px; margin:0 auto 0 auto"><div>Background Image</div><div><img src="'.$this->_path.'img/'.$bg_name.'" id="background_image" style="max-height:100px"/></div></div>
						<script>
						$(function() {
							d = new Date();
                            $("#background_image").attr("src", "'.$this->_path.'img/'.$bg_name.'?"+d.getTime());
						});
						</script>';
		$this->_html .= '</div><div style="display:block; width:550px;">
			<label for="assetwm" style="float:left">'.$this->l('Select a watermark').' :</label>
		<input style="float:left" type="file" name="assetwm" id="assetwm" />
		';
		
      $this->_html .= '<div style="width:150px;height:150px; margin:0 auto 0 auto"><div>WaterMark Image</div>
      <div><img src="'.$this->_path.'img/'.$watermark_name.'" style="max-height:100px" id="watermark_image"/></div></div>
						<script>
						$(function() {
							d = new Date();
                            $("#watermark_image").attr("src", "'.$this->_path.'img/'.$watermark_name.'?"+d.getTime());
						});
						</script>';
		$this->_html .= '</div><div style="width:50px; height:25px;margin-left:200px"><input type="submit" id="wssidassets" class="button" name="submitwssassets" value="'.$this->l('Save').'"/></div></form><div style="margin-left: auto;margin-right:auto; width:300px">';
		$this->_html .= '</div>
		
		</fieldset><br/>';
	}
	
	private function setNTUpdates()
	{
		global $cookie;

		if (!isset($cookie) OR !is_object($cookie))
			$cookie->id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
		$query = 'SELECT iso_code FROM '._DB_PREFIX_.'lang WHERE id_lang='.$cookie->id_lang.'';
		$iso_lang = Db::getInstance()->getValue($query);

		$this->_html .= '<fieldset><legend><img src="'.UPDATE_URL.'/img/NT-update-logo.gif" alt="Update" title="NT Updates" /> '.$this->l('Update and support').'</legend>
		<iframe src="'.UPDATE_URL.'?os_name='.OS.'&module_name='.$this->name.'&version='.$this->version.'&iso_lang='.$iso_lang.'" width="100%" frameborder="0"></iframe>
		</fieldset><br/>';
	}
	
	function hookExtraLeft()
	{
		global $smarty;
		global $cookie;
		
		/* GET THE LANG CODE */
		if (!isset($cookie) OR !is_object($cookie))
			$cookie->id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
		$query = 'SELECT language_code FROM '._DB_PREFIX_.'lang WHERE id_lang='.$cookie->id_lang.'';
		$language_code = Db::getInstance()->getValue($query);
		$smarty->assign('language_code', str_replace("-", "_", $language_code));
	
		/* GET THE CURRENCY */
		if (!isset($cookie) OR !is_object($cookie))
		$cookie->id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
		$query = 'SELECT sign FROM '._DB_PREFIX_.'currency WHERE id_currency='.$cookie->id_currency.'';
		$currency = Db::getInstance()->getValue($query);
		$smarty->assign('currency', $currency);
		
		/* OTHER ASSIGN */
		$aimgs = Db::getInstance()->getValue("SELECT * FROM "._DB_PREFIX_.'product_image WHERE display=0 AND id_product='.Tools::getValue('id_product'));
		if ($aimgs && ($this->status['status'][0] == 0) && 
		(($this->status[0]['StoreLicenseTypeID'] == 7)
			OR ($this->status[0]['StoreLicenseTypeID'] == 5)
			OR ($this->status[0]['StoreLicenseTypeID'] == 3)
			OR ($this->status[0]['StoreLicenseTypeID'] == 2))
		)
      $smarty->assign('display', '1');
    else
      $smarty->assign('display', '0');
		$smarty->assign('this_path', $this->_path);
		$smarty->assign('itemID', Tools::getValue('id_product'));
			
		/* GET THE PRODUCT NAME */
		$p = new Product(Tools::getValue('id_product'));
		$smarty->assign('product_name', $p->name[$cookie->id_lang]);
	
		/* GET THE PRODUCT PRICE ROUNDED*/
		$smarty->assign('product_price', round((float)Product::getPriceStatic(Tools::getValue('id_product')), 2));
		
		
		/* Display the Smarty Page */
		return $this->display(__FILE__, 'webcamsocialshopper.tpl');		
	}
	
	function	hookHeader()
	{
		 Tools::addJS('js/webcamsocialshopper.js');
	}
}

?>