<?php

namespace App\Service;

use App\Entity\AdvertPayment;
use App\Entity\Echeancier;
use App\Entity\EcheancierLine;
use App\Entity\Facture;
use App\Entity\FacturePrestataire;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class ComptaExportService
{
    public const LABEL_JOURNAL_VENTES = 'Journal des ventes';
    public const LABEL_GRAND_LIVRE = 'Grand livre clients';
    public const LABEL_COMMISSIONS_STRIPE = 'Commissions Stripe';
    public const DATE_FORMAT_FR = 'd/m/Y';
    private const DQL_BETWEEN_DATES = 'f.createdAt BETWEEN :from AND :to';
    private const DQL_IS_PAID = 'f.isPaid = true';
    private const PREFIX_FACTURE = 'Facture ';

    public const SERVICE_COSTS = [
        'website' => ['name' => 'E-Site', 'cout' => 150.00],
        'hosting' => ['name' => 'E-Site', 'cout' => 0.00],
        'maintenance' => ['name' => 'E-Site', 'cout' => 0.00],
        'esymail' => ['name' => 'E-Mail', 'cout' => 70.00],
        'ndd' => ['name' => 'Nom de domaine', 'cout' => 0.00, 'cout_par_ligne' => 15.00],
        'other' => ['name' => 'Autre', 'cout' => 0.00],
    ];

    public const STRIPE_COMMISSION_RATE = 0.015;
    public const STRIPE_FIXED_FEE = 0.25;

    public function __construct(
        private EntityManagerInterface $em,
        #[Autowire('%env(bool:TVA_ENABLED)%')]
        private bool $tvaEnabled,
        private ComptaHelperService $helper,
    ) {
    }

    /**
     * Retourne les donnees d'export selon le type.
     *
     * @return list<array<string, string>>
     */
    public function getExportData(string $type, \DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        return match ($type) {
            'journal-ventes' => $this->buildJournalVentesData($from, $to),
            'grand-livre' => $this->buildGrandLivreData($from, $to),
            'fec' => $this->buildFecData($from, $to),
            'balance-agee' => $this->buildBalanceAgeeData(),
            'reglements' => $this->buildReglementsData($from, $to),
            'commissions-stripe' => $this->buildCommissionsStripeData($from, $to),
            'couts-services' => $this->buildCoutsServicesData($from, $to),
            'echeanciers' => $this->buildEcheancierData($from, $to),
            default => [],
        };
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildJournalVentesData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $tvaEnabled = $this->tvaEnabled;
        $factures = $this->helper->getFactures($from, $to);
        $rows = [];

        foreach ($factures as $facture) {
            $customer = $facture->getCustomer();
            [$codeComptable, $raisonSociale] = $this->helper->resolveCustomerInfo($customer);

            $row = [
                'JournalCode' => 'VE',
                'JournalLib' => self::LABEL_JOURNAL_VENTES,
                'EcritureNum' => $facture->getInvoiceNumber(),
                'EcritureDate' => $facture->getCreatedAt()->format('Y-m-d'),
                'CompteNum' => '706000',
                'CompteLib' => 'Prestations de services',
                'CompAuxNum' => $codeComptable,
                'CompAuxLib' => $raisonSociale,
                'PieceRef' => $facture->getInvoiceNumber(),
                'PieceDate' => $facture->getCreatedAt()->format('Y-m-d'),
                'EcritureLib' => self::PREFIX_FACTURE.$facture->getInvoiceNumber().' - '.$raisonSociale,
                'Debit' => '0.00',
                'Credit' => $facture->getTotalHt(),
                'Lettrage' => '',
                'DateLettrage' => '',
                'ValidDate' => $facture->getCreatedAt()->format('Y-m-d'),
                'MontantDevise' => '',
                'Idevise' => 'EUR',
            ];
            $rows[] = $row;

            if ($tvaEnabled && (float) $facture->getTotalTva() > 0) {
                $rowTva = $row;
                $rowTva['CompteNum'] = '445710';
                $rowTva['CompteLib'] = 'TVA collectee';
                $rowTva['EcritureLib'] = 'TVA Facture '.$facture->getInvoiceNumber();
                $rowTva['Debit'] = '0.00';
                $rowTva['Credit'] = $facture->getTotalTva();
                $rows[] = $rowTva;
            }

            $rowClient = $row;
            $rowClient['CompteNum'] = $codeComptable;
            $rowClient['CompteLib'] = $raisonSociale;
            $rowClient['EcritureLib'] = 'Client '.$raisonSociale.' - Facture '.$facture->getInvoiceNumber();
            $rowClient['Debit'] = $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt();
            $rowClient['Credit'] = '0.00';
            $rows[] = $rowClient;

            if ($facture->isPaid() && null !== $facture->getPaidAt()) {
                $compteBanque = $this->helper->resolveCompteBanque($facture->getPaidMethod());
                $rowPay = $row;
                $rowPay['JournalCode'] = 'BQ';
                $rowPay['JournalLib'] = 'Journal de banque';
                $rowPay['EcritureDate'] = $facture->getPaidAt()->format('Y-m-d');
                $rowPay['CompteNum'] = $compteBanque;
                $rowPay['CompteLib'] = $this->helper->resolveLibelleBanque($facture->getPaidMethod());
                $rowPay['EcritureLib'] = 'Reglement Facture '.$facture->getInvoiceNumber().' - '.$raisonSociale;
                $rowPay['Debit'] = $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt();
                $rowPay['Credit'] = '0.00';
                $rowPay['PieceDate'] = $facture->getPaidAt()->format('Y-m-d');
                $rowPay['ValidDate'] = $facture->getPaidAt()->format('Y-m-d');
                $rows[] = $rowPay;

                $rowPayClient = $rowPay;
                $rowPayClient['CompteNum'] = $codeComptable;
                $rowPayClient['CompteLib'] = $raisonSociale;
                $rowPayClient['EcritureLib'] = 'Reglement Client '.$raisonSociale;
                $rowPayClient['Debit'] = '0.00';
                $rowPayClient['Credit'] = $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt();
                $rows[] = $rowPayClient;
            }
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildGrandLivreData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $tvaEnabled = $this->tvaEnabled;
        $factures = $this->helper->getFactures($from, $to);
        $rows = [];

        foreach ($factures as $facture) {
            $customer = $facture->getCustomer();
            [$codeComptable, $raisonSociale] = $this->helper->resolveCustomerInfo($customer);
            $montant = $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt();

            $rows[] = [
                'CompteNum' => $codeComptable,
                'CompteLib' => $raisonSociale,
                'EcritureNum' => $facture->getInvoiceNumber(),
                'EcritureDate' => $facture->getCreatedAt()->format('Y-m-d'),
                'EcritureLib' => self::PREFIX_FACTURE.$facture->getInvoiceNumber(),
                'Debit' => $montant,
                'Credit' => '0.00',
                'Solde' => $montant,
                'Lettrage' => $facture->isPaid() ? 'LET' : '',
                'DateLettrage' => $facture->isPaid() && $facture->getPaidAt() ? $facture->getPaidAt()->format('Y-m-d') : '',
                'PieceRef' => $facture->getInvoiceNumber(),
                'CodeJournal' => 'VE',
                'Statut' => $facture->isPaid() ? 'Paye' : 'Impaye',
                'MethodePaiement' => $facture->getPaidMethod() ?? '',
                'DatePaiement' => $facture->getPaidAt()?->format('Y-m-d') ?? '',
            ];
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildFecData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $tvaEnabled = $this->tvaEnabled;
        $factures = $this->helper->getFactures($from, $to);
        $rows = [];
        $ecritureNum = 1;

        foreach ($factures as $facture) {
            $customer = $facture->getCustomer();
            [$codeComptable, $raisonSociale] = $this->helper->resolveCustomerInfo($customer);
            $numEcriture = sprintf('VE%06d', $ecritureNum);

            $rows[] = [
                'JournalCode' => 'VE',
                'JournalLib' => self::LABEL_JOURNAL_VENTES,
                'EcritureNum' => $numEcriture,
                'EcritureDate' => $facture->getCreatedAt()->format('Ymd'),
                'CompteNum' => $codeComptable,
                'CompteLib' => $raisonSociale,
                'CompAuxNum' => $codeComptable,
                'CompAuxLib' => $raisonSociale,
                'PieceRef' => $facture->getInvoiceNumber(),
                'PieceDate' => $facture->getCreatedAt()->format('Ymd'),
                'EcritureLib' => self::PREFIX_FACTURE.$facture->getInvoiceNumber(),
                'Debit' => number_format($tvaEnabled ? (float) $facture->getTotalTtc() : (float) $facture->getTotalHt(), 2, '.', ''),
                'Credit' => '0.00',
                'EcrtureLet' => $facture->isPaid() ? 'AA' : '',
                'DateLet' => $facture->isPaid() && $facture->getPaidAt() ? $facture->getPaidAt()->format('Ymd') : '',
                'ValidDate' => $facture->getCreatedAt()->format('Ymd'),
                'Montantdevise' => '',
                'Idevise' => '',
            ];

            $rows[] = [
                'JournalCode' => 'VE',
                'JournalLib' => self::LABEL_JOURNAL_VENTES,
                'EcritureNum' => $numEcriture,
                'EcritureDate' => $facture->getCreatedAt()->format('Ymd'),
                'CompteNum' => '706000',
                'CompteLib' => 'Prestations de services',
                'CompAuxNum' => '',
                'CompAuxLib' => '',
                'PieceRef' => $facture->getInvoiceNumber(),
                'PieceDate' => $facture->getCreatedAt()->format('Ymd'),
                'EcritureLib' => self::PREFIX_FACTURE.$facture->getInvoiceNumber(),
                'Debit' => '0.00',
                'Credit' => $facture->getTotalHt(),
                'EcrtureLet' => '',
                'DateLet' => '',
                'ValidDate' => $facture->getCreatedAt()->format('Ymd'),
                'Montantdevise' => '',
                'Idevise' => '',
            ];

            if ($tvaEnabled && (float) $facture->getTotalTva() > 0) {
                $rows[] = [
                    'JournalCode' => 'VE',
                    'JournalLib' => self::LABEL_JOURNAL_VENTES,
                    'EcritureNum' => $numEcriture,
                    'EcritureDate' => $facture->getCreatedAt()->format('Ymd'),
                    'CompteNum' => '445710',
                    'CompteLib' => 'TVA collectee',
                    'CompAuxNum' => '',
                    'CompAuxLib' => '',
                    'PieceRef' => $facture->getInvoiceNumber(),
                    'PieceDate' => $facture->getCreatedAt()->format('Ymd'),
                    'EcritureLib' => 'TVA Facture '.$facture->getInvoiceNumber(),
                    'Debit' => '0.00',
                    'Credit' => $facture->getTotalTva(),
                    'EcrtureLet' => '',
                    'DateLet' => '',
                    'ValidDate' => $facture->getCreatedAt()->format('Ymd'),
                    'Montantdevise' => '',
                    'Idevise' => '',
                ];
            }

            ++$ecritureNum;
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildBalanceAgeeData(): array
    {
        $tvaEnabled = $this->tvaEnabled;
        $now = new \DateTimeImmutable();

        $factures = $this->em->createQueryBuilder()
            ->select('f')
            ->from(Facture::class, 'f')
            ->where('f.isPaid = false')
            ->andWhere('f.state != :cancel')
            ->setParameter('cancel', Facture::STATE_CANCEL)
            ->orderBy('f.createdAt', 'ASC')
            ->getQuery()
            ->getResult();

        $rows = [];
        foreach ($factures as $facture) {
            $customer = $facture->getCustomer();
            [$codeComptable, $raisonSociale] = $this->helper->resolveCustomerInfo($customer);
            $joursRetard = $facture->getCreatedAt()->diff($now)->days;

            $rows[] = [
                'CodeComptable' => $codeComptable,
                'Client' => $raisonSociale,
                'NumFacture' => $facture->getInvoiceNumber(),
                'DateFacture' => $facture->getCreatedAt()->format('Y-m-d'),
                'MontantHT' => $facture->getTotalHt(),
                'MontantTVA' => $tvaEnabled ? $facture->getTotalTva() : '0.00',
                'MontantTTC' => $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt(),
                'JoursRetard' => (string) $joursRetard,
                'Tranche' => $this->helper->resolveTrancheAge($joursRetard),
                'Statut' => $facture->getState(),
            ];
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildReglementsData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $tvaEnabled = $this->tvaEnabled;

        $factures = $this->em->createQueryBuilder()
            ->select('f')
            ->from(Facture::class, 'f')
            ->where(self::DQL_IS_PAID)
            ->andWhere('f.paidAt BETWEEN :from AND :to')
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->orderBy('f.paidAt', 'ASC')
            ->getQuery()
            ->getResult();

        $rows = [];
        foreach ($factures as $facture) {
            $customer = $facture->getCustomer();
            [$codeComptable, $raisonSociale] = $this->helper->resolveCustomerInfo($customer);

            $rows[] = [
                'DateReglement' => $facture->getPaidAt()->format('Y-m-d'),
                'CodeComptable' => $codeComptable,
                'Client' => $raisonSociale,
                'NumFacture' => $facture->getInvoiceNumber(),
                'MontantHT' => $facture->getTotalHt(),
                'MontantTVA' => $tvaEnabled ? $facture->getTotalTva() : '0.00',
                'MontantTTC' => $tvaEnabled ? $facture->getTotalTtc() : $facture->getTotalHt(),
                'MethodePaiement' => $facture->getPaidMethod() ?? 'inconnu',
                'CompteBanque' => $this->helper->resolveCompteBanque($facture->getPaidMethod()),
            ];
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildCommissionsStripeData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $payments = $this->em->createQueryBuilder()
            ->select('p')
            ->from(AdvertPayment::class, 'p')
            ->where('p.createdAt BETWEEN :from AND :to')
            ->andWhere('p.type = :type')
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->setParameter('type', AdvertPayment::TYPE_SUCCESS)
            ->orderBy('p.createdAt', 'ASC')
            ->getQuery()
            ->getResult();

        $rows = [];
        foreach ($payments as $p) {
            $amount = (float) $p->getAmount();
            $commission = round($amount * self::STRIPE_COMMISSION_RATE + self::STRIPE_FIXED_FEE, 2);
            $advert = $p->getAdvert();
            $customer = $advert->getCustomer();

            $rows[] = [
                'Date' => $p->getCreatedAt()->format('Y-m-d'),
                'NumAvis' => $advert->getOrderNumber()->getNumOrder(),
                'Client' => $customer?->getRaisonSociale() ?? ($customer ? $customer->getFirstName().' '.$customer->getLastName() : 'N/A'),
                'Methode' => $p->getMethod() ?? 'inconnu',
                'MontantTTC' => number_format($amount, 2, '.', ''),
                'TauxCommission' => number_format(self::STRIPE_COMMISSION_RATE * 100, 1).'% + '.number_format(self::STRIPE_FIXED_FEE, 2).'E',
                'CommissionStripe' => number_format($commission, 2, '.', ''),
                'NetPercu' => number_format($amount - $commission, 2, '.', ''),
            ];
        }

        return $rows;
    }

    /**
     * @return list<array<string, string>>
     */
    public function buildCoutsServicesData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $grouped = $this->groupFactureLinesByType($from, $to);
        $serviceGroups = $this->helper->getServiceGroups();

        $rows = [];
        $totalCout = 0.0;
        $totalCa = 0.0;

        foreach ($serviceGroups as $group) {
            [$caHt, $cout] = $this->helper->aggregateServiceGroup($group, $grouped);
            $marge = $caHt - $cout;
            $totalCout += $cout;
            $totalCa += $caHt;

            $rows[] = [
                'Service' => $group['name'],
                'CA_HT' => number_format($caHt, 2, '.', ''),
                'Cout_Ecosplay' => number_format($cout, 2, '.', ''),
                'Marge' => number_format($marge, 2, '.', ''),
                'Statut' => $this->helper->resolveStatutRentabilite($caHt, $marge),
            ];
        }

        $this->appendPrestataireRows($from, $to, $rows, $totalCout);

        $rows[] = [
            'Service' => 'TOTAL',
            'CA_HT' => number_format($totalCa, 2, '.', ''),
            'Cout_Ecosplay' => number_format($totalCout, 2, '.', ''),
            'Marge' => number_format($totalCa - $totalCout, 2, '.', ''),
            'Statut' => ($totalCa - $totalCout) >= 0 ? 'Rentable' : 'Negatif',
        ];

        return $rows;
    }

    /**
     * Regroupe les lignes de facture par type de service sur la periode.
     *
     * @return array<string, array{ca_ht: float, lines: int}>
     */
    public function groupFactureLinesByType(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $factures = $this->em->createQueryBuilder()
            ->select('f')
            ->from(Facture::class, 'f')
            ->where(self::DQL_BETWEEN_DATES)
            ->andWhere(self::DQL_IS_PAID)
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->orderBy('f.createdAt', 'ASC')
            ->getQuery()
            ->getResult();

        return $this->groupFactureLinesByTypeFromList($factures);
    }

    /**
     * Groupe les lignes de factures fournies par type de service.
     *
     * @param list<Facture> $factures
     *
     * @return array<string, array{ca_ht: float, lines: int}>
     */
    public function groupFactureLinesByTypeFromList(array $factures): array
    {
        $grouped = [];
        foreach (self::SERVICE_COSTS as $type => $config) {
            $grouped[$type] = ['ca_ht' => 0.0, 'lines' => 0];
        }

        foreach ($factures as $facture) {
            foreach ($facture->getLines() as $line) {
                $type = $line->getType() ?? 'other';
                if (!isset($grouped[$type])) {
                    $type = 'other';
                }
                $grouped[$type]['ca_ht'] += (float) $line->getPriceHt();
                $title = $line->getTitle();
                if ('ndd' !== $type || str_contains($title, 'Renouvellement') || str_contains($title, 'Depot')) {
                    ++$grouped[$type]['lines'];
                }
            }
        }

        return $grouped;
    }

    /**
     * Calcule le total des commissions Stripe sur la periode.
     */
    public function computeStripeCommissions(\DateTimeImmutable $from, \DateTimeImmutable $to): float
    {
        $payments = $this->em->createQueryBuilder()
            ->select('p')
            ->from(AdvertPayment::class, 'p')
            ->where('p.createdAt BETWEEN :from AND :to')
            ->andWhere('p.type = :type')
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->setParameter('type', AdvertPayment::TYPE_SUCCESS)
            ->getQuery()
            ->getResult();

        $total = 0.0;
        foreach ($payments as $p) {
            $total += round((float) $p->getAmount() * self::STRIPE_COMMISSION_RATE + self::STRIPE_FIXED_FEE, 2);
        }

        return $total;
    }

    /**
     * Calcule le cout total des services a partir de factures fournies.
     *
     * @param list<Facture> $factures
     */
    public function computeServiceCostsFromFactures(array $factures): float
    {
        $grouped = $this->groupFactureLinesByTypeFromList($factures);
        $cost = 0.0;

        foreach ($this->helper->getServiceGroups() as $group) {
            [, $cout] = $this->helper->aggregateServiceGroup($group, $grouped);
            $cost += $cout;
        }

        return $cost;
    }

    /**
     * Ajoute les lignes prestataires aux resultats et met a jour le cout total.
     *
     * @param list<array<string, string>> $rows
     */
    private function appendPrestataireRows(\DateTimeImmutable $from, \DateTimeImmutable $to, array &$rows, float &$totalCout): void
    {
        $facturesPresta = $this->em->createQueryBuilder()
            ->select('fp')
            ->from(FacturePrestataire::class, 'fp')
            ->where('fp.createdAt BETWEEN :from AND :to')
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->orderBy('fp.createdAt', 'ASC')
            ->getQuery()
            ->getResult();

        $prestaGrouped = [];
        foreach ($facturesPresta as $fp) {
            $name = $fp->getPrestataire()->getRaisonSociale();
            if (!isset($prestaGrouped[$name])) {
                $prestaGrouped[$name] = 0.0;
            }
            $prestaGrouped[$name] += (float) $fp->getMontantHt();
        }

        foreach ($prestaGrouped as $prestaName => $prestaTotal) {
            $totalCout += $prestaTotal;
            $rows[] = [
                'Service' => 'Prestataire : '.$prestaName,
                'CA_HT' => '0.00',
                'Cout_Ecosplay' => number_format($prestaTotal, 2, '.', ''),
                'Marge' => number_format(-$prestaTotal, 2, '.', ''),
                'Statut' => 'Depense',
            ];
        }
    }

    /**
     * Export des echeanciers et de leurs echeances sur la periode.
     *
     * @return list<array<string, string>>
     */
    public function buildEcheancierData(\DateTimeImmutable $from, \DateTimeImmutable $to): array
    {
        $echeanciers = $this->em->createQuery(
            'SELECT e FROM App\Entity\Echeancier e
             WHERE e.createdAt BETWEEN :from AND :to
             ORDER BY e.createdAt ASC'
        )
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->getResult();

        $rows = [];
        $stateLabels = [
            Echeancier::STATE_DRAFT => 'Brouillon',
            Echeancier::STATE_SEND => 'Envoye',
            Echeancier::STATE_SIGNED => 'Signe',
            Echeancier::STATE_PENDING_SETUP => 'En attente SEPA',
            Echeancier::STATE_ACTIVE => 'Actif',
            Echeancier::STATE_COMPLETED => 'Termine',
            Echeancier::STATE_CANCELLED => 'Annule',
            Echeancier::STATE_DEFAULT => 'Defaut',
        ];

        /** @var Echeancier $echeancier */
        foreach ($echeanciers as $echeancier) {
            $customer = $echeancier->getCustomer();
            $remaining = $echeancier->getTotalWithMajoration() - $echeancier->getTotalPaid();

            // Compter les paiements AdvertPayment lies a cet echeancier
            $advertPayments = $this->em->getRepository(AdvertPayment::class)->findBy(['echeancier' => $echeancier]);
            $nbAdvertPayments = \count($advertPayments);
            $totalAdvertPayments = 0.0;
            foreach ($advertPayments as $ap) {
                $totalAdvertPayments += (float) $ap->getAmount();
            }

            /** @var EcheancierLine $line */
            foreach ($echeancier->getLines() as $line) {
                $lineState = match ($line->getState()) {
                    EcheancierLine::STATE_OK => 'Paye',
                    EcheancierLine::STATE_KO => 'Echoue',
                    default => 'En attente',
                };

                $rows[] = [
                    'Reference' => $echeancier->getReference(),
                    'Client' => $customer->getFullName(),
                    'Email' => $customer->getEmail() ?? '',
                    'Statut echeancier' => $stateLabels[$echeancier->getState()] ?? $echeancier->getState(),
                    'Motif' => $echeancier->getDescription(),
                    'Creance HT' => number_format((float) $echeancier->getTotalAmountHt(), 2, '.', ''),
                    'Majoration' => number_format($echeancier->getMajoration(), 2, '.', ''),
                    'Total majore' => number_format($echeancier->getTotalWithMajoration(), 2, '.', ''),
                    'Total paye' => number_format($echeancier->getTotalPaid(), 2, '.', ''),
                    'Restant du' => number_format($remaining, 2, '.', ''),
                    'Nb paiements' => (string) $nbAdvertPayments,
                    'Total paiements avis' => number_format($totalAdvertPayments, 2, '.', ''),
                    'Echeance N' => (string) $line->getPosition(),
                    'Date prevue' => $line->getScheduledAt()->format(self::DATE_FORMAT_FR),
                    'Montant echeance' => number_format((float) $line->getAmount(), 2, '.', ''),
                    'Statut echeance' => $lineState,
                    'Paye le' => null !== $line->getPaidAt() ? $line->getPaidAt()->format(self::DATE_FORMAT_FR) : '',
                    'Stripe PI' => $line->getStripePaymentIntentId() ?? '',
                    'Avis lie' => null !== $echeancier->getAdvert() ? $echeancier->getAdvert()->getOrderNumber()->getNumOrder() : '',
                ];
            }
        }

        return $rows;
    }
}
