<?
require_once 'common/curl.php';

class MBilans {

	private $body = '';
	private $header = '';
	private $codeRetour = 0;
	private $cookie='';
	private $reference = 0;
	private $timeOut=0;
	private $url='';
	private $referer='';
	private $curPage='';

	public $siren;
	public $dernierExerciceDepose=0;
	public $dernierExerciceDeposeLe=0;

	function __construct($siren) {
		$this->partGetSession();
		$this->siren=$siren;
	}

	function __destruct() {
		$this->partSaveSession();
	}


	function listeBilans($uniquementEnBase=true) {
		//if ($siren<>0)	$this->siren=$siren;
		$iDb2=new WDB('insee');
		$ret=$iDb2->select(	'bilans', 'dateProvPartenaire, dateExercice, dateExercicePre, dureeExercice, dureeExercicePre, monnaieOrigine',
							"siren='$this->siren' ORDER BY dateExercice DESC");
//		if 		(count($ret)==0) return array();	// Pas de bilan disponible !
//		else {
			$tabRet=array();
			if (!$uniquementEnBase) {
				$iDb=new WDB('jo');
				$ret2=$iDb->select(	'bodacc_detail', 'Bodacc_Date_Parution, dateEffet, Bodacc_Num, Bodacc_Date_Parution, Num_Annonce, RC, raisonSociale, FJ, adrSiegeNum, adrSiegeIndRep, adrSiegeTypVoie, adrSiegeLibVoie, adrSiegeComp1, adrSiegeComp2, codePostalSiege, villeSiege', "siren='$this->siren' AND Rubrique='comptes' ORDER BY dateEffet DESC");
				$dateDerDepot=WDate::dateT('Y-m-d','Ymd',@$ret2[0]['dateEffet'])*1;
				$dateDerExercice=$ret[0]['dateExercice']*1;
				if ($dateDerDepot<>0) {
					$this->dernierExerciceDepose	= WDate::dateT('Y-m-d','d/m/Y',@$ret2[0]['dateEffet']);
					$this->dernierExerciceDeposeLe	= WDate::dateT('Y-m-d','d/m/Y',@$ret2[0]['Bodacc_Date_Parution']);
				}
				echo date('Y/m/d - H:i:s') ." - Dernier depot le ". $ret2[0]['Bodacc_Date_Parution'] .", dernier en base = $dateDerExercice !<br/>\n";
				if (   $dateDerDepot>$dateDerExercice ||
					 ( $dateDerDepot==0 && $dateDerExercice<date('Ymd', mktime(0,0,0, date('m')-16, date('d'), date('Y'))) ) ) {
					$tabRet=$this->partListeBilans();
				}
			}
			foreach ($ret as $i=>$bil) {
				$tabRet[$bil['dateExercice']]=array('dateProvPartenaire'=>$bil['dateProvPartenaire'],
													'dureeExercice'		=>$bil['dureeExercice'],
													'dateExercicePre'	=>$bil['dateExercicePre'],
													'dureeExercicePre'	=>$bil['dureeExercicePre'],
													'monnaie'			=>$bil['monnaieOrigine'],
													'source'			=>1,
													);
			}
			return $tabRet;
//		}
	}

