array('min'=> 0, 'max' => 100), 'Conan & Holder' => array('min' => -4.5, 'max' => 16), 'Afdcc2' => array('min' => 0, 'max' => 5), 'Score Z' => array('min' => -3, 'max' => 3), 'CommonRisk' => array('min' => 0, 'max' => 20), 'ERC' => array('min' => -5, 'max' => 5) ); private $pdRating = array('AAA' => 9, 'AA' => 8, 'A' =>7, 'BBB' => 6, 'BB' => 5, 'B' => 4, 'CCC' => 3, 'CC' => 2, 'C' => 1, 'D' => 0); private $pathImg; public function __construct($report, $pathImg) { $this->pathImg = $pathImg; $this->report = $report; $this->formatDate(); $this->setNomberRecommendation(); foreach($this->report->DataSet->Company->CreditRecommendation as $credit) { //echo "
";print_r($credit->RiskClasses);exit;
		   $this->createGraphique($this->scores[$credit->RiskClasses->CommonRiskClass->RatingName->_]['min'], $this->scores[$credit->RiskClasses->CommonRiskClass->RatingName->_]['max'],
					$credit->RiskClasses->CommonRiskClass->RatingValue, str_replace(' ', '_',$credit->RiskClasses->CommonRiskClass->RatingName->_));
		   foreach ($credit->RiskClasses->ProviderRiskClass as $ProviderRiskClass) {
				$this->createGraphique($this->scores[$ProviderRiskClass->RatingName->_]['min'], $this->scores[$ProviderRiskClass->RatingName->_]['max'],
						$ProviderRiskClass->RatingValue, str_replace(' ', '_',$ProviderRiskClass->RatingName->_));
		   }
	   }
    }

    public function formatDate()
    {
       for($i = 0; $i < count($this->report->DataSet->Company->CreditRecommendation); $i++) {
           if (isset($this->report->DataSet->Company->CreditRecommendation[$i]->Date->_)) {
               $this->report->DataSet->Company->CreditRecommendation[$i]->Date->_ =
                   WDate::dateT(GiantFunction::getFormatDate($this->report->DataSet->Company->CreditRecommendation[$i]->Date->format),
                                'd/m/Y',
                                $this->report->DataSet->Company->CreditRecommendation[$i]->Date->_);
           }
       }
    }

    public function setNomberRecommendation()
    {
        for($i = 0; $i < count($this->report->DataSet->Company->CreditRecommendation); $i++) {
            if (isset($this->report->DataSet->Company->CreditRecommendation[$i]->AmountAdvised->_)) {
                $this->report->DataSet->Company->CreditRecommendation[$i]->AmountAdvised->_ =
                    number_format($this->report->DataSet->Company->CreditRecommendation[$i]->AmountAdvised->_, 0, '', ' ');
                    $this->report->DataSet->Company->CreditRecommendation[$i]->AmountAdvised->currency = GiantFunction::getPoundName(
                            $this->report->DataSet->Company->CreditRecommendation[$i]->AmountAdvised->currency);
            }
        }
    }

	public function createGraphique($min, $max, $current, $name)
	{
		if(!file_exists($this->pathImg.'-'.$name.'.png')) {
			$m = new LinearMeter(640, 10, 0xffffff);
			$m->setMeter(0, 0, 630, 10, Bottom);
			switch($name) {
				case 'IndiScore':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(9, 100, 0x21FF11, "");
					$m->addZone(5, 9, 0xFF8C19, "");
					$m->addZone(0, 5, 0xFF0004, "");
					break;
				case 'Conan_&_Holder':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(6.8, 16, 0x21FF11, "");
					$m->addZone(-4.5, 6.8, 0xFF0004, "");
					break;
				case 'Afdcc2':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(0.30, 5, 0x21FF11, "");
					$m->addZone(0, 0.30, 0xFF0004, "");
					break;
				case 'Score_Z':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(0, 3, 0x21FF11, "");
					$m->addZone(-3, 0, 0xFF0004, "");
					break;
				case 'CommonRisk':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(8, 20, 0x21FF11, "");
					$m->addZone(5, 8, 0xFF8C19, "");
					$m->addZone(0, 5, 0xFF0004, "");
					break;
				case 'ERC':
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(0, 5, 0x21FF11, "");
					$m->addZone(-2, 0, 0xFF8C19, "");
					$m->addZone(-5, -2, 0xFF0004, "");
					break;
				case 'PD_Rating':
					$current = $this->pdRating[$current];
					$m->setScale(0, 9);
					$m->addZone(6, 9, 0x21FF11, "");
					$m->addZone(2, 6, 0xFF8C19, "");
					$m->addZone(0, 2, 0xFF0004, "");
					break;
				case 'PD_Percentage':
					$current = (($current > 100)?100:$current);
					$current = (($current < 0)?0:$current);
					$current = 100 - $current;
					$m->setScale(0, 100);
					$m->addZone(60, 100, 0x21FF11, "");
					$m->addZone(30, 60, 0xFF8C19, "");
					$m->addZone(0, 30, 0xFF0004, "");
					break;
				case 'Common_Rating':
					if(empty($min)){$min = 0;}
					if(empty($max)){$max = 10;}
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(4, 10, 0x21FF11, "");
					$m->addZone(2, 4, 0xFF8C19, "");
					$m->addZone(0, 2, 0xFF0004, "");
					break;
				default:
					if(empty($min)){$min = 0;}
					if(empty($max)){$max = 100;}
					$current = (($current > $max)?$max:$current);
					$current = (($current < $min)?$min:$current);
					$m->setScale($min, $max);
					$m->addZone(50, 100, 0x21FF11, "");
					$m->addZone(0, 50, 0xFF0004, "");
			}
			$pointerObj = $m->addPointer($current, 0x000000);
			$m->makeChart($this->pathImg.'-'.$name.'.png');
		}
	}

    public function getDatas()
    {
        return ($this->report);
    }
}

