<?

define('CREDITSAFE_WS_URL', 'https://www.creditsafe.fr/getdata/service/CSFRServices.asmx');
define('CREDITSAFE_WS_URI', 'https://www.creditsafe.fr/getdata/service/');

define('CREDITSAFE_WS_USER', 'scores_decisions');
define('CREDITSAFE_WS_PASS', 'yoann1306');

define('CREDITSAFE_WS_REF', 'ref');


if (!$_SESSION['connected'])	die();

function formatPct($pct) {
	$pct=round($pct/10,0)*10;
	if ($pct==0)	$pct=10;
	return $pct;
}

$tabInfo = $_SESSION['tabInfo'];

$siret=trim(preg_replace('/[^0-9]/', '', $_REQUEST['siret']));
if (strlen($siret)<>9 && strlen($siret)<>14)	die('Paramètres incorrects !');
if (strlen($siret)==9)	$siret=$tabInfo['entrep']['siret'];

$idEntreprise=trim(preg_replace('/[^0-9]/', '', $_REQUEST['idEntreprise']))*1;	// Si id=0 alors non communiqué
if (($siret*1)==0 && $idEntreprise==0) 										die('Paramètres incorrects !');
$siren=substr($siret,0,9);

$action=$_REQUEST['action'];
if ($action<>'' && $action<>'commande')	die('Paramètres incorrects !');


$raisonSociale=$tabInfo['entrep']['raisonSociale'];

require_once 'partenaires/classMTva.php';
require_once 'partenaires/classMMap.php';
require_once 'partenaires/classMCoface.php';
require_once 'common/dates.php';