	function getBilan($millesime='', $source=1) {

		$iDb2=new WDB('insee');
		$ret=$iDb2->select('bilans', 'dateProvPartenaire, dateExercice, dateExercicePre, dureeExercice, dureeExercicePre, monnaie, typeBilan, monnaieOrigine, unite, postes', "siren='$this->siren' AND dateExercice='$millesime'", true);
		/*echo $this->siren.'<br/>';
		echo $millesime.'<br/>';
		print_r($ret[0]);die();*/
		$bilan=$ret[0];
		if (count($ret)==0) {
			$tabBilan=$this->partGetBilan(WDate::dateT('Ymd','d/m/Y',$millesime));
			if ($tabBilan) {
				$tabInsert=array(	'siren'				=>$this->siren,
									'dateProvPartenaire'=>$tabBilan['DATE_FRAICHE_BILAN'],
									'dateExercice'		=>$tabBilan['DATE_CLOTURE'],
									'dateExercicePre'	=>$tabBilan['DATE_CLOTURE_PRE'],
									'dureeExercice'		=>$tabBilan['DUREE_MOIS'],
									'dureeExercicePre'	=>$tabBilan['DUREE_MOIS_PRE'],
									'monnaie'			=>$tabBilan['MONNAIE'],
									'typeBilan'			=>$tabBilan['CONSOLIDE'],
									'monnaieOrigine'	=>$tabBilan['MONNAIE_ORI'],
									'unite'				=>$tabBilan['MONNAIE_LIV_UNITE'],
									'postes'			=>$tabBilan['POSTES'],
									'partenaire'		=>1,
								);
				$iDb2->insert('bilans', $tabInsert);
				$ret=$iDb2->select('bilans', 'dateProvPartenaire, dateExercice, dateExercicePre, dureeExercice, dureeExercicePre, monnaie, typeBilan, monnaieOrigine, unite, postes', "siren='$this->siren' AND dateExercice='$millesime'");
				$bilan=$ret[0];
			}
		}
		$tabBilan=array();
		$tabBilan['SIREN']				= $this->siren;
		$tabBilan['DATE_FRAICHE_BILAN']	= $bilan['dateProvPartenaire'];	// SSAAMMJJ
		$tabBilan['DATE_CLOTURE']		= $bilan['dateExercice'];	// SSAAMMJJ
		$tabBilan['DATE_CLOTURE_PRE']	= $bilan['dateExercicePre'];	// SSAAMMJJ
		$tabBilan['DUREE_MOIS']			= $bilan['dureeExercice'];
		$tabBilan['DUREE_MOIS_PRE']		= $bilan['dureeExercicePre'];
		$tabBilan['MONNAIE']			= $bilan['monnaie'];
		$tabBilan['CONSOLIDE']			= $bilan['typeBilan'];	// C = Bilan consolidé
		$tabBilan['MONNAIE_ORI']		= $bilan['monnaieOrigine'];
		$tabBilan['MONNAIE_LIV_UNITE']	= $bilan['unite'];
		if ($bilan['monnaie']=='EUR')	$monnaie='&euro;';	else $monnaie=$bilan['monnaie'];
		switch (strtoupper($bilan['unite'])) {
			case 'K':	$unite='K';		break;
			case 'U':
			case ' ':
			case '' :	$unite='';		break;
			case 'M':	$unite='M';		break;
			default:	die('Unite Bilan ('. $bilan['unite'] .') non prise en charge !');	break;
		}
		$tabBilan['devise']				= /*$unite.*/$monnaie;

		$tabTmp=explode(';', $bilan['postes']);
		foreach ($tabTmp as $i=>$strTmp) {
			$tabTmp2=explode('=', $strTmp);
			if (isset($tabTmp2[1]))
				if     ($unite=='K' && $tabTmp2[0]<>'YP')	$tabBilan[$tabTmp2[0]]=$tabTmp2[1]*1000;
				elseif ($unite=='M' && $tabTmp2[0]<>'YP')	$tabBilan[$tabTmp2[0]]=$tabTmp2[1]*1000000;
				else										$tabBilan[$tabTmp2[0]]=$tabTmp2[1];
		}
		return $tabBilan;
	}

	private function partConnection() {
		if (!$this->cookie || time()>$this->timeOut) {
			$this->timeOut=time()+600;
			/** Recherche de machine dispo **/
			$this->referer='http://hyperbil.bil.fr/';
			$page=getUrl($this->referer, '', '', '', false, 'hyperbil.bil.fr');
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];
			$this->header=$page['header'];

			/** Redirection sur la bonne machine**/
			$this->url=trim(str_replace('https://', 'http://', $this->header['Location']));
			if (substr($this->url,-1)=='/')	$this->url=substr($this->url, 0, strlen($this->url)-1);

			$this->domaine=str_replace('/', '', str_replace('http:/', '', $this->url));
			//echo "Redirection sur $this->url<br/>Domaine = $this->domaine<br/>Referer = $this->referer<br/>";
			$page=getUrl($this->url, '', '', $this->referer, false, $this->domaine);
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];
			$this->header=$page['header'];