class ComparaisonValeurs
{
	private $report;
	private $pathImg;

    public function __construct($report, $pathImg)
	{
		$this->pathImg = $pathImg;
		$this->report = $report;
		foreach($this->report->DataSet->Company->PeerGroup as $PeerGroup) {
			if(isset($PeerGroup->FlexibleComparisonItems)){
				$this->generateStructureRatio('FlexibleComparisonItems');
				$copy = $this->report->DataSet->Company->ComparaisonValeurs;
				foreach($copy as $name => $ComparaisonValeurs) {
					if(isset($ComparaisonValeurs['old'])) {
						foreach($ComparaisonValeurs['old'] as $date => $valeur) {
							$labels[] = $date;
							foreach($valeur as $val) {
								$entreprise[] = $val->SubjectValue;
								$secteur[] = $val->AverageValue;
							}
						}
						$entreprise = array_reverse($entreprise);
						$secteur = array_reverse($secteur);
						$labels = array_reverse($labels);
						$this->createGraphique($name, $labels, $entreprise, $secteur);
						unset($entreprise, $secteur, $labels);
					}
				}
			} else if($PeerGroup->AmountAdvisedComparison) {
				print_r($PeerGroup->AmountAdvisedComparison);
			} else if($PeerGroup->ProviderRatingComparison) {
				print_r($PeerGroup->ProviderRatingComparison);
			}
		}
		//exit;
	}

	public function generateStructureRatio($type)
	{
		$i = 0;
		foreach($this->report->DataSet->Company->PeerGroup as $PeerGroup) {
			switch($type) {
				case 'FlexibleComparisonItems':

						foreach($PeerGroup->FlexibleComparisonItems->ComparisonItemsGroup as $ComparisonItemsGroup) {
							foreach($ComparisonItemsGroup->FlexibleComparisonItem as $FlexibleComparisonItem) {
								$name = str_replace(' ', '_', str_replace('\'', '', $FlexibleComparisonItem->ItemName->_));
								if(!isset($this->report->DataSet->Company->ComparaisonValeurs[$name]['date'])) {
									$this->report->DataSet->Company->ComparaisonValeurs[$name]['date'] = WDate::dateT('Ymd', 'd/m/Y', $ComparisonItemsGroup->Period->EndDate->_);}
								if(!isset($this->report->DataSet->Company->ComparaisonValeurs[$name]['current'])){
									$this->report->DataSet->Company->ComparaisonValeurs[$name]['current'] = $FlexibleComparisonItem->SubjectValue;}
								if(!isset($this->report->DataSet->Company->ComparaisonValeurs[$name]['entreprise'])){
									$this->report->DataSet->Company->ComparaisonValeurs[$name]['entreprise'] = $FlexibleComparisonItem->AverageValue;}
								if(WDate::dateT('Ymd', 'd/m/Y', $ComparisonItemsGroup->Period->EndDate->_) != $this->report->DataSet->Company->ComparaisonValeurs[$name]['date']){
									$this->report->DataSet->Company->ComparaisonValeurs[$name]['old'][WDate::dateT('Ymd', 'd/m/Y', $ComparisonItemsGroup->Period->EndDate->_)][] = $FlexibleComparisonItem;}}}
					break;
				case 'AmountAdvisedComparison':
					foreach($PeerGroup->AmountAdvisedComparison as $AmountAdvisedComparison) {
						$std = new stdClass();
						$std->description = $AmountAdvisedComparison->Description->_;
						$std->ComparisonFigures = $AmountAdvisedComparison->ComparisonFigures;
						$this->report->DataSet->Company->AmountAdvisedComparison = $std;
					}
					break;
				case 'ProviderRatingComparison':
					foreach($PeerGroup->AmountAdvisedComparison as $ProviderRatingComparison) {

					}
					break;
			}
		}
	}

	public function createGraphique($name, $labels, $entreprise, $secteur)
	{
		if(!file_exists($this->pathImg.'-'.$name.'.png')) {
			$c = new XYChart(400, 170);
			$c->setPlotArea(50, 20, 300, 120);

			$legendObj = $c->addLegend(110, -5, false, "arialbd.ttf", 9);
			$legendObj->setBackground(Transparent);

			$layer = $c->addLineLayer2();
			$layer->setLineWidth(1);
			$layer->addDataSet($entreprise, 0xFF0004, 'Entreprise');
			$layer->addDataSet($secteur, 0x2E00FF, 'Secteur');

			$c->xAxis->setLabels($labels);
			$c->xAxis->setLabelStep(1);
			$c->makeChart($this->pathImg.'-'.$name.'.png');
		}
	}

