<?php

ini_set('soap.wsdl_cache_enabled', 0);

class AmaSoapClient extends SoapClient {

    function __doRequest($request, $location, $action, $version) {
/*        $request = strtr($request, array('<ns1:'=>'<ama:',
        								 '</ns1:'=>'</ama:',
//        								 '<param0 xsi:type="xsd:string">'=>'',
        								 'xmlns:ns1="http://www.amabis.com/ama.xsd"'=>'xmlns:ama="http://www.amabis.com/ama.xsd"',
//        								 '</param0>'=>'',
//        								 '&lt;'=>'<',
//        								 '&gt;'=>'>',
        								)
        				);*/
        return parent::__doRequest($request, $location, $action, $version);
    }
}

class MAmabis {

	private $client;
	
	function __construct() {
	/*	$this->client = new AmaSoapClient(null, //'http://www.amabis.com/ama.wsdl',//null, //
							array(	'location'			=> AMABIS_WS_URL,//'http://sw4.amabis.com:5101',
                                    'uri'				=> AMABIS_WS_URI,//'http://sw4.amabis.com:5101',
                                    'soap_version'		=> SOAP_1_1,
                                    'trace'				=> 1,
                                    'style'				=> SOAP_RPC,
                                    'use'           	=> SOAP_ENCODED,
                                    'connection_timeout'=> 2,
                                 )
                         	);
      */                   	
        $this->client = new AmaSoapClient(null,
        					array(	//'location'				=> 'http://sw4.amabis.com:5100',
        							'location'				=> 'http://sw2.amabis.com:5100/',
          							'uri'					=> 'http://www.amabis.com/ns.xsd',
									'connection_timeout'	=> 2,
									'default_socket_timeout'=> 2,
									'soap_version'			=> SOAP_1_1,
                                    'trace'					=> 1,
                                    'style'					=> SOAP_RPC,
                                    'use'       	    	=> SOAP_ENCODED,
          						 )
          					);
	}
	
