<?php

namespace Garradin;

use Garradin\Plugin\RecusFiscaux\RecusPDF;
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
$totalPersonnes = cumulerVersements($versementsSelectionnes);

// générer les reçus
$nomAsso = Utils::getNomAsso();
$adresseAsso = Utils::getAdresseAsso();

// TODO
// - associer le taux de réduction à chaque montant total

// récupérer le logo CERFA (bôf) et la signature
$logoCERFA = PLUGIN_ROOT . "/data/logoCerfa.png";
$signature = PLUGIN_ROOT . "/data/default_signature.png";
$listeFichiers = [];

foreach ($totalPersonnes as $idPersonne => $personne) {
    // générer un fichier par reçu
    $pdf = new RecusPDF(
        'DejaVu',
        'SerifCondensed',
        $nomAsso,
        $adresseAsso,
        $logoCERFA,
        $signature
    );
    // extraire les montants des versements
    $lesMontants = array();
    foreach ($personne->versements as $versement)
    {
        if (array_key_exists($versement->tauxReduction, $lesMontants)) {
            $lesMontants[$versement->tauxReduction] += $versement->montant;
        }
        else {
            $lesMontants[$versement->tauxReduction] = $versement->montant;
        }
    }
    $pdf->imprimer_recu(
        $_SESSION['annee_recu'],
        $personne->id,
        $personne->nomPrenom,
        $lesMontants,
        $personne->adresse,
        $personne->codePostal,
        $personne->ville
    );
    // fabriquer le nom du fichier PDF
    $nom = str_replace(' ', '_', $personne->nomPrenom);
    $nom = str_replace("'", "", $nom);
    //    $nomFichier = Utils::getPDFDirectory() . "/" . 'recu_' . $annee_recu . '_' . $nom . '.pdf';
    $nomFichier = PLUGIN_ROOT . '/pdf/recu_' . $_SESSION['annee_recu'] . '_' . $nom . '.pdf';

    $pdf->Output('F', $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();
    $idTarif_courant = -1;
    $idPersonne_courant = -1;
    $totalVersements = 0;
    foreach ($versements as $ligne)
    {
        if (
            $ligne->idTarif != $idTarif_courant ||
            $ligne->idUser != $idPersonne_courant
        )
        {
            if ($idTarif_courant != -1) {
                $totalPersonnes[$idPersonne_courant]->ajouterVersement(
                    $_SESSION['lesTarifs'][$idTarif_courant]->idActivite,
                    $idTarif_courant,
                    $totalVersements/100,
                    $_SESSION['tauxSelectionnes'][$idTarif_courant]
                );
            }
            $idTarif_courant = $ligne->idTarif;
            $idPersonne_courant = $ligne->idUser;
            $totalVersements = $ligne->versement;
            // créer les infos de la personne, sauf si elle est déjà présente
            if (!array_key_exists($idPersonne_courant, $totalPersonnes))
            {
                $totalPersonnes["$idPersonne_courant"] = Personne::copier($_SESSION['membresDonateurs'][$ligne->idUser]);
            }
        } else {
            // cumuler versements
            $totalVersements += $ligne->versement;
        }
    }
    // et le dernier
    $totalPersonnes[$idPersonne_courant]->ajouterVersement(
        $_SESSION['lesTarifs'][$idTarif_courant]->idActivite,
        $idTarif_courant,
        $totalVersements/100,
        $_SESSION['tauxSelectionnes'][$idTarif_courant]
    );

    return $totalPersonnes;
}