<?php
// --------------------------------------------------------------------------- //
// giant_rapport.php
// --------------------------------------------------------------------------- //
$commande_id = $_GET['OrderId'];

abstract class AccountItem { }
class AmountAccountItem extends AccountItem { }
class AccountItemGroup  extends AccountItem { }
class AmountType { }

// --------------------------------------------------------------------------- //
// dRow
// --------------------------------------------------------------------------- //
function dRow($lib, $data, $title = '')
{
    $html  = '<tr>'."\n";
    $html .= '  <td width="30">&nbsp;</td>'."\n";
    $html .= '  <td width="200" class="StyleInfoLib">'.$lib.'</td>'."\n";

    if ($title != '') {
        $title  = ' title="'.$title.'"';
    }
    $html .= '  <td width="350" class="StyleInfoData"'.
        $title.'>'.$data.'</td>'."\n";
    $html .= '</tr>'."\n";
    print $html;
}

// --------------------------------------------------------------------------- //
// dRow2
// --------------------------------------------------------------------------- //
function dRow2($lib, $data, $id)
{
    $html  = '<tr>'."\n";
    $html .= '  <td width="30">&nbsp;</td>'."\n";
    $html .= '  <td width="100" class="StyleInfoLib" >'.$lib .'</td>'."\n";
    $html .= '  <td width="350" class="StyleInfoData">'.$data.'</td>'."\n";
    $html .= '  <td width="100" class="StyleInfoData">'.$id  .'</td>'."\n";
    $html .= '</tr>'."\n";
    print $html;
}

// --------------------------------------------------------------------------- //
// getArray
// --------------------------------------------------------------------------- //
function getArray($obj)
{
    if (is_array($obj) == false) {
        return array($obj);
    } else {
        return $obj;
    }
}

// --------------------------------------------------------------------------- //
// printObj
// --------------------------------------------------------------------------- //
function printObj($obj)
{
    $ret = '';
    foreach ($obj as $val) {
        if (is_object($val) == true) {
            $ret .= printObj($val);
        } else if ($val == 'OldValue' ||
                   $val == 'NewValue') {
            $ret .= '('.$val.') ';
        } else if ($val != 'eq') {
            $ret .= $val.' ';
        }
    }
    return $ret;
}

// --------------------------------------------------------------------------- //
// cmp
// --------------------------------------------------------------------------- //
function cmp($a, $b)
{
    if ($a->Date->_ == $b->Date->_) {
        return 0;
    }
    return ($a->Date->_ < $b->Date->_) ? 1 : -1;
}

// --------------------------------------------------------------------------- //
// pdate
// --------------------------------------------------------------------------- //
function pdate($d)
{
    if (isset($d->format) == false) {
        if (isset($d->_) == true) {
            return $d->_;
        } else {
            return $d;
        }
    }
    $f = substr($d->format, 0, 1);
    $date = '';
    for ($i = 0; $i < strlen($d->format); ++$i) {
        if (substr($d->format, $i, 1) != $f) {
            $f = substr($d->format, $i, 1);
            $date .= ' / ';
        }
        $date .= substr($d->_, $i, 1);
    }
    return $date;
}

// --------------------------------------------------------------------------- //
// arrayInsert
// --------------------------------------------------------------------------- //
function arrayInsert($array, $pos, $value)
{
  return array_merge(array_slice($array, 0 , $pos),
                     array($value),
                     array_slice($array,  $pos));
}