/*$client = new SoapClient('https://www.creditsafe.fr/getdata/service/CSFRServices.asmx?WSDL',
							 array(	'location'      => CREDITSAFE_WS_URL,
									'uri'			=> CREDITSAFE_WS_URI,
									'soap_version'  => SOAP_1_1,
									'trace'         => 1,
                                  		//'style'         => SOAP_RPC,
                                        //'use'           => SOAP_ENCODED,
									 ));
	*/

	$req='<xmlrequest>'.
			'<header>'.
				'<username>'.CREDITSAFE_WS_USER.'</username>'.
				'<password>'.CREDITSAFE_WS_PASS.'</password>'.
        		//'<operation>getcompanyinformation</operation>'.
        		'<operation>getratinglimit</operation>'.
        		'<country>FR</country>'.
        		'<language>FR</language>'.
        		'<chargereference>'.CREDITSAFE_WS_REF.'</chargereference>'.
    		'</header>'.
    		'<body>'.
				//'<package>standard</package>'.
				'<package>ratinglimit</package>'.
				"<companynumber>$siret</companynumber>".
    		'</body>'.
		'</xmlrequest>';

	$success=true;
	$date=date('Ymd');
	$fichier=$siret.'-'.$date.'.xml';

	if ( !file_exists(PATH_DATA.'/creditsafe/xml/'.$fichier) ) {
	/*	try {
			$O=$client->GetData('<RequestXmlString><xmlrequest>'.
			'<header>'.
				'<username>'.CREDITSAFE_WS_USER.'</username>'.
				'<password>'.CREDITSAFE_WS_PASS.'</password>'.
        		'<operation>getcompanyinformation</operation>'.
        		'<country>FR</country>'.
        		'<language>FR</language>'.
        		'<chargereference>'.CREDITSAFE_WS_REF.'</chargereference>'.
    		'</header>'.
    		'<body>'.
				'<package>standard</package>'.
				"<companynumber>$siret</companynumber>".
    		'</body>'.
		'</xmlrequest></RequestXmlString>');
			//die(print_r($O));
			$xml=implode('', (array)$O);
		}
		catch (SoapFault $soapFault) {//        echo "ERROR :\n", var_dump($soapFault), "\n"; echo "Request :\n", $client->__getLastRequest(), "\n";
	        $success=false;
			$response=$client->__getLastResponse();
			$response=str_replace("<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><SOAP-ENV:Body><ns0:getProduitsWebServicesXMLResponse xmlns:ns0='urn:local' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'><return xsi:type='xsd:string'>",'', $response);
			$xml=str_replace('</return></ns0:getProduitsWebServicesXMLResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>','', $response);
		}*/
	        //https://www.creditsafe.fr/getdata/service/CSFRServices.asmx/GetData
		//$url='https://www.creditsafe.fr/getdata/service/CSFRServices.asmx/GetData?RequestXmlString='.$req;
		$url='https://www.creditsafe.fr/getdata/service/CSFRServices.asmx/GetData?RequestXmlStr='.$req;//.'&RequestXmlString='.$req;
																				//requestXmlStr.
		$referer=$cookie='';
		$page=getUrl($url, $cookie, '', $referer, false, '', '');
		$referer=$url;

		/*
		$fp=@fopen(htmlspecialchars($url), 'rb');
		print $content = stream_get_contents($fp);
		fclose($fp);
		*/
		$xml=html_entity_decode($page['body'], ENT_QUOTES, 'UTF-8');
		/** Enregistrement du fichier XML en provenance des greffes
		 **/
		//TODO : Chemin !!
		$fp=@fopen(PATH_DATA.'/creditsafe/xml/'.$fichier, 'w');
		@fwrite($fp, $xml);
		@fclose($fp);


		$O = $client->setLog('scorecsf', $siret);

	} else {
		/** Lecture du fichier XML en provenance des greffes
		 **/
		//TODO : Chemin !!
		$xml=file_get_contents(PATH_DATA.'/creditsafe/xml/'.$fichier);
		$O = $client->setLog('scorecsf', $siret, 0, 'local');
	}
	/*<>100</rating>
2000000</creditlimit>*/

	$dom_object = new DomDocument2();
	//TODO : Chemin !!
	$dom_object->load(PATH_DATA.'/creditsafe/xml/'.$fichier);
	/* create DOMXPath object with our DOMObject
	$xpath = new Domxpath($dom_object);
	$result = $xpath->query("//liste_depot_acte/depot_acte/.");
foreach ($result as $annonce) {
	// N° Gestion
	$title = $xpath->query ("num_gest/greffe", $annonce);
	$num_gest_greffe=$title->item(0)->nodeValue;
	*/
	$companyname=$dom_object->getValueFromTag('companyname');
	$rating=$dom_object->getValueFromTag('rating');
	$ratingdesc1=str_replace('?',"'",$dom_object->getValueFromTag('ratingdesc1'));
	$ratingdesc2=str_replace('?',"'",$dom_object->getValueFromTag('ratingdesc2'));
	$creditlimit=$dom_object->getValueFromTag('creditlimit');
	$libelle='';
	if (strtoupper($creditlimit)<>strtolower($creditlimit) || $creditlimit=='')
		$strCreditlimit=$creditlimit;
	else
		$strCreditlimit=number_format($creditlimit,null,null,' '). ' &euro;';

	if       ($rating>=40)	{
		$fontColor='green';
		$imgFeux='<img src="./img/creditsafe/feux_vert.png"/>';
		if     ($rating>=71)	$libelle='Très bonne cote de crédit/solvabilité';
		elseif ($rating>=51)	$libelle='Bonne cote de crédit/solvabilité';
		else					$libelle='Solvable';

	} elseif ($rating>=20)	{
		$fontColor='yellow';//#f2be2c';
		$imgFeux='<img src="./img/creditsafe/feux_orange.png"/>';
		$libelle='Précautions recommandées';
	} elseif (strtoupper($rating)<>strtolower($rating)) {
		$fontColor='black';
		$imgFeux='&nbsp;';
	}
	elseif ($rating=='') {
		$fontColor='black';
		$imgFeux='&nbsp;';
	}
	else {
		$fontColor='red';
		$imgFeux='<img src="./img/creditsafe/feux_rouge.png"/>';
		if     ($rating==0)	$libelle='Entreprise en situation de défaillance et ayant un très fort risque de radiation';
		else 				$libelle='Avertissement - Crédit à votre discrétion';
	}

?>
<div id="center">
<h1 class="titre">&Eacute;VALUATION</h1>

<table>
<tr>
	<td width="30">&nbsp;</td>
	<td width="200" class="StyleInfoLib">Num&eacute;ro identifiant Siren</td>
	<td width="350" class="StyleInfoData"><?=substr($siret,0,3).' '.substr($siret,3,3).' '.substr($siret,6,3)?></td>
</tr>
<tr>
	<td width="30">&nbsp;</td>
	<td width="200" class="StyleInfoLib">Raison Sociale</td>
	<td width="350" class="StyleInfoData"><?if ($companyname<>'')	echo $companyname;
											else 					echo $raisonSociale;
	?></td>
