<?php

namespace Garradin;

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

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

// signature
$signature =
           (null !== $plugin->getConfig('signature')) ?
           Files::get($plugin->getConfig('signature'))->fullpath() :
           "";

// logo
$logo_file = Files::get(File::CONTEXT_CONFIG . '/logo.png');
$logo_asso =
          (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;
    }
}
$nbArticles = count($articlesCGI);
if ($nbArticles == 1)
{
    $texteArticles = 'à l’article ' . $articlesCGI[0];
}
elseif ($nbArticles > 1)
{
    $texteArticles = 'aux articles ';
    for ($i = 0; $i < $nbArticles; ++$i) {
        $texteArticles .= $articlesCGI[$i];
        if ($i < $nbArticles - 2) {
            $texteArticles .= ", ";
        }
        else if ($i == $nbArticles - 2) {
            $texteArticles .= " et ";
        }
    }
}

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

// cumuler les versements
if ($_GET['type'] == 'personne')
{
    $totalPersonnes = cumulerVersementsPersonne($versementsSelectionnes);
}
elseif ($_GET['type'] == 'activite')
{
    $totalPersonnes = cumulerVersementsTarif($versementsSelectionnes);
}

// générer les reçus
$listeFichiersPDF = array();
foreach ($totalPersonnes as $idPersonne => $personne)
{
    $tpl = new UserTemplate();
    $tpl->setSource(PLUGIN_ROOT . '/templates/recu.skel');

    $tpl->assignArray(compact('signature', 'logo_asso', 'texteArticles'));
    $tpl->assign('objet_asso', $plugin->getConfig('objet_asso'));
    $tpl->assign('nom_responsable', $plugin->getConfig('nom_responsable'));
    $tpl->assign('fonction_responsable', $plugin->getConfig('fonction_responsable'));
    $tpl->assign('ville_asso', $plugin->getConfig('ville_asso'));
    $tpl->assign('annee_recu', $_SESSION['annee_recu']);
    $tpl->assign('numero', $personne->id);
    $tpl->assign('nom', $personne->nomPrenom);
    $tpl->assign('adresse', $personne->adresse);
    $tpl->assign('code_postal', $personne->codePostal);
    $tpl->assign('ville', $personne->ville);
    $tpl->assign('date', date("j/m/Y"));

    // les versements
    $tpl->registerSection('versements',
                          function () use($personne)
                          {
                              foreach ($personne->versements as $taux => $montant)
                              {
                                  $ligne['montant'] = $montant;
                                  $ligne['libelle'] = Utils::getLigneReduction($taux);
                                  yield $ligne;
                              }
                          });

    // mentions complémentaires
    $donnees = array(
        'Date des versements : ' => "année " . $_SESSION['annee_recu'],
        'Nature du don : ' => "Numéraire",
        'Mode de versement : ' => "chèque et/ou virement"
    );
    $infos = array();
    foreach ($donnees as $titre => $libelle)
    {
        $elem = new \stdClass();
        $elem->titre = $titre;
        $elem->libelle = $libelle;
        $infos[] = $elem;
    }

    $tpl->registerSection('informations',
                          function () use ($infos)
                          {
                              foreach ($infos as $elem)
                              {
                                  yield (array) $elem;
                              }
                          });

    // fabriquer le fichier PDF
    $result = $tpl->fetch();
    $nomPDF = \Garradin\Utils::filePDF($result);
    // 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
    $listeFichiersPDF[] = $nomFichier;
}

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

/**
 * Cumuler les versements de chaque personne
 * @param tableau des versements triés par idUser, date
 * @return tableau des versements cumulés : id => Personne
 */
function cumulerVersementsPersonne($versements)
{
    $totalPersonnes = array();
    $idPersonneCourant = -1;
    $totalVersements = 0;
    foreach ($versements as $ligne)
    {
        if ($ligne->idUser != $idPersonneCourant)
        {
            // changement de personne
            if ($idPersonneCourant != -1)
            {
                $totalPersonnes[$idPersonneCourant]->ajouterVersement(
                    $_SESSION['taux_reduction'],
                    $totalVersements
                );
            }
            $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['taux_reduction'],
        $totalVersements
    );
    return $totalPersonnes;
}

/**
 * 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 cumulerVersementsTarif($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
                );
            }
            $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
    );
    return $totalPersonnes;
}