// --------------------------------------------------------------------------- //
// fillAccountItem
// --------------------------------------------------------------------------- //
function fillAccountItem(&$tab, &$num, $item, $year, $level = 0, $desPrec = '')
{
    if (isset($item->AccountItem)      == true ||
        isset($item->GroupTotalAmount) == true) {
        if (isset($item->AccountItem)  == true) {
            foreach (getArray($item->AccountItem) as $it) {
                if (isset($item->Description->_) == true) {
                    fillAccountItem($tab, $num, $it, $year,
                                    $level + 1, $desPrec.$item->Description->_);
                } else {
                    fillAccountItem($tab, $num, $it, $year,
                                    $level + 1, $desPrec);
                }
            }
        }
        if (isset($item->GroupTotalAmount) == true) {
            if (isset($tab[$num]) == true) {
                for ($i = $num; $i < count($tab); ++$i) {
                    if (isset($item->Description->code) == true) {
                        $code = $item->Description->code;
                    } else {
                        $code = $desPrec.$item->Description->_;
                    }
                    if ($tab[$i]->cde == $code) {
                        $num = $i;
                        $tab[$num]->val[$year] = $item->GroupTotalAmount->_;
                        return;
                    }
                }
                $obj             = new StdClass;
                $obj->des        = $item->Description->_;
                $obj->val[$year] = $item->GroupTotalAmount->_;
                if (isset($item->Description->code) == true) {
                    $obj->cde        = $item->Description->code;
                } else {
                    $obj->cde        = $desPrec.$item->Description->_;
                }
                $obj->niv        = $level;
                $tab = arrayInsert($tab, $num, $obj);
            } else {
                $obj             = new StdClass;
                $obj->des        = $item->Description->_;
                $obj->val[$year] = $item->GroupTotalAmount->_;
                if (isset($item->Description->code) == true) {
                    $obj->cde        = $item->Description->code;
                } else {
                    $obj->cde        = $desPrec.$item->Description->_;
                }
                $obj->niv        = $level;
                $tab[$num]       = $obj;
            }
            ++$num;
        }
    } else {
        if (isset($tab[$num]) == true) {
            for ($i = 0; $i < count($tab); ++$i) {
                if (isset($item->Description->code) == true) {
                    $code = $item->Description->code;
                } else {
                    $code = $desPrec.$item->Description->_;
                }
                if ($tab[$i]->cde == $code) {
                    $num = $i;
                    $tab[$num]->val[$year] = $item->Value->_;
                    return;
                }
            }
            $obj             = new StdClass;
            $obj->des        = $item->Description->_;
            $obj->val[$year] = $item->Value->_;
            if (isset($item->Description->code) == true) {
                $obj->cde        = $item->Description->code;
            } else {
                $obj->cde        = $desPrec.$item->Description->_;
            }
            $obj->niv        = $level;
            $tab = arrayInsert($tab, $num, $obj);
        } else {
            $obj             = new StdClass;
            $obj->des        = $item->Description->_;
            $obj->val[$year] = $item->Value->_;
            if (isset($item->Description->code) == true) {
                $obj->cde        = $item->Description->code;
            } else {
                $obj->cde        = $desPrec.$item->Description->_;
            }
            $obj->niv        = $level;
            $tab[$num]       = $obj;
        }
        ++$num;
    }
}

// --------------------------------------------------------------------------- //
// printAccountItem
// --------------------------------------------------------------------------- //
function printAccountItem(&$company, $title)
{
    $tab   = array();
    $years = array();
    foreach ($company->AnnualAccounts as $a) {
        switch ($title) {
        case 'ACTIF':
            $account = $a->OriginalAnnualAccounts
                ->BalanceSheet->Assets;
            break;
        case 'PASSIF':
            $account = $a->OriginalAnnualAccounts
                ->BalanceSheet->Liabilities;
            break;
        default:
            $account = $a->OriginalAnnualAccounts->ProfitAndLoss;
        }
        $num     = 0;
        $year    = substr($a->AccountsDate->_, 0, 4);
        $years[] = $year;
        fillAccountItem($tab, $num, $account, $year);
    }
    rsort($years);
    print '<tr>'.
        '<td style="background-color: #00008c; color: #ffffff;"><b>'.
        $title.'</b></td>';
    foreach ($years as $y) {
        print '<td  style="background-color: #00008c; color: #ffffff;"'.
            ' align="right"><b>'.$y.'</b></td>';
    }
    $level = 0;
    foreach ($tab as $line) {
        while ($line->niv < $level) {
            print '</tbody>';
            --$level;
        }
        $level = $line->niv;
        print '<tr>';
        print '<td>';
        for ($i = 0; $i < $line->niv; ++$i) {
            print '&nbsp;';
        }
        print $line->des;
        print '</td>';
        foreach ($years as $y) {
            print '<td align="right">';
            if (isset($line->val[$y]) == true) {
                print $line->val[$y];
            }
            print '</td>';
        }
        print '</tr>';
    }
}