</tr>
<?	if ($etab['NumRC']*1<>0) { ?>
<tr>
	<td width="30">&nbsp;</td>
	<td width="200" class="StyleInfoLib">Num&eacute;ro R.C.</td>
    <td width="350" class="StyleInfoData"><?=$etab['NumRC']?></td>
</tr>
<?	}	?>
<tr>
</table>

<h2>Scoring partenaire : Creditsafe&reg;</h2>
<table>
<tr><td colspan="3">
	  <table cellspacing="0">
	  <tr>
		<td width="20">&nbsp;</td>
		<td width="10"  bgcolor="#bebebe">&nbsp;</td>
		<td width="200" bgcolor="#bebebe"><font size="2"><b>Note &agrave; ce jour [0 - 100]</b></font></td>
		<td width="250" bgcolor="#bebebe"><font color="<?=$fontColor?>" size="2"><?=$rating;?></font></td>
		<td width="100" bgcolor="#bebebe"><?=$imgFeux?></td>
	  </tr>
	  <tr>
		<td width="20">&nbsp;</td>
		<td width="10"  bgcolor="#e7e7e7">&nbsp;</td>
		<td width="200" bgcolor="#e7e7e7"><font size="2"><b>Limite &agrave; ce jour [&euro;]</b></font></td>
		<td width="350" colspan="2" bgcolor="#e7e7e7"><font size="2"><?=$strCreditlimit?></font></td>
	  </tr>
	  <tr>
		<td width="20">&nbsp;</td>
		<td width="10"  bgcolor="#bebebe">&nbsp;</td>
		<td width="200" bgcolor="#bebebe"><font size="2"><b>Informations compl&eacute;mentaires</b></font></td>
		<td width="350" colspan="2" bgcolor="#bebebe"><font color="<?=$fontColor?>" size="2"><?=$libelle.'<br/>'.$ratingdesc1; if (trim($ratingdesc2)<>'') echo '<br/>'.$ratingdesc2;?></font></td>
	  </tr>
	  </table>
  </td>
 </tr>
<?php
if ($action<>'commande') {
?>
<tr>
	<td width="30">&nbsp;</td>
	<td width="550" colspan="2" class="StyleInfoData"><br/><br/><form action="./?page=scorescf&action=commande&siret=<?=$siret?>&idEntreprise=<?=$idEntreprise?>" method="POST"><input type="checkbox"/> Mettre cette entreprise sous surveillance scoring partenaire<br/><br/>Adresse email du destinataire <input name="email" type="text" value="<? if ($_SESSION['tabInfo']['login']<>'testreunica' && $_SESSION['tabInfo']['login']<>'reunicacsf') echo $tabInfo['email']?>" size="20"/>&nbsp;&nbsp;&nbsp;<input class="imgButton" type="image" src="./img/boutton_valider_off.gif" name="submit" onmouseover="this.src='./img/boutton_valider_on.gif'" onmouseout="this.src='./img/boutton_valider_off.gif'" title="Surveiller le score partenaire de cette entreprise..."></form></td>
</tr>
<?
	} else {
		if (preg_match('#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,5}$#',$_REQUEST['email'])) {
	 		$message='Entreprise mise sous surveillance scoring partenaire !';
			mail(	'contact@scores-decisions.com',"Demande de surveillance score CreditSafe pour $siren à ".$_REQUEST['email'],
					'REQUEST='.EOL.print_r($_REQUEST,true).'EOL'.
					'SERVER='.EOL.print_r($_SERVER,true).'EOL'.
					'SESSION='.EOL.print_r($_SESSION,true).'EOL'.
					'ENV='.EOL.print_r($_ENV,true).'EOL'.
					'tabInfo='.print_r($tabInfo,true));
			$fp=fopen(PATH_LOGS.'surveillance_scf.csv', 'a');
			fwrite($fp, date('Y/m/d H:i:s').";$siren;".$_REQUEST['email'].';'.$tabInfo['login'].';'.$tabInfo['email'].';'.$tabInfo['ip']."\n");
			fclose($fp);
		} else {
			$message="ERREUR : Veuillez saisir une adresse email valide pour la mise sous surveillance";
		}
 ?>
  <tr>
	<td width="30">&nbsp;</td>
	<td width="550" colspan="2" class="StyleInfoData"><br/><br/><h3><?=$message;?></h3></td>
  </tr>
<?php
	}

  class DomDocument2 extends DOMDocument {

	function getValueFromTag($tagName) {
		$items=$this->getElementsByTagName($tagName);
		foreach ($items as $item) {

    		return utf8_decode($item->nodeValue);
		}
	}

}
?>
</table>
</div>