<?php

if (!page_checkParams()) die('Paramètres incorrects !');

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');

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

$tabInfo = $_SESSION['tabInfo'];

if (strlen($siret)==9)	$siret=$tabInfo['entrep']['siret'];

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

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

$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_SITE.'/cache/creditsafe/'.$fichier) )
	{
		$url='https://www.creditsafe.fr/getdata/service/CSFRServices.asmx/GetData?RequestXmlStr='.$req;
		$referer=$cookie='';
		$page=getUrl($url, $cookie, '', $referer, false, '', '');
		$referer=$url;
		$xml = html_entity_decode($page['body'], ENT_QUOTES, 'UTF-8');
		/** Enregistrement du fichier XML en provenance des greffes **/
		$fp=@fopen(PATH_SITE.'/cache/creditsafe/'.$fichier, 'w');
		@fwrite($fp, $xml);
		@fclose($fp);
		$O = $client->setLog('scorecsf', $siret);
	} else {
		/** Lecture du fichier XML en provenance des greffes **/
		$xml = file_get_contents(PATH_SITE.'/cache/creditsafe/'.$fichier);
		$O = $client->setLog('scorecsf', $siret, 0, 'local');
	}

	$dom_object = new DomDocument2();
	//TODO : Chemin !!
	$dom_object->load(PATH_SITE.'/cache/creditsafe/'.$fichier);
	$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 !';

	 		require_once 'sendmail/mail.php';
			sendMail(
				"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),
				//From
				array(
					'email' => 'contact@scores-decisions.com',
					'name' => 'Contact',
				),
				//TO
				array(
					0 => array(
						'email' => 'contact@scores-decisions.com',
						'name' => 'Contact',
					)
				)
			);

			$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 $item->nodeValue;
		}
	}

}
?>
</table>
<p class="confidentiel blockh2">
<?php
require_once 'cgu/cgu.php';
echo afficheCgu();
?>
</p>
</div>