	function getZonage($adrNum, $adrIndRep, $adrTypeVoie, $adrLibVoie, $cp, $ville='', $codeRivoli='', $rnvp=false, $raisonSociale='TEST', $debug=false) {
		$tabRep=array();
		if (!$rnvp) {
			if ($cp<10000)	$cp='0'.$cp;
			$dep2=substr($cp,0,2)*1;
			$dep3=substr($cp,0,3)*1;
			switch ($dep2) {
				case 0:
				case 5:
				case 9:
				case 15:
				case 19:
				case 23:
				case 32:
				case 46:
				case 48:
				case 82:
				case 97:	// DOM
				case 98:	// TOM
				case 99:	// Etranger
					return $tabRep;
					break;
				default:
					//if ($dep3==975)	return $tabRep;
					break;
			}
		}
		
		$iDb=new WDB();
		$adresse=addslashes(trim(preg_replace('/ +/',' ', "$adrNum $adrIndRep $adrTypeVoie $adrLibVoie")));
		$ville=addslashes($ville);
		$ret=$iDb->select(	'zonage', 'zus, zru, zfu, cucs', "address='$adresse' AND adr_cp='$cp' AND adr_ville='$ville'",false, MYSQL_ASSOC);
		if (count($ret)>0) {
			$zones=$ret[0];
			$tabRep['ZUS']=$tabRep['ZFU']=$tabRep['ZRU']=$tabRep['CUCS']='NON';
			if (trim($zones['zus'])<>'') {
				if (trim($zones['zus'])=='NSP')		$tabRep['ZUS']='NSP';
				else 								$tabRep['ZUS']='OUI';
				$tabRep['NZUS']=$zones['zus'];
			}
			if (trim($zones['zru'])<>'') {
				if (trim($zones['zru'])=='NSP')		$tabRep['ZRU']='NSP';
				else 								$tabRep['ZRU']='OUI';
				$tabRep['NZRU']=$zones['zru'];
			}
			if (trim($zones['zfu'])<>'') {
				if (trim($zones['zfu'])=='NSP')		$tabRep['ZFU']='NSP';
				else 								$tabRep['ZFU']='OUI';
				$tabRep['NZFU']=$zones['zfu'];
			}
			if (trim($zones['cucs'])<>'') {
				if (trim($zones['cucs'])=='NSP')	$tabRep['CUCS']='NSP';
				else 								$tabRep['CUCS']='OUI';
				$tabRep['NCUCS']=$zones['cucs'];
			}
			//return $tabRep;
		} else {
		
		try {
			if (trim($raisonSociale)=='') $raisonSociale='TEST';	// Le RNVP ne fonctionne pas sans la Raison Sociale qui est la 1ère ligne d'adresse
			$rep=$this->client->zonage(	new SoapParam(strtr("$raisonSociale:$adresse:$cp:$ville",
			'¿°ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿ??', 
    		'  aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr'),'adresse'),
          								new SoapParam(':','separateur'),
          								new SoapParam('type=M','options')
          							  );
			/*$rep=$this->client->zonage(	"<adresse></adresse>".
										"<separateur>:</separateur>".
										"<options>type=M</options>");*/
			
			/** Découpage des ZFU, CUCS etcs...
			 **/
			$fp=fopen(LOG_PATH.'/amabis.log', 'a');
			fwrite($fp, date('d-m-Y H:i:s').' - '.implode("\n", $rep)."\n============================================================================\n");
			fclose($fp);
			
			$tabZones=explode(',',$rep['zonage']); // ZUS=OUI,NZUS=1127020,ZFU=OUI,NZFU=11270ZF,CUCS=OUI,NCUCS=1127020
			foreach ($tabZones as $zone) {
				$tabTmp=explode('=',$zone);
				if (trim($tabTmp[0])<>'')
					$tabRep[$tabTmp[0]]=$tabTmp[1];
			}
			if ($tabRep['ZUS']=='NSP')	$tabRep['NZUS']='NSP';
			if ($tabRep['ZRU']=='NSP')	$tabRep['NZRU']='NSP';
			if ($tabRep['ZFU']=='NSP')	$tabRep['NZFU']='NSP';
			if ($tabRep['CUCS']=='NSP')	$tabRep['NCUCS']='NSP';
			$adresse=stripslashes(trim(preg_replace('/ +/',' ', "$adrNum $adrIndRep $adrTypeVoie $adrLibVoie")));
			$ville=stripslashes($ville);
			$tabInsert=array(	'address'=>$adresse,
								'adr_cp'=>$cp,
								'adr_ville'=>$ville,
								'zus'=>$tabRep['NZUS'],
								'zru'=>$tabRep['NZRU'],
								'zfu'=>$tabRep['NZFU'],
								'cucs'=>$tabRep['NCUCS'],
								'adrNum'=>$adrNum,
								'adrIndRep'=>$adrIndRep,
								'adrTypeVoie'=>$adrTypeVoie,
								'adrLibVoie'=>$adrLibVoie,
								'rivoli'=>$codeRivoli,
							);
			$iDb->insert('zonage', $tabInsert);
			
			/** Autres Informations de la RNVP
			 **/
			if ($rnvp || $debug) {
				$tabRepTmp=array();
				$tabZones=explode(',',$rep['objdesc']);
				foreach ($tabZones as $zone) {
					$tabTmp=explode('=',$zone);
					if (trim($tabTmp[0])<>'') 
						$tabRepTmp[$tabTmp[0]]=$tabTmp[1];
				}
				if (!$debug) {
					$tabRep['ADR1']=@$tabRepTmp['ADR1'];
					$tabRep['ADR2']=@$tabRepTmp['ADR2'];
					$tabRep['ADR3']=@$tabRepTmp['ADR3'];
					$tabRep['ADR4']=@$tabRepTmp['ADR4'];
					$tabRep['ADR5']=@$tabRepTmp['ADR5'];
					$tabRep['ADR6']=@$tabRepTmp['ADR6'];
					$tabRep['ADR7']=@$tabRepTmp['ADR7'];
				} else {
					$tabRep=array_merge($tabRep, $tabRepTmp);
				}
			}
		} catch (SoapFault $fault) {
			echo 'ERREUR SOAP :'.EOL;
			print_r($fault);
			echo $this->client->__getLastRequest()."\n";
			echo $this->client->__getLastResponse()."\n";
			$fp=fopen(LOG_PATH.'/amabis.log', 'a');
			fwrite($fp, date('d-m-Y H:i:s').' - ERREUR SOAP : Requete = '.$this->client->__getLastRequest()."\n Reponse = ".$this->client->__getLastResponse()."\n============================================================================\n");
			fclose($fp);
		}
		//return $tabRep;
		}
		$codeInsee=substr($codeRivoli,0,5);
		$ret=$iDb->select(	'zonageInsee', 'typeZone, arreteDate, decretDate, decretNum, decretModifieDate, decretModifieNum, dateDebut, dateFin', "codeInsee='$codeInsee'",false, MYSQL_ASSOC);
		$tabRep['ZRR']=$tabRep['AFR']='NON';
		foreach ($ret as $zones)
			switch ($zones['typeZone']) {
				case 'ZRR':		$tabRep['ZRR']='OUI';	$tabRep['NZRR']=$codeInsee;		break;
				case 'ZAFR':	$tabRep['AFR']='OUI';	$tabRep['NAFR']=$codeInsee;		break;
				default:																break;
			}
		
		return $tabRep;
	}

	function searchByTelFax($tel) {
		return $this->getTelFax('','','','',$tel);
	}

	function getTelFax($nom, $cp, $ville='', $prenom='', $tel='') {
		if (trim($tel)<>'')
			$query="<telep>$tel</telep><scoremini>10</scoremini><distinction>30</distinction>";
		elseif (trim($prenom)=='')
			$query="<rs>$nom</rs><cpville>$cp $ville</cpville><scoremini>90</scoremini><distinction>30</distinction>";
		else
			$query="<nom>$nom</nom><prenom>$prenom</prenom><cpville>$cp $ville</cpville><scoremini>90</scoremini><distinction>30</distinction>";
		 
		$rep=$this->client->rechtel($query);
		
		$fp=fopen(LOG_PATH.'/amabis.log', 'a');
		fwrite($fp, date('d-m-Y H:i:s')." - $query - ".implode("\n", $rep)."\n============================================================================\n");
		fwrite($fp, "Requête : ".$this->client->__getLastRequest()."\n");
		fwrite($fp, "Réponse : ".$this->client->__getLastResponse()."\n");
		fclose($fp);
	}
	
}

?>