	public function getDatas()
	{
		return ($this->report);
	}
}

class ComportementPaiement
{
    private $report;
	private $pathImg;

    public function __construct($report, $pathImg)
    {
        $this->report = $report;
		$this->pathImg = $pathImg;
        $this->generateStructure();
        $this->createGraphique('ComportementPaiement');
        $this->createGraphiqueByAmount('ComportementPaiementByAmount');
    }

    public function generateStructure()
    {
		if(isset($this->report->DataSet->Company->PaymentBehaviour)) {
			foreach($this->report->DataSet->Company->PaymentBehaviour as $PaymentBehaviour) {
				if(isset($PaymentBehaviour->AnalysisByPeriod->Category)) {
					foreach($PaymentBehaviour->AnalysisByPeriod->Category as $period) {
						foreach($period->DueDateExceeds as $DueDateExceeds) {
							$this->report->DataSet->Company->
								   ComportementPaiement[WDate::dateT('Ymd', 'd/m/Y', $period->Period->StartDate->_).':'.WDate::dateT('Ymd', 'd/m/Y', $period->Period->EndDate->_)][$DueDateExceeds->NrOfDaysExceeds->LowerLimit->_.':'.$DueDateExceeds->NrOfDaysExceeds->UpperLimit->_] =
									$DueDateExceeds->Percentage;
						}
					}
				}
				if(isset($PaymentBehaviour->AnalysisByAmount->Category)) {
					foreach($PaymentBehaviour->AnalysisByAmount->Category as $Amount) {
						foreach($Amount->DueDateExceeds as $AmountExceeds) {
							$index = ((isset($Amount->AmountCategory->LowerLimit->_))?$Amount->AmountCategory->LowerLimit->_:'0').
									':'.(isset($Amount->AmountCategory->HigherLimit->_)?$Amount->AmountCategory->HigherLimit->_:'0');
							$this->report->DataSet->Company->ByAmount[$index][$AmountExceeds->NrOfDaysExceeds->LowerLimit->_.':'.$AmountExceeds->NrOfDaysExceeds->UpperLimit->_] = $AmountExceeds->Percentage;
						}
					}
				}
			}
		}
		return (false);
    }


    public function createGraphique($nameImg)
    {
		if(!file_exists($this->pathImg.'-'.$nameImg.'.png')) {
			# The data for the chart
			if(isset($this->report->DataSet->Company->ComportementPaiement)) {
				foreach($this->report->DataSet->Company->ComportementPaiement as $date => $ComportementPaiement) {
					$date = explode(':', $date);
					$dates = explode('/', $date[1]);
					$labels[] = $dates[1].'/'.$dates[2];
					foreach($ComportementPaiement as $name => $element) {
						if(max($ComportementPaiement) == $element) {
							$name = explode(':', $name);
							$datas[] = $name[0];
						}
					}
				}
				$data = array_reverse($datas);
				$labels = array_reverse($labels);
				$c = new XYChart(600, 300, 0xffffc0, 0x000000, 1);
				$c->setSearchPath(dirname(__FILE__));
				$plotAreaObj = $c->setPlotArea(95, 50, 420, 205, 0xffffff);
				$plotAreaObj->setGridColor(0xc0c0c0, 0xc0c0c0);
				$legendBox = $c->addLegend(55, 25, false, "", 8);
				$legendBox->setBackground(Transparent);
				$legendBox->addKey("Normal", 0x8033ff33);
				$legendBox->addKey("Attention", 0x80ff8f0f);
				$legendBox->addKey("Critique", 0x80ff3333);
				$textBoxObj = $c->addTitle(
					"<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Jours ".
					"<*img=star.png*><*img=star.png*><*/*>", "arialbi.ttf", 13, 0xffffff);
				$textBoxObj->setBackground(0x000000, -1, 1);
				$c->yAxis->setTitle("Jours");
				$c->xAxis->setLabels($labels);
				$c->xAxis->setLabelStep(1);
				$c->xAxis->setTitle(
					"<*block,valign=absmiddle*><*img=clock.png*>  Dates<*/*>");
				$c->xAxis->setWidth(2);
				$c->yAxis->setWidth(2);
				$markObj = $c->yAxis->addMark(30, 0x80ff8f0f, "Attention = 30");
				$markObj->setLineWidth(1);
				$markObj = $c->yAxis->addMark(60, 0x80ff3333, "Critique = 60");
				$markObj->setLineWidth(1);
				$c->addAreaLayer($data, $c->yZoneColor(30, 0x8033ff33, 0x80ff8f0f));
				$c->addAreaLayer($data, $c->yZoneColor(60, 0x80ff8f0f, 0x80ff3333));
				$textBoxObj = $c->addText(475, 255,
					"<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*>".
					"<*font=timesbi.ttf,size=10,color=804040*>Scores et decisions<*/*>");
				$textBoxObj->setAlignment(BottomRight);
				$c->makeChart($this->pathImg.'-'.$nameImg.'.png');
			}
		}
    }

