<?php

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

use Garradin\Plugin\RecusFiscaux\RecusHTML;
use Garradin\Plugin\RecusFiscaux\Utils;
use Garradin\Plugin\RecusFiscaux\Personne;

// récupérer les lignes sélectionnées
$lesLignes = f('selected');

// filtrer les versements sélectionnés
$versementsSelectionnes = array();
foreach ($lesLignes as $ligne) {
    $versementsSelectionnes[] = $_SESSION['lesVersements'][$ligne];
}

// cumuler les versements d'une personne : id => Personne
$totalPersonnes = cumulerVersements($versementsSelectionnes);
error_log("totalPersonnes = " . print_r($totalPersonnes, true));

// informations pour les reçus
$nomAsso = $config->get('nom_asso');
$adresseAsso = $config->get('adresse_asso');
$signature =
           (null !== $plugin->getConfig('signature')) ?
           Files::get($plugin->getConfig('signature'))->fullpath() :
           "";

// logo
$logo_file = Files::get(File::CONTEXT_CONFIG . '/logo.png');
$logoAsso =
          (null !== $logo_file) ?
          Files::get($logo_file->path)->fullpath() :
          "";

// articles du CGI
$articlesCGI = array();
foreach ($plugin->getConfig('articlesCGI') as $article)
{
    if ($article->valeur == 1) {
        $articlesCGI[] = $article->titre;
    }
}

$listeFichiers = array();    // fichiers pdf générés
foreach ($totalPersonnes as $idPersonne => $personne)
{
    // générer un fichier par reçu
    $html = new RecusHTML(
        $nomAsso,
        $adresseAsso,
        $logoAsso,
        $plugin->getConfig('objet_asso'),
        $plugin->getConfig('nom_responsable'),
        $plugin->getConfig('fonction_responsable'),
        $plugin->getConfig('ville_asso'),
        $articlesCGI,
        $signature
    );

    $html->imprimer_recu(
        $_SESSION['annee_recu'],
        $personne->id,
        $personne->nomPrenom,
        $personne->versements,
        $personne->adresse,
        $personne->codePostal,
        $personne->ville
    );
    // fabriquer le fichier PDF
    $nomPDF = \Garradin\Utils::filePDF($html->get());
    // changer le nom du fichier
    $nom = str_replace(' ', '_', $personne->nomPrenom);
    $nom = str_replace("'", "", $nom);
    $nomFichier = "recu_" . $_SESSION['annee_recu'] . "_" . $nom . ".pdf";
    rename($nomPDF, $nomFichier);
    // ajouter le nom du fichier à la liste pour mettre dans une archive
    $listeFichiers[] = $nomFichier;
}

// faire une archive zip
$fichierZip = Utils::makeArchive(
    $listeFichiers,
    $_SESSION['annee_recu'],
    PLUGIN_ROOT . "/zip"
);

/**
 * Cumuler les versements de chaque personne par tarif
 * @param tableau des versements triés par idTarif, idUser, date
 * @return tableau des versements cumulés : id => Personne
 */
function cumulerVersements($versements)
{
    $totalPersonnes = array();
    $idTarifCourant = -1;
    $idPersonneCourant = -1;
    $totalVersements = 0;
    foreach ($versements as $ligne)
    {
        if (
            $ligne->idTarif != $idTarifCourant ||
            $ligne->idUser != $idPersonneCourant
        )
        {
            if ($idTarifCourant != -1)
            {
                // changement de tarif ou de personne
                $totalPersonnes[$idPersonneCourant]->ajouterVersement(
                    $_SESSION['tauxSelectionnes'][$idTarifCourant],
                    $totalVersements/100
                );
            }
            $idTarifCourant = $ligne->idTarif;
            $idPersonneCourant = $ligne->idUser;
            $totalVersements = $ligne->versement;
            // créer les infos de la personne, sauf si elle est déjà présente
            if (!array_key_exists($idPersonneCourant, $totalPersonnes))
            {
                $totalPersonnes["$idPersonneCourant"] = $_SESSION['membresDonateurs'][$ligne->idUser]->clone();
            }
        } else {
            // cumuler versements
            $totalVersements += $ligne->versement;
        }
    }
    // et le dernier
    $totalPersonnes[$idPersonneCourant]->ajouterVersement(
        $_SESSION['tauxSelectionnes'][$idTarifCourant],
        $totalVersements/100
    );
    return $totalPersonnes;
}