// --------------------------------------------------------------------------- //
// printLiensFinanciers
// --------------------------------------------------------------------------- //
function printLiensFinanciers(&$company, $type)
{
    foreach (getArray($company->Associated) as $t) {
        if ($t->RelationShip == $type) {
            $libelle = '';
            if (isset($t->Shares) == true) {
                $libelle = $t->Shares->Percentage.' %';
            }
            $id = '';
            if (isset($t->Company->CompanyId) == true) {
                $id = $t->Company->CompanyId;
            } else if (isset($t->Company->CompanyAddress) == true &&
                       isset($t->Company->CompanyAddress->Country) == true) {
                $id = '('.$t->Company->CompanyAddress->Country.')';
            }
            $name = '';
            if (isset($t->Company->CompanyName) == true) {
                $name .= ' '.$t->Company->CompanyName->_;
            }
            dRow2($libelle, $name, $id);
        }
    }
}

// --------------------------------------------------------------------------- //
// Type de rapport
// --------------------------------------------------------------------------- //
require_once 'dbbootstrap.php';
setDbConn('giantclient');

$r = Doctrine_Query::create()
    ->from('Rapports')
    ->where('OrderId = ?', $commande_id)
    ->andWhere('User = ?', $_SESSION['tabInfo']['login'])
    ->fetchOne();

if ($r == false) {
    exit;
}

print '<div id="center">';
switch ($r->DataSetType) {
case 'Full':
    print '<h1>RAPPORT COMPLET</h1>';
    break;
case 'Compact':
    print '<h1>RAPPORT DE SYNTHESE</h1>';
    break;
case 'CreditRecommendation':
    print '<h1>RAPPORT DE SCORE</h1>';
    break;
}
$d = unserialize($r->DataSet);
$c = $d->Company;
print '<p id="rsynthese">SOCI&Eacute;T&Eacute; : '.$c->CompanyName->_.'</p>';

// --------------------------------------------------------------------------- //
// Identite de l'entreprise
// --------------------------------------------------------------------------- //
print '<h1>IDENTITÉ DE L\'ENTREPRISE</h1>';
print '<table>';
dRow('Numéro identifiant',             $c->CompanyId);
if (isset($c->Vat->VatNumber) == true) {
    dRow('Numéro de TVA Intracom.',    $c->Vat->VatNumber);
}
if (isset($c->SocialSecurityNumber) == true) {
    dRow('Numéro de Securité Sociale', $c->SocialSecurityNumber);
}
if (isset($c->CompanyStatus) == true) {
    dRow('Etablissement actif', ($c->CompanyStatus == 'Active') ? 'Oui' : 'Non');
}
print '</table>';

// --------------------------------------------------------------------------- //
// Raison sociale et coordonnees
// --------------------------------------------------------------------------- //
print '<h2>Raison sociale &amp; Coordonnées</h2>';
print '<table>';
dRow('Raison Sociale',  $c->CompanyName->_);
if (isset($c->TradeName) == true) {
    $libelle = 'Enseigne(s)';
    foreach (getArray($c->TradeName) as $t) {
        dRow($libelle, $t->_);
        $libelle = '';
    }
}
if (isset($c->LegalForm->CountryLegalForm) == true) {
    dRow('Forme juridique',
         $c->LegalForm->CountryLegalForm->code.' : '.
         $c->LegalForm->CountryLegalForm->_);
}
dRow('Adresse',
     $c->CompanyAddress->HouseNumber.' '.
     $c->CompanyAddress->Street.' '.
     $c->CompanyAddress->PostCode.' '.
     $c->CompanyAddress->City.' '.
     $c->CompanyAddress->Country);
if (isset($c->TelephoneNumber) == true) {
    $libelle = 'Téléphone(s)';
    foreach (getArray($c->TelephoneNumber) as $t) {
        $mobile = (isset($t->isMobile) == true &&
                   $t->isMobile == 1) ? ' (mobile)' : '';
        dRow($libelle, $t->_.$mobile);
        $libelle = '';
    }
}
if (isset($c->Telefax) == true) {
    dRow('Fax', $c->Telefax);
}
if (isset($c->WebAddress) == true) {
    dRow('Site Internet',
         '<a href="'.$c->WebAddress.'" target="_blank">'.$c->WebAddress.'</a>');
}
if (isset($c->EmailAddress) == true) {
    dRow('Courriel',
         '<a href="mailto:'.$c->EmailAddress.'" target="_blank">'.
         $c->EmailAddress.'</a>');
}
print '</table>';

