#!/usr/bin/perl

#Recherche du client le plus important


if (! -e "commandes.txt" || -z "commandes.txt")
{
    print "Content-type: text/html\r\n\r\n";
    print "<html><head><title>Aucune commande</title></head";
    print "<body><p>";
    print "Il n'y a actuellement aucune commande";
    print "</p></body></html>";
    exit;
}

%total = ();
%nombre_commandes = ();

open FICHIER,"commandes.txt";
@commandes = <FICHIER>;
close FICHIER;

chomp @commandes;

foreach (@commandes)
{
    ($numero,$nom,$prenom,$email,$produit) = split /\//;
    $identifiant = "$nom/$prenom/$email";
    $nombre_commandes{$identifiant}++;
    $total{$identifiant} += 10 if ($produit eq "Livre");
    $total{$identifiant} += 15 if ($produit eq "CD");
    $total{$identifiant} += 22 if ($produit eq "DVD");
}

$max = 0;

foreach (keys %total)
{
    $max = $total{$_} if ($total{$_} > $max);
}

%plus_importants = ();

foreach (keys %total)
{
    $plus_importants{$_} = $total{$_} if ($total{$_} == $max);
}

print "Content-type: text/html\r\n\r\n";
print "<html><head><title>Resultats</title></head";
print "<body><p><table border='1'>";
print "<tr><th>Nom</th><th>Pr&eacute;nom</th><th>Adresse e-mail</th>";
print "<th>Nombre de commandes</th><th>Total en euros</th></tr>";
while ( ($client,$montant) = each (%plus_importants) )
{
    ($nom,$prenom,$email) = split /\//,$client;
    print "<tr>";
    print "<td>$nom</td><td>$prenom</td><td>$email</td>";
    print "<td>$nombre_commandes{$client}</td>";
    print "<td>$montant</td>";
    print "</tr>";
} 
print "</p></table></body></html>";