			/** Connexion LOGIN PASSWORD **/
			//print_r($this->header);
			$this->cookie=$this->header['Set-Cookie'];
			$postData=array('rq'=>'hbilabon', 'QPABO'=>'101001002', 'QPPAS'=>'otY66');
			$urlConn=$this->url.'/cgi-bin/h2r';
			//echo "Connexion à $urlConn<br/>";
			$page=getUrl($urlConn, $this->cookie, $postData, $this->url, false, $this->domaine);
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];
			$this->header=$page['header'];
			$this->cookie=$this->header['Set-Cookie'];

			/** Base entreprise **/
//			print_r($this->header);
			$urlEntrep=$this->url.'/cgi-bin/h2r?rq=hbilcrit&QPABO=101001002';///cgi-bin/h2r?rq=hbilcrit"
			sleep(1);
			$page=getUrl($urlEntrep, $this->cookie, '', $this->url, false, $this->domaine);
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];
			$this->header=$page['header'];
		}
	}

	private function partVitrine() {
		//echo "Recherche du siren $this->siren<br/>\n";
		$this->partConnection();

		/** Liste des établissements **/
		$urlEntrep=$this->url .'/cgi-bin/h2r?rq=hbilentl&QEREC=B&QESIR='.$this->siren
							.'&QENOM=&QEPRN=&QENAIA=&QENAIM=&QECP=&QESIEG=A&QEVIL=&QENRU=&QERUE=&QEAPE=&QETEL=&QENAOB&wi=1';
			/*	QESIEG :
				""  = Tous les étab
				"A" = Dernier Si&egrave;ge Actif connu
				"S" = Historique des Si&egrave;ges
				"E" = Historique des &eacute;tablissements secondaires
			 */
		//sleep(1);
		$page=getUrl($urlEntrep, $this->cookie, '', $this->url, false, $this->domaine);
	 	$bil=$page['body'];
	 	preg_match_all('/"\/cgi-bin\/h2r\?rq=hbiliden&QINUME=(\d*)&QISIR=(\d*)&(.*)"/', $bil, $matches);
		//print_r($matches);
		/** Fiche d'identité du siège **/
		$urlEntrep=$url. str_replace('"', '', $matches[0][0]);
	 	sleep(1);
		$page=getUrl($urlEntrep, $this->cookie, '', $this->url, false, $this->domaine);
	 	$bil=$page['body'];
	 	$this->reference=$matches[1][0];
	 	//echo "QINUME = $this->reference<br/>\n";
	}

	private function partListeBilans() {
		$this->partVitrine();
 		$urlEntrep=$this->url."/cgi-bin/h2r?rq=hbilbill&QINUME=$this->reference&QISIR=$this->siren&wi=1&wc=N";
		$page=getUrl($urlEntrep, $this->cookie, '', $this->url, false, $this->domaine);
		echo date('Y/m/d - H:i:s') ." - Liste des bilans de notre partenaire : $urlEntrep<br/>\n";
		$tabRet=array();
		if (preg_match_all("/NAME=\"QBDTCN\" VALUE=\"(.*)\"><B>(?:.*)Dur&eacute;e : <B>(.*) mois/i", $page['body'], $matches)) {
			foreach ($matches[1] as $num=>$millesime) {
				$millesime=WDate::dateT('d/m/Y','Ymd',$millesime);
				$tabRet[$millesime]=array(	'dateProvPartenaire'=>date('Ymd'),
										  	'dureeExercice'		=>$matches[2][$num],
											'dateExercicePre'	=>WDate::dateT('d/m/Y','Ymd',$matches[1][$num+1]),
											'dureeExercicePre'	=>$matches[2][$num+1],
											'monnaie'			=>'EUR',
											'source'			=>0,
										  );
			}
		}
		return $tabRet;
	}

	private function partGetBilan($millesime) {
		$this->partConnection();

		$urlEntrep=$this->url."/cgi-bin/h2r?rq=hbilsobi&QINUME=$this->reference&QISIR=$this->siren&wi=1&wc=N&QIMONN=EU&QIDLIM=".urlencode($millesime);

		$page=getUrl($urlEntrep, $this->cookie, '', $this->url, false, $this->domaine);
		echo date('Y/m/d - H:i:s') ." - Bilan $millesime de notre partenaire : $urlEntrep<br/>\n";

 		$bil=strip_tags($page['body']);
		$fcontents=explode("\n",$bil);
		$tabBilan=array();
		$i=1;
		$tabBilan['SIRET']				=substr($fcontents[1],  36, 14);
		$tabBilan['DATE_FRAICHE_BILAN']	=trim(substr($fcontents[1],  57,  8));	// SSAAMMJJ
		if ($tabBilan['DATE_FRAICHE_BILAN']=='')	return false;
		$tabBilan['DATE_CLOTURE']		=trim(substr($fcontents[1], 101,  8));	// SSAAMMJJ
		$tabBilan['DATE_CLOTURE_PRE']	=trim(substr($fcontents[1], 109,  8));	// SSAAMMJJ
		$tabBilan['DUREE_MOIS']			=trim(substr($fcontents[1], 117,  2));
		$tabBilan['DUREE_MOIS_PRE']		=trim(substr($fcontents[1], 119,  2));
		$type							=trim(substr($fcontents[1], 123,  1));	// C = Bilan consolidé
		if ($type=='')		$tabBilan['CONSOLIDE']='N';
		elseif ($type=='C')	$tabBilan['CONSOLIDE']='C';
		else {				$tabBilan['CONSOLIDE']=$type;
							echo ("Type de bilan inconnu en provenance de notre partenaire B='$type' !");
		}
		$tabBilan['MONNAIE_ORI']		=trim(substr($fcontents[1], 793,  3));
		$tabBilan['MONNAIE_UNITE']		=trim(substr($fcontents[1], 796,  1));
		$tabBilan['MONNAIE']			=trim(substr($fcontents[1], 797,  3));
		$tabBilan['POSTES']				='';

		while (substr($fcontents[$i], 65, 1)=='7') {
			for ($j=0; $j<30; $j++)
			{
				$code			=rtrim(substr($fcontents[$i],   124+$j*20,   4));
				if ($code!='')
				{
					$colonneLiasse=(int)substr($code,2,1);
					$signe		=substr($fcontents[$i],   128+$j*20,   1);
					$valeur		=(double)substr($fcontents[$i],   129+$j*20,  15);
					if ($signe=='-')
						$valeur*=-1;
					$tabBilan['POSTES'].="$code=$valeur;";
					//$tabBilan['POSTES'][$code]=$valeur;
				}
			}
			$i++;
		}
		return $tabBilan;
	}

	private function partSaveSession() {
		$fp=fopen('/tmp/php_bil_session.id', 'w');
		fwrite($fp,$this->cookie.'^'.$this->timeOut.'^'.$this->url.'^'.$this->siren.'^'.$this->reference);
		fclose($fp);
	}

	private function partGetSession() {
		$strTmp=file_get_contents('/tmp/php_bil_session.id');
		$tabTmp=explode('^', $strTmp);
		$this->cookie=$tabTmp[0];
		$this->timeOut=$tabTmp[1];
		$this->url=$tabTmp[2];
		$this->siren=$tabTmp[3];
		$this->reference=$tabTmp[4];
	}

}

 ?>