// --------------------------------------------------------------------------- //
// Banques
// --------------------------------------------------------------------------- //
if (isset($c->Bank) == true) {
    print '<h2>Banques</h2>';
    print '<table>';
    foreach (getArray($c->Bank) as $t) {
        $libelle = $t->BankName;
        if (isset($t->BankIdentifierCode) == true) {
            dRow($libelle, 'BIC: '.$t->BankIdentifierCode);
            $libelle = '';
        }
        if (isset($t->BankAccount) == true) {
            dRow($libelle,
                 $t->BankAccount->AccountType.': '.
                 $t->BankAccount->AccountNumber);
            $libelle = '';
        }
        if (isset($t->BankAddress) == true) {
            $adresse = '';
            if (      isset($t->BankAddress->HouseNumber) == true) {
                $adresse .= $t->BankAddress->HouseNumber.' ';
            }
            if (      isset($t->BankAddress->Street) == true) {
                $adresse .= $t->BankAddress->Street.' ';
            }
            if (      isset($t->BankAddress->PostCode) == true) {
                $adresse .= $t->BankAddress->PostCode.' ';
            }
            if (      isset($t->BankAddress->City) == true) {
                $adresse .= $t->BankAddress->City.' ';
            }
            if (      isset($t->BankAddress->Country) == true) {
                $adresse .= $t->BankAddress->Country.' ';
            }
            dRow($libelle, $adresse);
        }
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Activite(s) et chiffre d'affaire
// --------------------------------------------------------------------------- //
if (isset($c->Operations->IndustryCode) == true ||
    isset($c->FinancialSummary) == true ||
    isset($capital) == true ||
    isset($c->Employees) == true) {
    print '<h2>Activité(s) &amp; Chiffre d\'affaire</h2>';
    print '<table>';
    if (isset($c->Operations->IndustryCode) == true) {
        $libelle = 'Activité(s)';
        foreach (getArray($c->Operations->IndustryCode) as $t) {
            $desc = 'Nace '.$t->NaceCode;
            if (       isset($t->Description->_) == true) {
                $desc .= ' '.$t->Description->_;
            }
            dRow($libelle, $desc);
            $libelle = '';
        }
    }
    if (isset($c->FinancialSummary) == true) {
        $tab  = getArray($c->FinancialSummary);
        $date = 0;
        foreach ($tab as $t) {
            if ($t->SummaryDate->_ > $date &&
                isset($t->AuthorizedCapital) == true) {
                $capital = $t->AuthorizedCapital->_;
                $date    = $t->SummaryDate->_;
            }
        }
    }
    if (isset($capital) == false &&
        isset($c->ShareCapital->AuthorizedCapital->_) == true &&
        (isset($c->ShareCapital->AuthorizedCapital->currency) == false ||
         $c->ShareCapital->AuthorizedCapital->currency == 'EUR')) {
        $capital = $c->ShareCapital->AuthorizedCapital->_;
    }
    if (isset($capital) == true) {
        dRow('Capital', $capital.' &euro;');
    }
    if (isset($c->Employees) == true) {
        $annee = 0;
        $total = 0;
        foreach (getArray($c->Employees) as $t) {
            if (isset($t->Period) == true) {
                if (isset($t->Period->StartDate->_) == true &&
                    $t->Period->StartDate->_ > $annee) {
                    $annee = $t->Period->StartDate->_;
                    $total = $t->TotalStaffEmployed + 0;
                } else if (isset($t->Period->EndDate->_) == true &&
                           $t->Period->EndDate->_ > $annee) {
                    $annee = $t->Period->EndDate->_;
                    $total = $t->TotalStaffEmployed + 0;
                }
            } else {
                $total = $t->TotalStaffEmployed + 0;
            }
        }
        if ($total > 0) {
            if ($annee > 0) {
                dRow('Effectif de l\'entreprise',
                     $total.' salarié(s) en '.substr($annee, 0, 4));
            } else {
                dRow('Effectif de l\'entreprise', $total.' salarié(s)');
            }
        }
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Annonces legales
// --------------------------------------------------------------------------- //
if (isset($c->Event) == true) {
    print '<h1>ANNONCES LÉGALES</h1>';
    print '<table>';
    $tab = getArray($c->Event);
    usort($tab, 'cmp');
    foreach ($tab as $t) {
        if (isset($t->Value) == true) {
            $desc = printObj($t->Value);
            if (  isset($t->Description->_) == true) {
                $desc = $t->Description->_.' '.$desc;
            }
            dRow(pdate($t->Date), $desc);
        } else if (isset($t->Description->_) == true) {
            dRow(pdate($t->Date), $t->Description->_);
        } else {
            dRow(pdate($t->Date), '('.$t->EventCode.')');
        }
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Dirigeants
// --------------------------------------------------------------------------- //
if (isset($c->Position) == true) {
    print '<h1>DIRIGEANTS</h1>';
    print '<table>';
    foreach (getArray($c->Position) as $t) {
        if (isset($t->Person) == false) {
            continue;
        }
        $date = '';
        if (isset($t->Period->StartDate) == true) {
            $date .= pdate($t->Period->StartDate);
        }
        $date .= ' - ';
        if (isset($t->Period->EndDate) == true) {
            $date .= pdate($t->Period->EndDate);
        }
        $desc = $t->PositionTitle->_.' '.$t->Person->LastName;
        if (isset($t->Person->FirstName) == true) {
            $desc .= ' '.$t->Person->FirstName;
        }
        dRow($date, $desc);
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Employés
// --------------------------------------------------------------------------- //
if (isset($c->Employees) == true) {
    print '<h1>EMPLOYÉS</h1>';
    print '<table>';
    foreach (getArray($c->Employees) as $t) {
        if (isset($t->Period) == true) {
            if (isset($t->Period->StartDate) == true) {
                dRow(pdate($t->Period->StartDate), $t->TotalStaffEmployed + 0);
            } else if (isset($t->Period->EndDate) == true) {
                dRow(pdate($t->Period->EndDate), $t->TotalStaffEmployed + 0);
            }
        } else {
            dRow('', $t->TotalStaffEmployed + 0);
        }
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Synthese
// --------------------------------------------------------------------------- //
if (isset($c->FinancialSummary) == true) {
    print '<h1>Synthèse</h1>';
    print '<center>';
    print '<table cellpadding="4">';
    $tab = getArray($c->FinancialSummary);
    print '<tr><td></td>';
    foreach ($tab as $t) {
        print '<td align="right"><b>'.substr($t->SummaryDate->_, 0, 4).
            '</b></td>';
    }
    print '</tr>';
    foreach (array('Revenue',
                   'TotalEquity',
                   'ProfitLossBeforeTax',
                   'ProfitLoss',
                   'WorkingCapital',
                   'AuthorizedCapital') as $n) {
        print '<tr>';
        print '<td>';
        print $n;
        print '</td>';
        foreach ($tab as $t) {
            print '<td align="right">';
            if (isset($t->$n) == true) {
                $val = $t->$n->_;
                if (is_numeric($val) == true) {
                    print $val * $t->Unit;
                } else {
                    print $val;
                }
            }
            print '</td>';
        }
        print '</tr>';
    }
    print '</table>';
    print '</center>';
}

// --------------------------------------------------------------------------- //
// Bilans
// --------------------------------------------------------------------------- //
if (isset($c->AnnualAccounts) == true) {
    print '<h1>ÉLÉMENTS FINANCIERS - BILANS</h1>';
    print '<center>';
    print '<table rules="groups" cellpadding="4">';
    printAccountItem($c, 'ACTIF');
    printAccountItem($c, 'PASSIF');
    printAccountItem($c, 'COMPTE DE RÉSULTAT');
    print '</table>';
    print '</center>';
}

// --------------------------------------------------------------------------- //
// Etablissements
// --------------------------------------------------------------------------- //
if (isset($c->Branch) == true) {
    print '<h1>Établissements</h1>';
    print '<table>';
    foreach (getArray($c->Branch) as $t) {
        if (isset($t->BranchName->_) == true) {
            $libelle = $t->BranchName->_;
        } else if (isset($t->BranchName) == true) {
            $libelle = $t->BranchName;
        } else if (isset($t->BranchId) == true) {
            $libelle = $t->BranchId;
        }
        dRow($libelle,
             $c->CompanyAddress->HouseNumber.' '.
             $c->CompanyAddress->Street.' '.
             $c->CompanyAddress->PostCode.' '.
             $c->CompanyAddress->City.' '.
             $c->CompanyAddress->Country);
    }
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Liens financiers
// --------------------------------------------------------------------------- //
if (isset($c->Associated) == true) {
    print '<h1>Liens financiers</h1>';
    print '<h2>Actionnariat</h2>';
    print '<table>';
    printLiensFinanciers($c, 'Shareholder');
    print '</table>';
    print '<h2>Participations</h2>';
    print '<table>';
    printLiensFinanciers($c, 'Participation');
    print '</table>';
}

// --------------------------------------------------------------------------- //
// Paiements
// --------------------------------------------------------------------------- //
if (isset($c->PaymentBehaviour) == true) {
    print '<h1>Paiements</h1>';
    print '<table>';
    $date = '';
    if (isset($c->PaymentBehaviour->Period->StartDate) == true) {
        $date = pdate($c->PaymentBehaviour->Period->StartDate);
    }
    if (isset($c->PaymentBehaviour->Period->EndDate) == true) {
        $date .= ' -> '.pdate($c->PaymentBehaviour->Period->EndDate);
    }
    if (empty($date) == false) {
        dRow('Date', $date);
    }
    if (isset($c->PaymentBehaviour->DebtorDays) == true) {
        dRow('DebtorDays', $c->PaymentBehaviour->DebtorDays);
    }
    if (isset($c->PaymentBehaviour->CreditorDays) == true) {
        dRow('CreditorDays', $c->PaymentBehaviour->CreditorDays);
    }
    if (isset($c->PaymentBehaviour->LiquidityAssessment) == true) {
        $desc = $c->PaymentBehaviour->LiquidityAssessment->Qualification;
        if (isset($c->PaymentBehaviour->LiquidityAssessment
                  ->AdditionalQualification) == true) {
            $desc .= ', '.$c->PaymentBehaviour->LiquidityAssessment
                ->AdditionalQualification->_;
        }
        dRow('LiquidityAssessment', $desc);
    }
    if (isset($c->PaymentBehaviour->PaymentQualification) == true) {
        $desc = $c->PaymentBehaviour->PaymentQualification->Qualification;
        if (isset($c->PaymentBehaviour->PaymentQualification
                  ->AdditionalQualification) == true) {
            $desc .= ', '.$c->PaymentBehaviour->PaymentQualification
                ->AdditionalQualification->_;
        }
        dRow('PaymentQualification', $desc);
    }
    print '</table>';
    if (isset($c->PaymentBehaviour->AnalysisByPeriod) == true) {
        $ap = $c->PaymentBehaviour->AnalysisByPeriod;
        $tab = array();
        foreach ($ap->Category as $cat) {
            $trim =
                pdate($cat->Period->StartDate).' - '.
                pdate($cat->Period->EndDate);
            $total = 0;
            foreach (getArray($cat->DueDateExceeds) as $e) {
                if ($e->NrOfDaysExceeds->LowerLimit->_ >= 90) {
                    $total += $e->Percentage;
                } else {
                    $lab =
                        $e->NrOfDaysExceeds->LowerLimit->_.' to '.
                        $e->NrOfDaysExceeds->UpperLimit->_;
                    $tab[$lab][$trim] = $e->Percentage;
                }
            }
            $tab['90-'][$trim] = $total;
        }
        ksort($tab);
        print '<h2>'.$ap->Description->_.'</h2>';
        print '<table cellpadding="10">';
        print '<tr>';
        print '<td>Quarter</td>';
        print '<td>Within term</td>';
        foreach ($tab as $tranche => $valeurs) {
            print '<td>'.$tranche.'</td>';
        }
        print '</tr>';
        foreach ($ap->Category as $cat) {
            $trim =
                pdate($cat->Period->StartDate).' - '.
                pdate($cat->Period->EndDate);
            print '<tr align="right">'.
                '<td>'.$trim.'</td>'.
                '<td>'.$cat->PercentageWithinTerms.' %</td>';
            foreach ($tab as $tranche => $valeurs) {
                if (isset($tab[$tranche][$trim]) == true) {
                    print '<td>'.$tab[$tranche][$trim].' %</td>';
                } else {
                    print '<td>0 %</td>';
                }
            }
            print '</tr>';
        }
        print '</table>';
    }
    if (isset($c->PaymentBehaviour->AnalysisByAmount) == true) {
        $ap = $c->PaymentBehaviour->AnalysisByAmount;
        $tab = array();
        foreach ($ap->Category as $cat) {
            $amount = '';
            if (     isset($cat->AmountCategory->LowerLimit) == true) {
                $amount .= $cat->AmountCategory->LowerLimit->_;
            }
            $amount .= '-';
            if (     isset($cat->AmountCategory->HigherLimit) == true) {
                $amount .= $cat->AmountCategory->HigherLimit->_;
            }
            $total = 0;
            foreach (getArray($cat->DueDateExceeds) as $e) {
                if ($e->NrOfDaysExceeds->LowerLimit->_ >= 90) {
                    $total += $e->Percentage;
                } else {
                    $lab =
                        $e->NrOfDaysExceeds->LowerLimit->_.' to '.
                        $e->NrOfDaysExceeds->UpperLimit->_;
                    $tab[$lab][$amount] = $e->Percentage;
                }
            }
            $tab['90-'][$amount] = $total;
        }
        ksort($tab);
        print '<h2>'.$ap->Description->_.'</h2>';
        print '<table cellpadding="10">';
        print '<tr>';
        print '<td>Amount</td>';
        print '<td>Within term</td>';
        foreach ($tab as $tranche => $valeurs) {
            print '<td>'.$tranche.'</td>';
        }
        print '</tr>';
        foreach ($ap->Category as $cat) {
            $amount = '';
            if (     isset($cat->AmountCategory->LowerLimit) == true) {
                $amount .= $cat->AmountCategory->LowerLimit->_;
            }
            $amount .= '-';
            if (     isset($cat->AmountCategory->HigherLimit) == true) {
                $amount .= $cat->AmountCategory->HigherLimit->_;
            }
            print '<tr>'.
                '<td>'.$amount.'</td>'.
                '<td>'.$cat->PercentageWithinTerms.' %</td>';
            foreach ($tab as $tranche => $valeurs) {
                if (isset($tab[$tranche][$amount]) == true) {
                    print '<td>'.$tab[$tranche][$amount].' %</td>';
                } else {
                    print '<td>0 %</td>';
                }
            }
            print '</tr>';
        }
        print '</table>';
    }
}

// --------------------------------------------------------------------------- //
// Score
// --------------------------------------------------------------------------- //
print '<h1>Score</h1>';
print '<table>';
if (isset($c->CreditRecommendation->Date) == true) {
    dRow('Date', pdate($c->CreditRecommendation->Date));
}
if (isset($c->CreditRecommendation->RiskClasses) == true) {
    foreach (getArray($c->CreditRecommendation
                      ->RiskClasses->ProviderRiskClass) as $t) {
        if (isset($t->Description->_) == true) {
            $desc = '&nbsp;&nbsp;&nbsp;&nbsp;'.
                '<img src="img/info.gif"'.
                ' style="vertical-align:middle;"'.
                ' title="'.$t->Description->_.'"/>';
        } else {
            $desc = '';
        }
        dRow($t->RatingName->_.$desc, $t->RatingValue);
    }
    $t = $c->CreditRecommendation->RiskClasses->CommonRiskClass;
    if (isset($t->Description->_) == true) {
        $desc = '&nbsp;&nbsp;&nbsp;&nbsp;'.
            '<img src="img/info.gif"'.
            ' style="vertical-align:middle;"'.
            ' title="'.$t->Description->_.'"/>';
    } else {
        $desc = '';
    }
    dRow($t->RatingName->_.$desc, $t->RatingValue);
}
dRow('AmountAdvised', $c->CreditRecommendation->AmountAdvised->_.' '.
     $c->CreditRecommendation->AmountAdvised->currency);
print '</table>';

// --------------------------------------------------------------------------- //
// Ratios secteur
// --------------------------------------------------------------------------- //
if (isset($c->PeerGroup->FlexibleComparisonItems
          ->ComparisonItemsGroup[0]->FlexibleComparisonItem) == true) {
    print '<h1>Ratios secteur</h1>';
    print '<table>';
    print '<tr>';
    print '<td>';
    print '</td>';
    foreach ($c->PeerGroup->FlexibleComparisonItems->ComparisonItemsGroup as
             $group) {
        print '<td align="right"><b>';
        print substr($group->Period->EndDate->_, 0, 4);
        print '</b></td>';
        print '<td align="right">';
        print 'secteur';
        print '</td>';
    }
    print '<tr>';
    foreach ($c->PeerGroup->FlexibleComparisonItems
             ->ComparisonItemsGroup[0]->FlexibleComparisonItem as $i => $item) {
        print '<tr>';
        print '<td>';
        print $item->ItemName->_;
        print '</td>';
        foreach ($c->PeerGroup->FlexibleComparisonItems->ComparisonItemsGroup as
                 $group) {
            print '<td align="right">';
            print $group->FlexibleComparisonItem[$i]->SubjectValue;
            print '</td>';
            print '<td align="right">';
            print $group->FlexibleComparisonItem[$i]->AverageValue;
            print '</td>';
        }
        print '</tr>';
    }
    print '</table>';
}

print '</div>';
?>