    public function createGraphiqueByAmount($nameImg)
    {
		if(!file_exists($this->pathImg.'-'.$nameImg.'.png')) {
			if(isset($this->report->DataSet->Company->ByAmount)) {
				foreach($this->report->DataSet->Company->ByAmount as $sommes => $ByAmount) {
					$somme = explode(':', $sommes);
					$labels[] = round($somme[0]/1000).'-'.round($somme[1]/1000).'K€';
					foreach($ByAmount as $name => $element) {
						if(max($ByAmount) == $element) {
							$name = explode(':', $name);
							$data[] = $name[0];
							break;
						}
					}
				}
				$colors = array(0xcc0000, 0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff);
				$c = new XYChart(600, 340);
				$c->setColors($whiteOnBlackPalette);
				$c->setBackground(0xffffff);
				$c->setPlotArea(70, 50, 480, 240, -1, -1, Transparent, 0xe2e2e2);
				$c->swapXY();
				$barLayerObj = $c->addBarLayer3($data, $colors);
				$barLayerObj->setBorderColor(Transparent, barLighting(0.75, 2.0));
				$c->xAxis->setLabels($labels);
				$c->syncYAxis();
				$c->yAxis->setTitle("Jours", "arialbd.ttf", 10);
				$c->yAxis->setColors(Transparent);
				$c->yAxis2->setColors(Transparent);
				$c->xAxis->setTickColor(Transparent);
				$c->xAxis->setLabelStyle("arialbd.ttf", 8);
				$c->yAxis->setLabelStyle("arialbd.ttf", 8);
				$c->yAxis2->setLabelStyle("arialbd.ttf", 8);
				$c->makeChart($this->pathImg.'-'.$nameImg.'.png');
			}
		}
    }

    public function getDatas()
    {
        return ($this->report);
    }
}

class ComptesAnnuels
{

    private $report;
	private $pathImg;

    public function  __construct($report, $pathImg)
    {
		$this->pathImg = $pathImg;
        $this->report = $report;
        $this->formatDate($report);
        $this->report->DataSet->Company->Assets->TotalAssets = $this->bilans('Assets', 'TotalAssets');
        $this->report->DataSet->Company->Assets->TotalFixedAssets = $this->bilans('Assets', 'FixedAssets:TotalFixedAssets', true);
		$this->report->DataSet->Company->Assets->FixedAssets = $this->bilans('Assets', 'FixedAssets:TotalIntangibleAssets', true);
        $this->report->DataSet->Company->Assets->TotalIntangibleAssets = $this->bilans('Assets', 'FixedAssets:TotalTangibleAssets', true);
        $this->report->DataSet->Company->Assets->TotalFinancialAssets = $this->bilans('Assets', 'FixedAssets:TotalFinancialAssets', true);
        $this->report->DataSet->Company->Assets->RawMaterialsAndSupplies = $this->bilans('Assets', 'CurrentAssets:RawMaterialsAndSupplies', true);
        $this->report->DataSet->Company->Assets->Inventories = $this->bilans('Assets', 'CurrentAssets:Inventories', true);
        $this->report->DataSet->Company->Assets->TotalReceivables = $this->bilans('Assets', 'CurrentAssets:TotalReceivables', true);
        $this->report->DataSet->Company->Assets->CashBankSecurities = $this->bilans('Assets', 'CurrentAssets:CashBankSecurities', true);
        $this->report->DataSet->Company->Assets->OtherCurrentAssets = $this->bilans('Assets', 'CurrentAssets:OtherCurrentAssets', true);
        $this->report->DataSet->Company->Assets->TotalCurrentAssets = $this->bilans('Assets', 'CurrentAssets:TotalCurrentAssets', true);

        $this->report->DataSet->Company->Liabilities->TotalLiabilities = $this->bilans('Liabilities', 'TotalLiabilities');
        $this->report->DataSet->Company->Liabilities->TotalEquity = $this->bilans('Liabilities', 'ShareholdersFunds:TotalEquity', true);
        $this->report->DataSet->Company->Liabilities->EquityCapital = $this->bilans('Liabilities', 'ShareholdersFunds:EquityCapital', true);
        $this->report->DataSet->Company->Liabilities->SurplusEquity = $this->bilans('Liabilities', 'ShareholdersFunds:SurplusEquity', true);
        $this->report->DataSet->Company->Liabilities->ProfitAndLossAccount = $this->bilans('Liabilities', 'ShareholdersFunds:ProfitAndLossAccount', true);
        $this->report->DataSet->Company->Liabilities->LongTermDeferredTaxes = $this->bilans('Liabilities', 'LongTermLiabilities:LongTermDeferredTaxes', true);
        $this->report->DataSet->Company->Liabilities->AccumulatedDepreciation = $this->bilans('Liabilities', 'LongTermLiabilities:AccumulatedDepreciation', true);
        $this->report->DataSet->Company->Liabilities->OtherLongTermLiabilities = $this->bilans('Liabilities', 'LongTermLiabilities:OtherLongTermLiabilities', true);
        $this->report->DataSet->Company->Liabilities->TotalLongTermLiabilities = $this->bilans('Liabilities', 'LongTermLiabilities:TotalLongTermLiabilities', true);
        $this->report->DataSet->Company->Liabilities->TradeCreditors = $this->bilans('Liabilities', 'CurrentLiabilities:TradeCreditors', true);
        $this->report->DataSet->Company->Liabilities->DueToBanks = $this->bilans('Liabilities', 'CurrentLiabilities:DueToBanks', true);
        $this->report->DataSet->Company->Liabilities->ShortTermLiabilities = $this->bilans('Liabilities', 'CurrentLiabilities:ShortTermLiabilities', true);
        $this->report->DataSet->Company->Liabilities->Provisions = $this->bilans('Liabilities', 'CurrentLiabilities:Provisions', true);
        $this->report->DataSet->Company->Liabilities->OtherShortTermLiabilities = $this->bilans('Liabilities', 'CurrentLiabilities:OtherShortTermLiabilities', true);
        $this->report->DataSet->Company->Liabilities->TotalShortTermLiabilities = $this->bilans('Liabilities', 'Other:WorkingCapital', true);

        $this->report->DataSet->Company->ProfitAndLoss->NetSales = $this->bilans('ProfitAndLoss', 'NetSales', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->NetIncomeLossOfTheYear = $this->bilans('ProfitAndLoss', 'NetIncomeLossOfTheYear', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->GrossProfit = $this->bilans('ProfitAndLoss', 'GrossProfit', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->OperatingResult = $this->bilans('ProfitAndLoss', 'OperatingResult', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->ResultsOfOrdinaryOperations = $this->bilans('ProfitAndLoss', 'ResultsOfOrdinaryOperations', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->NetProfitBeforeTaxes = $this->bilans('ProfitAndLoss', 'NetProfitBeforeTaxes', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->FinancialCharges = $this->bilans('ProfitAndLoss', 'FinancialCharges', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->Depreciation = $this->bilans('ProfitAndLoss', 'Depreciation', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->Purchases = $this->bilans('ProfitAndLoss', 'Purchases', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->WagesAndSalaries = $this->bilans('ProfitAndLoss', 'WagesAndSalaries', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->FinancialIncome = $this->bilans('ProfitAndLoss', 'FinancialIncome', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->Tax = $this->bilans('ProfitAndLoss', 'Tax', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->ExtraordinaryItems = $this->bilans('ProfitAndLoss', 'ExtraordinaryItems', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->NetSales = $this->bilans('ProfitAndLoss', 'NetSales', false, 'ProfitAndLoss');
        $this->report->DataSet->Company->ProfitAndLoss->NetSales = $this->bilans('ProfitAndLoss', 'NetSales', false, 'ProfitAndLoss');

        $this->report->DataSet->Company->KeyCreditRatios->Leverage = $this->bilans('KeyCreditRatios', 'Leverage', false, 'KeyCreditRatios');
        $this->report->DataSet->Company->KeyCreditRatios->QuickRatio = $this->bilans('KeyCreditRatios', 'QuickRatio', false, 'KeyCreditRatios');
        $this->report->DataSet->Company->KeyCreditRatios->CurrentRatio = $this->bilans('KeyCreditRatios', 'CurrentRatio', false, 'KeyCreditRatios');
        $this->report->DataSet->Company->KeyCreditRatios->InterestCover = $this->bilans('KeyCreditRatios', 'InterestCover', false, 'KeyCreditRatios');
        $this->report->DataSet->Company->KeyCreditRatios->Gearing = $this->bilans('KeyCreditRatios', 'Gearing', false, 'KeyCreditRatios');
        $this->generateDatasForGraphique($this->report);
    }

	public function createGraphiqueLine($name, $datas)
	{
		if(!file_exists($this->pathImg.'-'.$name.'-line.png')) {
			foreach($datas as $date => $valeur) {
				$labels[] = $date;
				$data[] = $valeur;
			}
			if(!empty($data))
				$data = array_reverse($datas);
			if(!empty($labels))
				$labels = array_reverse($labels);
			$c = new XYChart(400, 170);
			$c->setPlotArea(50, 20, 300, 120);

			$legendObj = $c->addLegend(110, -5, false, "arialbd.ttf", 9);
			$legendObj->setBackground(Transparent);

			$layer = $c->addLineLayer2();
			$layer->setLineWidth(1);
			$layer->addDataSet($data, 0xFF0004, 'Valeurs');
			$c->xAxis->setLabels($labels);
			$c->xAxis->setLabelStep(1);
			$c->makeChart($this->pathImg.'-'.str_replace(' ', '', $name).'-line.png');
		}
	}

    public function createBilanGraphique($name, $datas, $labels, $width = 590, $height = 270)
    {
        if(!file_exists($this->pathImg.'-'.$name.'.png')) {
            $c = new PieChart($width, $height);
            $c->setPieSize(150, 135, 100);
            $c->addLegend(340, 60);
            $c->setLabelFormat("{percent}%");
            $c->setData($datas, $labels);
            $c->setSectorStyle(RoundedEdgeShading, 0xffffff, 1);
            $c->makeChart($this->pathImg.'-'.$name.'.png');
        }
    }

    public function generateDatasForGraphique($result)
    {
        $parametres       = new stdClass();
        $actifLabel = array('FixedAssets', 'TotalIntangibleAssets', 'TotalFinancialAssets', 'RawMaterialsAndSupplies', 'Inventories', 'CashBankSecurities', 'OtherCurrentAssets');
        $actifDatas = array(
            $result->DataSet->Company->Assets->FixedAssets[key($result->DataSet->Company->Assets->FixedAssets)],
            $result->DataSet->Company->Assets->TotalIntangibleAssets[key($result->DataSet->Company->Assets->TotalIntangibleAssets)],
            $result->DataSet->Company->Assets->TotalFinancialAssets[key($result->DataSet->Company->Assets->TotalFinancialAssets)],
            $result->DataSet->Company->Assets->RawMaterialsAndSupplies[key($result->DataSet->Company->Assets->RawMaterialsAndSupplies)],
            $result->DataSet->Company->Assets->Inventories[key($result->DataSet->Company->Assets->Inventories)],
            $result->DataSet->Company->Assets->CashBankSecurities[key($result->DataSet->Company->Assets->CashBankSecurities)],
            $result->DataSet->Company->Assets->OtherCurrentAssets[key($result->DataSet->Company->Assets->OtherCurrentAssets)]
        );

        $passifLabel = array('EquityCapital', 'SurplusEquity', 'ProfitAndLossAccount', 'LongTermDeferredTaxes', 'AccumulatedDepreciation', 'OtherLongTermLiabilities',
                             'TotalLongTermLiabilities', 'TradeCreditors', 'DueToBanks', 'ShortTermLiabilities', 'Provisions', 'OtherShortTermLiabilities', 'TotalShortTermLiabilities');
        $passifDatas = array(
            $result->DataSet->Company->Liabilities->EquityCapital[key($result->DataSet->Company->Liabilities->EquityCapital)],
            $result->DataSet->Company->Liabilities->SurplusEquity[key($result->DataSet->Company->Liabilities->SurplusEquity)],
            $result->DataSet->Company->Liabilities->ProfitAndLossAccount[key($result->DataSet->Company->Liabilities->ProfitAndLossAccount)],
            $result->DataSet->Company->Liabilities->LongTermDeferredTaxes[key($result->DataSet->Company->Liabilities->LongTermDeferredTaxes)],
            $result->DataSet->Company->Liabilities->AccumulatedDepreciation[key($result->DataSet->Company->Liabilities->AccumulatedDepreciation)],
            $result->DataSet->Company->Liabilities->OtherLongTermLiabilities[key($result->DataSet->Company->Liabilities->OtherLongTermLiabilities)],
            $result->DataSet->Company->Liabilities->TotalLongTermLiabilities[key($result->DataSet->Company->Liabilities->TotalLongTermLiabilities)],
            $result->DataSet->Company->Liabilities->TradeCreditors[key($result->DataSet->Company->Liabilities->TradeCreditors)],
            $result->DataSet->Company->Liabilities->DueToBanks[key($result->DataSet->Company->Liabilities->DueToBanks)],
            $result->DataSet->Company->Liabilities->ShortTermLiabilities[key($result->DataSet->Company->Liabilities->ShortTermLiabilities)],
            $result->DataSet->Company->Liabilities->Provisions[key($result->DataSet->Company->Liabilities->Provisions)],
            $result->DataSet->Company->Liabilities->OtherShortTermLiabilities[key($result->DataSet->Company->Liabilities->OtherShortTermLiabilities)],
            $result->DataSet->Company->Liabilities->TotalShortTermLiabilities[key($result->DataSet->Company->Liabilities->TotalShortTermLiabilities)]
        );

        $profitandlossLabel = array('NetSales', 'NetIncomeLossOfTheYear', 'GrossProfit', 'OperatingResult', 'ResultsOfOrdinaryOperations', 'NetProfitBeforeTaxes',
                             'FinancialCharges', 'Depreciation', 'Purchases', 'WagesAndSalaries', 'FinancialIncome', 'Tax', 'ExtraordinaryItems');
        $lossDatas = array('NetSales', 'NetIncomeLossOfTheYear', 'GrossProfit', 'OperatingResult', 'ResultsOfOrdinaryOperations', 'NetProfitBeforeTaxes',
									 'FinancialCharges', 'Depreciation', 'Purchases', 'WagesAndSalaries', 'FinancialIncome', 'Tax', 'ExtraordinaryItems');
		foreach($lossDatas as $profitandlossData) {
			if(isset($result->DataSet->Company->ProfitAndLoss->$profitandlossData))
				$Datas[] = $result->DataSet->Company->ProfitAndLoss->{$profitandlossData}[key($result->DataSet->Company->ProfitAndLoss->$profitandlossData)];
			else
				$Datas[] = 0;
		}
		$profitandlossDatas = $Datas;
        $this->createBilanGraphique('actifs', $actifDatas, $actifLabel);
        $this->createBilanGraphique('passifs', $passifDatas, $passifLabel, 590, 310);
        $this->createBilanGraphique('profitandloss', $profitandlossDatas, $profitandlossLabel, 590, 310);
    }

    public function bilans($type, $name, $lvl = false, $BalanceSheet = 'BalanceSheet')
    {
       if($lvl){$explode = explode(':', $name);$name=$explode[0];}
       foreach($this->report->DataSet->Company->AnnualAccounts as $AnnualAccounts) {
           foreach($AnnualAccounts->HarmonizedAnnualAccounts->{$BalanceSheet} as $bilan => $HarmonizedAnnualAccounts) {
               if ($BalanceSheet == 'BalanceSheet') {
                   if ($bilan == $type) {
                      foreach($HarmonizedAnnualAccounts as $element => $valeur) {
                          if ($element == $name) {
                              ($lvl)?$bilans[$AnnualAccounts->AccountsDate->_] =
                                      $valeur->$explode[1]->_/1000:
                                      $bilans[$AnnualAccounts->AccountsDate->_] = $valeur->_/1000; } } }
               } else {
                   if($bilan == $name) {
                       (!$BalanceSheet == 'KeyCreditRatios')?$div=1000:$div=1;
                       $bilans[$AnnualAccounts->AccountsDate->_] = $HarmonizedAnnualAccounts->_/$div; } } } }
		$name = ($lvl)?$explode[1]:$name;
		$this->createGraphiqueLine($name, $bilans);
		return $bilans;
    }

    public function formatDate($report)
    {
        for ($i = 0; $i < count($this->report->DataSet->Company->AnnualAccounts); $i++) {
            if(isset($this->report->DataSet->Company->AnnualAccounts[$i]->AccountsDate->_)) {
                $this->report->DataSet->Company->AnnualAccounts[$i]->AccountsDate->_ = WDate::dateT(
                    GiantFunction::getFormatDate($this->report->DataSet->Company->AnnualAccounts[$i]->AccountsDate->format), 'd/m/Y',
                    $this->report->DataSet->Company->AnnualAccounts[$i]->AccountsDate->_);
            }
        }
    }

    public function getDatas()
    {
        return ($this->report);
    }
}

class Dirigeant {

	private $report;

	public function  __construct($report, $pathImg)
	{
		$this->report = $report;
		$this->generateStructure();
	}

	public function generateStructure()
	{
		foreach($this->report->DataSet->Company->Position as $Position) {
			$this->report->DataSet->Company->Dirigeant[$Position->PositionTitle->code][WDate::dateT('Ymd', 'd/m/Y', $Position->Period->StartDate->_).':'.WDate::dateT('Ymd', 'd/m/Y',$Position->Period->EndDate->_)][] = $Position->Person;
		}
	}

	public function getDatas()
	{
		return ($this->report);
	}
}

class Historiques
{
	private $report;

	public function __construct($report, $pathImg)
	{
		$this->report = $report;
		if(isset($this->report->DataSet->Company->Event))
			$this->generateStructure();
	}

	public function generateStructure()
	{
		$myEvent = array();
		foreach($this->report->DataSet->Company->Event as $events) {
			$std = new stdClass();
			$std->EventCode = $events->EventCode;
			$std->Description = $events->Description->_;
			$std->FreeText = $events->FreeText->_;
			$std->Date = GiantFunction::setDate($events->Date->_, $events->Date->format);
			$std->Format = $events->Date->format;
			$myEvent[$events->Source->_][$events->Date->_][] = $std;
			unset ($std);
		}
		$this->report->DataSet->Company->Event = $myEvent;
		foreach($this->report->DataSet->Company->Event as $name => $event) {
				ksort($this->report->DataSet->Company->Event[$name]);
				$this->report->DataSet->Company->Event[$name] = array_reverse($this->report->DataSet->Company->Event[$name], true);
		}
	}

	public function getDatas()
	{
		return ($this->report);
	}
}

class InformationGenerale
{
    private $report;
    private $block = array('block1' => array('CompanyName', 'Vat',
                              'LegalForm', 'IncorporationDate',
                              'CompanyStatus', 'CompanyId'
    ),
                            'block2' => array('TelephoneNumber', 'Telefax',
                            'EmailAddress', 'WebAddress',
                            'Address'
    ));

    public function  __construct($report, $pathImg)
    {
        if(isset($report)) {
            $this->report                    = $report->DataSet->Company;
            $this->report->Vat               = $this->report->Vat->VatNumber;
            $this->report->CompanyName       = $this->report->CompanyName[0]->_;
            $this->report->CompanyAddress    = $this->report->CompanyAddress[0]->HouseNumber.' '.$this->report->CompanyAddress[0]->Street.' - '.$this->report->CompanyAddress[0]->PostCode.' '.$this->report->CompanyAddress[0]->City;
            $this->report->TelephoneNumber   = $this->report->TelephoneNumber[0]->_;
            $this->report->Telefax           = $this->report->Telefax[0];
            $this->report->IncorporationDate = GiantFunction::setDate($this->report->IncorporationDate->_, $this->report->IncorporationDate->format);
            $this->report->UnifiedLegalForm  = $this->report->LegalForm[0]->UnifiedLegalForm;
            $this->report->LegalForm         = $this->report->LegalForm[0]->CountryLegalForm->_;
            $this->report->WebAddress        = ''.$this->report->WebAddress.'';
            $this->report->EmailAddress      = ''.$this->report->EmailAddress.'';
            $this->report->activity          = $this->getActivity($this->report->Operations);
            $this->report->Employees         = $this->getEmployees($this->report->Employees);
            $this->report->ProductName       = $this->report->Operations->ProductName;
            //$this->report->ValideNumber    = GiantFunction::checkVat(substr($this->report->Vat, 2), $request->getParam('Pays'));
            $this->generateStructur();
        }
    }

    public function getEmployees($Employees)
    {
        $employees = array();
		if(isset($Employees)) {
			foreach($Employees as $employed) {
				$employees[$employed->Period->StartDate->_] =
							array('TotalStaffEmployed' => (empty($employed->TotalStaffEmployed))?'NC':$employed->TotalStaffEmployed,
																	'FulltimeEquivalent' => (empty($employed->FulltimeEquivalent))?'NC':$employed->FulltimeEquivalent);
			}
			return ($employees);
		}
    }

    public function getActivity($Operations)
    {
        $activity = array();
        if(isset($Operations->IndustryCode)) {
            foreach($Operations->IndustryCode as $operation) {
                $activity = array_merge(
                            array((empty($operation->NaceCode))?'NC':' '.$operation->NaceCode => (empty($operation->Description->_))?'NC':$operation->Description->_), $activity);
            }
        }
        return ($activity);
    }

    public function generateStructur()
    {
        foreach($this->block as $elements) {
            foreach($elements as $element) {
                if(empty ($this->report->$element))
                    $this->report->$element = 'N/C';
            }
        }
    }

    public function getDatas()
    {
        return ($this->report);
    }

}

class PositionFinanciere
{
    private $report;
	private $labelDate = array();
    private $color = array(0x808080ff, 0x80ff0000, 0x8000ff00, 0x80FF16EB, 0x801900FF, 0x80EEFF02, 0x8033D6C8);
	private $pathImg;

    public function  __construct($report, $pathImg)
    {
		$this->pathImg = $pathImg;
        $this->report = $report;
        $this->generateStructure();
        $this->createGraphique();
    }

    public function createGraphique()
    {
		if(!file_exists($this->pathImg.'-positionFinanciere.png')) {
			# The data for the area chart
			foreach($this->report->DataSet->Company->PositionFinanciere as $name => $element) {
				if($name == 'AuthorizedCapital' or $name == 'IssuedCapital' or $name == 'WorkingCapital') {
					foreach($element as $item) {
						$data[$name][] = ($item < 0)?0:$item;
					}
				}
			}
			foreach($this->labelDate as $date => $val) {
				$labels[] = $date;
			}
			$labels = array_reverse($labels);
			$c = new XYChart(500, 270);
			$c->setPlotArea(70, 70, 350, 150);
			$legendObj = $c->addLegend(55, 0, false, "", 8);
			$legendObj->setBackground(Transparent);
			$c->xAxis->setTitle("Années");
			$c->yAxis->setTitle("Euros");
			$c->xAxis->setLabels($labels);
			//$c->xAxis->setLabelStep(2, 1);
			foreach($data as $name => $val) {
				$val = array_reverse($val);
				$key = array_rand($this->color);
				$c->addAreaLayer($val, $this->color[$key], $name, 3);
			}
			$c->makeChart($this->pathImg.'-positionFinanciere.png');
		}
    }

    public function generateStructure()
    {
        foreach($this->report->DataSet->Company->FinancialSummary as $FinancialSummary) {
            foreach($FinancialSummary as $name => $valeur) {
                if($name != 'SummaryDate' and $name != 'AccountStatus' and $name != 'Unit') {
					(($FinancialSummary->Unit == 1)?$unit=1000:$unit=1);
					$date = (strlen($FinancialSummary->SummaryDate->_) == 8 )?WDate::dateT('Ymd', 'd/m/Y', $FinancialSummary->SummaryDate->_):$FinancialSummary->SummaryDate->_;
                    $return[$name][$date] = number_format ($valeur->_/$unit, 0, '', ' ').(($unit==1000)?' K€':' €');
					$this->labelDate[$date] = true;
				}
            }
        }
		$this->report->DataSet->Company->PositionFinanciereDate = $this->labelDate;
        $this->report->DataSet->Company->PositionFinanciere = $return;
    }

    public function getDatas()
    {
        return ($this->report);
    }
}

class StructureEntreprise
{
    private $report;

    public function  __construct($report, $pathImg)
    {
        $this->report = $report;
        $this->generatestructure();
    }

    public function generatestructure()
    {
        foreach($this->report->DataSet->Company->Associated as $Associated) {
            if($Associated->RelationShip == 'Shareholder' ) {
                $this->report->DataSet->Company->Shareholder[] = $Associated;
            }
            if($Associated->RelationShip == 'Participation') {
                $this->report->DataSet->Company->Participation[] = $Associated;
            }
        }
    }

    public function getDatas()
    {
        return ($this->report);
    }
}
?>