?? GreyFile — Mystic File Browser

Current path: home/webdevt/cryptoimpot.fr/module/Application/src/Controller/



?? Go up: /home/webdevt/cryptoimpot.fr/module/Application/src

?? Viewing: RapportControllerOkMars2021.php

<?php

namespace Application\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Laminas\Mail\Message;
use Laminas\Mime;
use Laminas\Mail\Transport\Sendmail as SendmailTransport;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class RapportController extends AbstractActionController
{

    const ROUTE_APERCU = 'rapport/apercu';
    const ROUTE_DOWNLOAD = 'rapport/download';
    const ROUTE_GENERATE = 'rapport/generate';
    const ROUTE_VALIDATION_COMMANDE = 'rapport/validation-commande';

    /**
     * @var \TCPDF
     */
    protected $tcpdf;

    /**
     * @var RendererInterface
     */
    protected $renderer;

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $entityManager;

//    public function setEntityManager(EntityManager $em) {
//        $this->em = $em;
//    }
//
//    public function getEntityManager() {
//        if (null === $this->em) {
//            $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
//        }
//        return $this->em;
//    }
//
//    public function getServiceManager() {
//        return $this->serviceManager;
//    }
//
//    public function setServiceManager(Laminas\ServiceManager\ServiceManager $serviceManager) {
//        $this->serviceManager = $serviceManager;
//        return $this;
//    }

    /**
     * Constructor.
     */
    public function __construct($entityManager, $authManager, $userManager, $config, $tcpdfRapport, $tcpdfBrouillon, $fpdiFormulaire2048m, $renderer)
    {

        $this->entityManager = $entityManager;
        $this->authManager = $authManager;
        $this->userManager = $userManager;
        $this->config = $config;
        $this->tcpdf = $tcpdfRapport;
        $this->fpdiFormulaire2048m = $fpdiFormulaire2048m;
        $this->tcpdfBrouillon = $tcpdfBrouillon;
        $this->renderer = $renderer;

    }

    public function indexAction()
    {
        if ($user = $this->currentUser()) {

        } else {
            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        }

        $entityManager = $this->getEntityManager();
        /* @var $entityManager \Doctrine\ORM\EntityManager */
        $ledgioMapper = new \Application\Mapper\LedgioMapper($entityManager);


        $arrayRapportDispo = [];
        foreach (range('2011', date('Y') - 1) as $anneeCheck) {
            echo $anneeCheck;
            $countInvestFiatByUserAndYear = $ledgioMapper->countInvestFiatByUserAndYear($user, $anneeCheck);
            $countSessionFiatByUserAndYear = $ledgioMapper->countSessionFiatByUserAndYear($user, $anneeCheck);
//            $countTrade = $ledgioMapper->countTradeByUser($user)
            $countTradeByUserAndYear = $ledgioMapper->countTradeByUser($user, 'all', 'all', $year = $anneeCheck);
            if (!empty($countTradeByUserAndYear)) {
                $arrayRapportDispo[] = [
                    //'arrayExhanges' => $arrayExhanges,
                    'countInvestFiatByUserAndYear' => $countInvestFiatByUserAndYear,
                    'countSessionFiatByUserAndYear' => $countSessionFiatByUserAndYear,
                    'countTradeByUserAndYear' => $countTradeByUserAndYear,
                    'year' => $anneeCheck
                ];
            }

        }


        //$countTradeOut = $ledgioMapper->countTradeOutByUser($user);
        //var_dump($countTrade); exit;

        return new ViewModel(array(
            //'arrayExhanges' => $arrayExhanges,
            'arrayRapportDispo' => $arrayRapportDispo,
//            'countInvestFiatByUserAndYear' => $countInvestFiatByUserAndYear,
//            'countSessionFiatByUserAndYear' => $countSessionFiatByUserAndYear,
//            'countTrade' => $countTrade,
        ));
    }

//    public function getConfig() {
//        return $this->config;
//    }

    public function getEntityManager()
    {
        return $this->entityManager;
//        if (null === $this->em) {
//            $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
//        }
//        return $this->em;
    }

//    public function rapportAction()
//    {
//
////        if ($this->zfcUserAuthentication()->hasIdentity()) {
////            $user = $this->zfcUserAuthentication()->getIdentity();
////            //var_dump($user);
////        } else {
////            return $this->redirect()->toRoute('zfcuser', array('action' => 'login'));
////        }
//        if ($user = $this->currentUser()) {
//
//        } else {
//            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
//        }
//
//        //$mapperUserExchangeLinker = new \Application\Mapper\UserExchangeLinkerMapper($this->getEntityManager());
//        // calcul plus value
//        $ledgioService = new \Application\Service\LedgioService($user, $this->getEntityManager(), $this->config);
//
//
//        reportByYear
//        $ledgioService->report();
//
//
////        $exchange = $mapperUserExchangeLinker->findByUser($user);
////        $arrayExhanges = array();
////        //var_dump($exchange->getExchangesId());
////        if (!empty($exchange && $exchange->getExchangesId())) {
////            $arrayIdExhanges = explode(',', $exchange->getExchangesId());
////            $mapperExchange = new \Application\Mapper\ExchangeMapper($this->getEntityManager());
////
////            foreach ($arrayIdExhanges as $id) {
////                $arrayExhanges[] = $mapperExchange->findById($id);
////            }
////        }
//
//
//        $this->layout('layout/layout-ledgio');
//
//        $view = new ViewModel(
//            ['array' => $ledgioService->getArrayRapportAnnexePrincipale()
//            ]);
////$view->setTemplate('rapport-pdf');
//
//
//        $renderer = $this->renderer;
//        $view->setTemplate('layout/rapport');
//        $html = $renderer->render($view);
//
//        $pdf = $this->tcpdf;
//
//
//        //$pdf->SetFont('arialnarrow', '', 12, '', false);
//        $pdf->AddPage('L');
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//        //$pdf->Output();
//
//        $pdf->Output('kuitti' . $ordernumber . '.pdf', 'F');
//
//
////        return new ViewModel(array(
////            'arrayExhanges' => $arrayExhanges,
//////            'listeOffresEmploi' => $listeOffresEmploi,
//////            'nbIngenieurs' => $config['wdp-front-global']['nbIngenieurs'],
////        ));
//    }

    public function generateAction()
    {

//echo 'toto'; exit;
//        phpinfo();
//        exit;
        if ($user = $this->currentUser()) {

        } else {
            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        }
        //$mapperUserExchangeLinker = new \Application\Mapper\UserExchangeLinkerMapper($this->getEntityManager());


        $entityManager = $this->getEntityManager();

        /* @var $entityManager \Doctrine\ORM\EntityManager */

        $reportMapper = new \Application\Mapper\ReportMapper($entityManager);

        $year = $this->params()->fromRoute('year', null);

//

        $reportFind = $reportMapper->findByYearAndUser($year, $user);

        //var_dump($reportFind); exit;

        if (!$reportFind || $reportFind->isNotValidated()) {


            goto generate;
        } else {
            //exit;
            goto display;
        }

        generate:

//        echo 'titi'; exit;
        // calcul plus value

        $this->config['anneeImposition'] = $year;

        $ledgioService = new \Application\Service\LedgioService($user, $this->getEntityManager(), $this->config);

//        $ledgioService->report();
        $ledgioService->reportByYear();


        if ($year < 2019) {
            // ini_set('max_execution_time', 0);
            $filePath = $ledgioService->outputDir . 'annexe-declaration-fiscale-crypto-monnaies-' . $year . '-' . date('d-m-Y') . '.pdf';

            $view = new ViewModel([
                'arrayTransactionsImposable2048m' => $ledgioService->getArrayTransactionsImposable2048m(),
                'alldetailAchatParCession2048m' => $ledgioService->getAlldetailAchatParCession2048m(),
                'arrayAcquisitionBefore2019' => $ledgioService->getarrayAcquisitionBefore2019(),
                'arrayDetailFusionLigneMemeDateMemeAsset' => $ledgioService->getArrayDetailFusionLigneMemeDateMemeAsset(),
                'annee' => $year
            ]);

            foreach ($ledgioService->getArrayTransactionsImposable2048m() as $key => $transaction) {
//$key=0;
                $filePathFormulaire = $ledgioService->outputDir . 'declaration-n' . ($key + 1) . 'fiscale-crypto-monnaies-' . $year . '-' . date('d-m-Y') . '.pdf';
//echo $filePathFormulaire; exit;
                /* @var $pdf \Application\Service\FPDIFormulaire2048m */
                $pdf = clone $this->fpdiFormulaire2048m;


                //$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
                $pdf->SetCreator(PDF_CREATOR);
                $pdf->SetAuthor('Marc');
                $pdf->SetTitle('2048m');
                $pdf->SetSubject('2048m');
                $pdf->SetKeywords('2048m');

// set header and footer fonts
                $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));

// set default monospaced font
                $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
                $pdf->SetMargins(0, 0, 0);
                $pdf->SetHeaderMargin(0);
                $pdf->SetFooterMargin(0);

// remove default footer
                $pdf->setPrintFooter(false);

// set auto page breaks
                $pdf->SetAutoPageBreak(TRUE, 0);

// set image scale factor
                $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
//            if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
//                require_once(dirname(__FILE__).'/lang/eng.php');
//                $pdf->setLanguageArray($l);
//            }

// ---------------------------------------------------------

// set font
                $pdf->SetFont('times', '', 48);

// add a page

                // page 1
                $pdf->AddPage();
                // nom
                //$pdf->Cell(30, 0, 'Bottom-Bottom', 1, $ln=0, 'C', 0, '', 0, false, 'B', 'B');
// Print a text

                $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                $pdf->SetAutoPageBreak(false, 0);

                $img_file = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-1.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-1.jpg' : $this->config['path-app'] . '/public/form/2048-2020-1.jpg';
                $pdf->Image($img_file, 0, 0, 210, 297, 'JPG', '', 'M', true, 300, 'C', false, false, 0);

                $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
// set the starting point for the page content
                $pdf->setPageMark();

                $pdf->SetFont('helvetica', '', 11);
                $pdf->setCellHeightRatio(1);
                $pdf->SetLineWidth(0);

                // Rédacteur de l'acte ne pas remplir
                $pdf->SetXY(20, 56);
                $pdf->Cell(150, 0, '', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(24, 62);
                $pdf->Cell(150, 0, '', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(34, 67);
                $pdf->Cell(150, 0, '', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(36, 72);
                $pdf->Cell(150, 0, '', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');


                // Désignation du cédant
                $pdf->SetXY(68, 85);
                $pdf->Cell(150, 0, 'Jean Dupont', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(38, 90);
                $pdf->Cell(150, 0, '03/10/1979', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(60, 95);
                $pdf->Cell(150, 0, 'rue de la mer 14360', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');


                $pdf->SetXY(20, 100);
                $pdf->Cell(150, 0, 'FRANCE', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
                $pdf->SetXY(34, 105);
                $pdf->Cell(150, 0, 'jimmy@gmail.com', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            $pdf->SetXY(48, 178);
            $pdf->Cell(150, 0, 'crypto-actif', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');


            // Renseignements relatifs à la cession
                // Nature et date du transfert
                $pdf->SetXY(65, 238);
                $pdf->Cell(150, 0, 'Cession de crypto-actif le ' . $transaction['datetime']->format('d/m/Y'), 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
//                $pdf->Cell(150, 0, 'Cession de crypto-actif le ' . date('d/m/Y'), 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

                // Nom acquéreur
                $pdf->SetXY(60, 243);
                $pdf->Cell(150, 0, 'Non identifiable', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

                // Adresse acquéreur
                $pdf->SetXY(62, 248);
                $pdf->Cell(150, 0, 'Non identifiable', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            // SIREN
            $pdf->SetXY(53, 253);
            $pdf->Cell(150, 0, 'Non identifiable', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');


            // Origine de propriété
            $pdf->SetXY(49, 267);
//            $pdf->Cell(150, 0, dateacquisitionmoyen ????, 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');
            $pdf->Cell(150, 0, date('d  m  Y'), 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

// indivision ?
            $pdf->SetXY(70.68, 273.7);
            $pdf->Cell(150, 0, 'x', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            // mode acquisition ?
            $pdf->SetXY(105.3, 268.34);
            $pdf->Cell(150, 0, 'x', 0, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            // page 2
                $pdf->AddPage();

                $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                $pdf->SetAutoPageBreak(false, 0);

                $img_file2 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-2.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-2.jpg' : $this->config['path-app'] . '/public/form/2048-2020-2.jpg';

                $pdf->Image($img_file2, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                // set the starting point for the page content
                $pdf->setPageMark();
// Print a text

                $pdf->SetFont('helvetica', '', 11);
                $pdf->setCellHeightRatio(1);
                $pdf->SetLineWidth(0);

                // 101 Prix de cession
                $a101 =  number_format($transaction['priceEUR'],2, '.', '');
//                $a101 = 101;
                $pdf->SetXY(131, 36);
                $pdf->Cell(30, 0, $a101, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                // 102 Sommes à ajouter au prix de cession
                $a102 = 0;
                $pdf->SetXY(131, 43);
                $pdf->Cell(30, 0, $a102, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                // 103 Frais de cession
                $a103 =  number_format($transaction['fraisCession'], 2, '.', '');
//                $a103 = number_format(1037655765.25654, 2, '.', '');
                $pdf->SetXY(131, 51);
                $pdf->Cell(30, 0, $a103, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                // 104 = 101 + 102 - 103 Prix de cession corrigé
                $a104 = $a101 + $a102 - $a103;
                $pdf->SetXY(166, 58);
                $pdf->Cell(30, 0, $a104, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');


                // 105 Prix acquisition
                $a105 =  number_format($transaction['totalEURAcquisitionFIFO'], 2, '.', '');
//                $a105 =  number_format(10590909.5657, 2, '.', '');
                $pdf->SetXY(131, 65);
                $pdf->Cell(30, 0, $a105, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

// 106 Frais d'acquisition
                $a106 = 0; // @todo ajouter frais
                $pdf->SetXY(131, 72);
                $pdf->Cell(30, 0, $a106, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

// 107 Frais de restauration
                $a107 = 0;
                $pdf->SetXY(131, 79);
                $pdf->Cell(30, 0, $a107, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

// 108 Prix d'acquisition corrigé 105 + 106 + 107
                $a108 = $a105 + $a106 + $a107;
                $pdf->SetXY(166, 87);
                $pdf->Cell(30, 0, $a108, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                // 110 Plus value brute 104 - 108
                $a110 = $a104 - $a108;
                $pdf->SetXY(166, 94);
                $pdf->Cell(30, 0, $a110, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

// 121 Nb année détention au delà 2eme année
                $a121 = ($transaction['moyenneAnneeAquisition'] - 2 < 0) ? 0 : ($transaction['moyenneAnneeAquisition'] - 2);
//                $a121 = 0;
                $pdf->SetXY(132, 114);
                $pdf->Cell(30, 0, $a121, 1, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

// 122 Tx de reduction 121 x 5%

                $a122 =  number_format($a121 * 5 / 100, 2, '.', '');
                $pdf->SetXY(130, 121);
                $pdf->Cell(30, 0, $a122, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');
// 123 Montant de la réduction 110 x 122
                $a123 =  number_format($a110 * $a122, 2, '.', '');
                $pdf->SetXY(166, 129);
                $pdf->Cell(30, 0, $a123, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                // 130 Plus-value nette imposable 110 - 123
                $a130 = $a110 - $a123;
                $pdf->SetXY(166, 136);
                $pdf->Cell(30, 0, $a130, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                if ($year == 2017) {
                    // 140
                    $a140 =  number_format($a130 * 19 / 100, 2, '.', '');
                    $pdf->SetXY(166, 151);
                    $pdf->Cell(30, 0, $a140, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                    // 141
                    $a141 =  number_format($a130 * 8.2 / 100, 2, '.', '');
                    $pdf->SetXY(166, 158);
                    $pdf->Cell(30, 0, $a141, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                    // 142
                    $a142 = number_format($a130 * 0.5 / 100, 2, '.', '');
                    $pdf->SetXY(166, 165);
                    $pdf->Cell(30, 0, $a142, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                    // 143
                    $a143 = number_format($a130 * 4.5 / 100, 2, '.', '');
                    $pdf->SetXY(166, 173);
                    $pdf->Cell(30, 0, $a143, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                    // 144
                    $a144 = number_format($a130 * 0.3 / 100, 2, '.', '');
                    $pdf->SetXY(166, 180);
                    $pdf->Cell(30, 0, $a144, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                    // 145
                    $a145 = number_format($a130 * 2 / 100, 2, '.', '');
                    $pdf->SetXY(166, 187);
                    $pdf->Cell(30, 0, $a145, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

//Total 140 + 141 + 142 + 143 + 144 + 145

                    $totalAPayer = $a140 + $a141 + $a142 + $a143 + $a144 + $a145;
                    $pdf->SetXY(167, 208.5);
                    $pdf->Cell(30, 0, $totalAPayer, 0, $ln = 0, 'R', 0, '', 0, false, 'T', 'C');

                }

            $faitA = 'Paris';
            $pdf->SetXY(14, 225);
            $pdf->Cell(30, 0, $faitA, 1, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            $faitLe = date('d   m   Y');
            $pdf->SetXY(77, 225);
            $pdf->Cell(30, 0, $faitLe, 1, $ln = 0, 'L', 0, '', 0, false, 'T', 'C');

            // page 3
                $pdf->AddPage();

                $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-pagex-break
                $pdf->SetAutoPageBreak(false, 0);


                $img_file3 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-3.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-3.jpg' : $this->config['path-app'] . '/public/form/2048-2020-3.jpg';

//                $img_file3 = $this->config['path-app'] . '/public/form/2048-m-sd_2950-3.jpg';
                $pdf->Image($img_file3, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                // set the starting point for the page content
                $pdf->setPageMark();
// Print a text


                // page 4
                $pdf->AddPage();

                $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                $pdf->SetAutoPageBreak(false, 0);

//                $img_file4 = $this->config['path-app'] . '/public/form/2048-m-sd_2950-4.jpg';
                $img_file4 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-4.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-4.jpg' : $this->config['path-app'] . '/public/form/2048-2020-4.jpg';

                $pdf->Image($img_file4, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                // set the starting point for the page content
                $pdf->setPageMark();
// Print a text

                // page 5
                $pdf->AddPage();

                $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                $pdf->SetAutoPageBreak(false, 0);

//                $img_file5 = $this->config['path-app'] . '/public/form/2048-m-sd_2950-5.jpg';
                $img_file5 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-5.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-5.jpg' : $this->config['path-app'] . '/public/form/2048-2020-5.jpg';
                $pdf->Image($img_file5, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                // set the starting point for the page content
                $pdf->setPageMark();
// Print a text

                if ($year > 2016) {
                    // page 6
                    $pdf->AddPage();

                    $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                    $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                    $pdf->SetAutoPageBreak(false, 0);

//                    $img_file6 = $this->config['path-app'] . '/public/form/2048-m-sd_2950-6.jpg';
                    $img_file6 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-6.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-6.jpg' : $this->config['path-app'] . '/public/form/2048-2020-6.jpg';

                    $pdf->Image($img_file6, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                    $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                    // set the starting point for the page content
                    $pdf->setPageMark();
// Print a text

                    // page 7
                    $pdf->AddPage();

                    $bMargin = $pdf->getBreakMargin();
// get current auto-page-break mode
                    $auto_page_break = $pdf->getAutoPageBreak();
// disable auto-page-break
                    $pdf->SetAutoPageBreak(false, 0);

//                    $img_file7 = $this->config['path-app'] . '/public/form/2048-m-sd_2950-7.jpg';
                    $img_file7 = is_file($this->config['path-app'] . '/public/form/2048-' . $year . '-6.jpg') ? $this->config['path-app'] . '/public/form/2048-' . $year . '-6.jpg' : $this->config['path-app'] . '/public/form/2048-2020-6.jpg';

                    $pdf->Image($img_file7, 0, 0, 210, 297, 'JPG', '', 'M', false, 300, 'C', false, false, 0);

                    $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
                    // set the starting point for the page content
                    $pdf->setPageMark();
                }
                // fin boucle formulaire 2048
// Print a text

// --- example with background set on page ---

// remove default header
                $pdf->setPrintHeader(false);

// add a page


// ---------------------------------------------------------

//Close and output PDF document
                //$pdf->Output('example_051.pdf', 'I');

                $pdf->Output($filePathFormulaire, 'F');



            }


//            $pdfFormulaire->SetMargins(PDF_MARGIN_LEFT, 40, PDF_MARGIN_RIGHT);
//            $pdfFormulaire->SetAutoPageBreak(true, 40);
//
//// add a page
//            $pdfFormulaire->AddPage();

// get external file content
//            $utf8text = file_get_contents('tcpdf/examples/data/utf8test.txt', true);
//
//            $pdfFormulaire->SetFont('freeserif', '', 12);
//// now write some text above the imported page
//            $pdfFormulaire->Write(5, $utf8text);

            // $pdfFormulaire->Output();
//            $pdfFormulaire->Output($filePathFormulaire, 'F');
//echo 'ok';
//exit;
            $renderer = $this->renderer;
            $view->setTemplate('layout/rapport2048m');
            $html = $renderer->render($view);
            $pdf = $this->tcpdf;
            $pdf->titlePDFCustom = 'Annexe de la 2048m' . $year;
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('Ledgio');

            $pdf->SetTitle('Annexe de la 2048m' . $year);
            $pdf->SetSubject('Calcul des plus values');
            $pdf->AddPage('L');
            $pdf->SetFont('Helvetica', '', 8, '', 'false');

            // get the current page break margin
            $bMargin = $pdf->getBreakMargin();
            // get current auto-page-break mode
            $auto_page_break = $pdf->getAutoPageBreak();
            // disable auto-page-break
//        $pdf->SetAutoPageBreak(false, 0);
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
            $pdf->setPageMark();

            $pdf->writeHTML($html, true, false, true, false, '');
            $pdf->Output($filePath, 'F');

            if (is_file($filePath)) {


                if ($reportFind) {
                    $reportFind->setPath($filePath);
                    // $reportFind->setPathBrouillon($filePathBrouillon);
                    $reportFind->setCreatedDate(new \DateTime());

                    $reportMapper->update($reportFind);

                    if ($reportFind && is_file($reportFind->getPath())) {
                        echo 'true';
                        exit;
                    } else {
                        echo 'false';
                        exit;
                    }
                } else {
                    $report = new \Application\Entity\Report();
                    $report->setStatus(0);
                    $report->setYear($year);
                    $report->setUser($user);
                    $report->setPath($filePath);
                    // $report->setPathBrouillon($filePathBrouillon);
                    $report->setCreatedDate(new \DateTime());


                    $reportMapper->insert($report);

                    if ($report && is_file($report->getPath())) {
                        echo 'true';
                        exit;
                    } else {
                        echo 'false';
                        exit;
                    }
                }
            } else {
                echo 'false';
                exit;
            }

        } else {

            //$exchange = $mapperUserExchangeLinker->findByUser($user);
            //$arrayExhanges = $user->getExchanges();
            //var_dump($exchange->getExchangesId());
//        if (!empty($exchange && $exchange->getExchangesId())) {
//            $arrayIdExhanges = explode(',', $exchange->getExchangesId());
//            $mapperExchange = new \Application\Mapper\ExchangeMapper($this->getEntityManager());
//
//            foreach ($arrayIdExhanges as $id) {
//                $arrayExhanges[] = $mapperExchange->findById($id);
//            }
//        }


            // @todo if is already paied lock file génération return echo true;
//        $filePath = $ledgioService->outputDir . 'declaration-fiscale-' . $year . '-' . uniqid() . '.pdf';
            $filePath = $ledgioService->outputDir . 'declaration-fiscale-crypto-monnaies-' .$year . '-' . date('d-m-Y') . '.pdf';
            $filePathBrouillon = $ledgioService->outputDir . 'brouillon-2019' . '.pdf';
            $filePathAcquisitionAvant2019 = $ledgioService->outputDir . 'acquisition-avant-2019' . '.pdf';
            $filePathWarningWallet = $ledgioService->outputDir . 'warning-wallet-' .$year . '-' . date('d-m-Y') . '.pdf';
            @unlink($filePathBrouillon);
            @unlink($filePath);
            @unlink($filePathAcquisitionAvant2019);
            @unlink($filePathWarningWallet);
            if (empty($ledgioService->getBrouillonArrayRapportAnnexePrincipale())) {
                echo 'false';
                exit;
            }

            $this->layout('layout/layout-ledgio');
//echo "toto"; exit;
//        foreach($ledgioService->getArrayImport() as $import) {
//            var_dump($import->getSourceType());
//            exit;
//        }


            $arrayRapportAnnexePrincipale = $ledgioService->getArrayRapportAnnexePrincipale();
            // debug montant acquisition
            $arrayRapportAnnexePrincipaleEntre2019etJanvierAnneeImposition = $ledgioService->getArrayRapportAnnexePrincipaleEntre2019etJanvierAnneeImposition();
            // generer excel
            // annexe principale
            $header = array(
                "Cession N°" => "string",
                "211. Date de cession" => "date",
                "Heure de cession*" => "time",
                "212. Valeur globale\ndu portefeuille\nau moment\nde la cession" => "price",
                "213. Prix\nde cession" => "price",
                "214. Frais\nde cession" => "price",
                "215. Prix\nde cession\nnet des frais" => "price",
                "216. Soulte reçue\nou versée\nlors de la cession" => "price",
                "217. Prix\nde cession\nnet des soultes" => "price",
                "218. Prix\nde cession\nnet des frais\net soults" => "price",
                "220. Prix total\nd'acquisition" => "price",
                "221. Fractions\nde capital initial\ncontenues dans\nle prix total\n
        d'acquisition" => "price",
                "223. Prix total\nd'acquisition net" => "price",
                "Plus-values\net moins-values" => "price",
            );


            $spreadsheet = new Spreadsheet();

            $sheetAnnexePrincipale = new Worksheet($spreadsheet, 'Annexe principale');
            $nombreCession = count($arrayRapportAnnexePrincipale);
            if ($nombreCession > 20) {
                $sheetDetailFusionCession20 = new Worksheet($spreadsheet, 'Détail des cessions 20 à ' . $nombreCession);
                $sheetDetailFusionCession20->fromArray(array_keys($header), NULL, 'A1');
            }
// Retrieve the current active worksheet
            //$sheetAnnexePrincipale = $spreadsheet->getActiveSheet();
            //$sheetAnnexePrincipale->setTitle('Annexe principale');
            //$arrayLetter = range('A', 'Z');

            $numCession = 1;

            $numeroLigneTableauPrincipal = 0;
            $sheetAnnexePrincipale->fromArray(array_keys($header), NULL, 'A1');

            $sommeCessionBrut = 0;
            $sommeFraisCession = 0;
            $sommePrixCession = 0;
            $sommePrixCessionEtSoults = 0;
            $sommePrixAcquites = 0;
            $sommeFractionsInitialesCapital = 0;
            $sommePrixTotalAcquisition = 0;
            $sommeValeurPortefeuille = 0;
            $sommePlusOuMoinsValue = 0;

            $sommeSecondtermePV = 0;

            $lineDetail = 2;
            foreach ($arrayRapportAnnexePrincipale as $key => $ligneRapport) {
                $colIndex = 1;
                if ($numeroLigneTableauPrincipal < 19 || ($numeroLigneTableauPrincipal == 20 && $nombreCession == 20)) {

                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, $numCession++);
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, $ligneRapport->getDateCession()->format('d-m-Y'));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, $ligneRapport->getDateCession()->format('H:i:s'));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getValeurPortefeuille(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getPrixCessionBrut(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getFraisCession(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getPrixCession(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, '');
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getPrixCessionBrut(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getPrixCession(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getSommePrixAcquites(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getSommeFractionsInitialesCapital(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, number_format($ligneRapport->getPrixTotalAcquisition(), 0, '.', ''));
                    $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $key + 2, (($ligneRapport->getPlusOuMoinsValue() > 0) ? '+' : '') . ' ' . number_format($ligneRapport->getPlusOuMoinsValue(), 0, '.', ''));
                } else {
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, $numCession++);
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, $ligneRapport->getDateCession()->format('d-m-Y'));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, $ligneRapport->getDateCession()->format('H:i:s'));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getValeurPortefeuille(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getPrixCessionBrut(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getFraisCession(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getPrixCession(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, '');
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getPrixCessionBrut(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getPrixCession(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getSommePrixAcquites(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getSommeFractionsInitialesCapital(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, number_format($ligneRapport->getPrixTotalAcquisition(), 0, '.', ''));
                    $sheetDetailFusionCession20->setCellValueByColumnAndRow($colIndex++, $lineDetail, (($ligneRapport->getPlusOuMoinsValue() > 0) ? '+' : '') . ' ' . number_format($ligneRapport->getPlusOuMoinsValue(), 0, '.', ''));

                    $lineDetail++;
                    $sommeCessionBrut += $ligneRapport->getPrixCessionBrut();
                    $sommeFraisCession += $ligneRapport->getFraisCession();
                    $sommePrixCession += $ligneRapport->getPrixCession();
                    $sommePrixCessionEtSoults += $ligneRapport->getPrixCessionBrut();
                    $sommePrixAcquites += $ligneRapport->getSommePrixAcquites();
                    $sommeFractionsInitialesCapital += $ligneRapport->getSommeFractionsInitialesCapital();
                    $sommePrixTotalAcquisition += $ligneRapport->getPrixTotalAcquisition();
                    $sommeValeurPortefeuille += $ligneRapport->getValeurPortefeuille();
                    $sommePlusOuMoinsValue += $ligneRapport->getPlusOuMoinsValue();
                }
                $numeroLigneTableauPrincipal++;

            }


            if ($nombreCession > 20) {
                ${212} = ($sommePrixTotalAcquisition / ($numeroLigneTableauPrincipal - 19)) * $sommePrixCessionEtSoults / ($sommePrixCession - $sommePlusOuMoinsValue);
                $currentLineDetailFusionCession = 20;
                $colIndex = 1;
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, '20 (fusion des cessions 20 à ' . $nombreCession . ')');
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, '31-12-' . $year);
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, '23:59:59');
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format(${212}, 0, '.', '')); //212
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommeCessionBrut, 0, '.', '')); //213
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommeFraisCession, 0, '.', '')); //214
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommePrixCession, 0, '.', '')); //215
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, ''); //216
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, $sommePrixCessionEtSoults); //217
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommePrixCession, 0, '.', '')); //218
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommePrixAcquites / ($numeroLigneTableauPrincipal - 19), 0, '.', '')); //220
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommeFractionsInitialesCapital / ($numeroLigneTableauPrincipal - 19), 0, '.', '')); //221
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommePrixTotalAcquisition / ($numeroLigneTableauPrincipal - 19), 0, '.', '')); //223
                $sheetAnnexePrincipale->setCellValueByColumnAndRow($colIndex++, $currentLineDetailFusionCession, number_format($sommePlusOuMoinsValue, 0));


            }


            // $spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet');

            // Write an .xlsx file
            $spreadsheet->addSheet($sheetAnnexePrincipale, 0);
            if (!empty($sheetDetailFusionCession20)) {
                $spreadsheet->addSheet($sheetDetailFusionCession20);
            }

            foreach (range('A', $sheetAnnexePrincipale->getHighestColumn()) as $column) {
                $sheetAnnexePrincipale->getStyle($column)->getAlignment()->setWrapText(true);
                $sheetAnnexePrincipale->getColumnDimension($column)->setAutoSize(true);
            }

            $sheetAnnexePrincipale->getRowDimension(1)->setRowHeight(-1);
            $writer = new Xlsx($spreadsheet);


// Save .xlsx file to the current directory
            $writer->save($ledgioService->outputDir . 'declaration-fiscale-crypto-monnaies-' . date('d-m-Y') . '.xlsx');

//        $writer = new XLSXWriter();
//        $writer->writeSheetHeader('Annexe principale', $header );
//        foreach($data as $row)
//            $writer->writeSheetRow('Annexe principale', $row );
//        $writer->writeToFile('rapport-test.xlsx');
//var_dump($arrayRapportAnnexePrincipaleEntre2019etJanvierAnneeImposition); exit;
//$testNum = 0;
//            foreach($ledgioService->arrayValuesWalletEUR as $arrayInfos) {
//                var_dump($arrayInfos);
//                $testNum++;
//
//                if ($testNum == 10) exit;
//            }

            $renderer = $this->renderer;
            // Rapport warning incohérence wallet (qté vendue sup à ce qu'il y a dans le wallet
            $viewWarningWallet = new ViewModel([
                'arrayWarningWalletQte' => $ledgioService->arrayWarningWalletQte,
                'arrayImport' => $ledgioService->getArrayImport(),
                'annee' => $year
            ]);

            $viewWarningWallet->setTemplate('layout/warning-rapport');
            $htmlWarningWallet = $renderer->render($viewWarningWallet);
            $pdfWarningWallet = $this->tcpdf;
            $pdfWarningWallet->titlePDFCustom = 'Erreurs du rapport ' . $year;
            $pdfWarningWallet->SetCreator('Ledgio');
            $pdfWarningWallet->SetAuthor('Ledgio');
            $pdfWarningWallet->SetTitle('Erreurs du rapport' . $year);
            $pdfWarningWallet->SetSubject('Erreurs du rapport');
            $pdfWarningWallet->AddPage('L');
            $pdfWarningWallet->SetFont('Helvetica', '', 8, '', 'false');
            $pdfWarningWallet->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdfWarningWallet->setPageMark();
            $pdfWarningWallet->writeHTML($htmlWarningWallet, true, false, true, false, '');
            $pdfWarningWallet->Output($filePathWarningWallet, 'F');


            $view = new ViewModel([
                'lignesRapport' => $arrayRapportAnnexePrincipale,
                'lignesRapportEntre2019etJanvierAnneeImposition' => $arrayRapportAnnexePrincipaleEntre2019etJanvierAnneeImposition, // // debug montant acquisition
                'arrayValuesWalletEUR' => $ledgioService->arrayValuesWalletEUR,
                'totalAcquisitionDebutAnnee' => $ledgioService->getTotalPrixAcquisitionBefore2019(),
                'totalPrixAcquisitionPremierJanvierAnneeImposition' => $ledgioService->getTotalPrixAcquisitionBefore2019(), //// debug montant acquisition
                //'sommePrixAcquitesEntre2019EtJanvierImposition' => $ledgioService->sommePrixAcquitesEntre2019EtJanvierAnneeImposition, //// debug montant acquisition
                'investFiatAfter2019Detail' => $ledgioService->getInvestFiatAfter2019Detail(),
                'arrayAcquisitionFiatAvantDateCession' => $ledgioService->getArrayAcquisitionFiatAvantDateCession(),
                'arrayAcquisitionFiatAvantDateCessionEntre2019etJanvierAnneeImposition' => $ledgioService->getArrayAcquisitionFiatAvantDateCessionEntre2019etJanvierAnneeImposition(), // // debug montant acquisition
                'arrayTransactionsCessionFiatAnneeImposition' => $ledgioService->getArrayTransactionsCessionFiatAnneeImposition(),
                'arrayDetailFusionLigneMemeDateMemeAsset' => $ledgioService->getArrayDetailFusionLigneMemeDateMemeAsset(),
                'explanationPrixTotalAcquisition' => $ledgioService->explanationPrixTotalAcquisition,
                'arrayAcquisitionBefore2019' => $ledgioService->getarrayAcquisitionBefore2019(),
                'explicationAcquisitionAvant2019' => $ledgioService->explicationAcquisitionAvant2019,
                'arrayImport' => $ledgioService->getArrayImport(),
                'arrayExplicationAcquisitionEUR' => $ledgioService->arrayExplicationAcquisitionEUR,
                'explicationValeurEchangeAvant2019' => $ledgioService->explicationValeurEchangeAvant2019,
                'detailArrayAcquisitionFiatDepuisDerniereCession' => $ledgioService->detailArrayAcquisitionFiatDepuisDerniereCession,
                'arrayValuesWalletEURAcquisitionAvantAnneeImposition' => $ledgioService->arrayValuesWalletEURAcquisitionAvantAnneeImposition,
                'arrayExplicationWalletApres2019' => $ledgioService->arrayExplicationWalletApres2019,

                'annee' => $year
            ]);
            $viewBrouillon = new ViewModel([
                'lignesRapport' => $ledgioService->getBrouillonArrayRapportAnnexePrincipale(),
                'arrayValuesWalletEUR' => $ledgioService->arrayValuesWalletEUR,
                'totalAcquisitionDebutAnnee' => $ledgioService->getTotalPrixAcquisitionBefore2019(),
                'investFiatAfter2019Detail' => $ledgioService->getInvestFiatAfter2019Detail(),
                'arrayAcquisitionFiatAvantDateCession' => $ledgioService->getArrayAcquisitionFiatAvantDateCession(),
                'arrayTransactionsCessionFiatAnneeImposition' => $ledgioService->getArrayTransactionsCessionFiatAnneeImposition(),
                'arrayDetailFusionLigneMemeDateMemeAsset' => $ledgioService->getArrayDetailFusionLigneMemeDateMemeAsset(),
                'arrayImport' => $ledgioService->getArrayImport(),
                'annee' => $year
            ]);
//        echo '<pre>';
//        var_dump($ledgioService->arrayValuesWalletEUR); exit;
//         echo '</pre>';
            $viewAcquisition = new ViewModel(
                ['arrayAcquisitionBefore2019' => $ledgioService->getarrayAcquisitionBefore2019()
                ]);
//$view->setTemplate('rapport-pdf');



            $view->setTemplate('layout/rapport');
            $viewBrouillon->setTemplate('layout/brouillon-rapport');
            $viewAcquisition->setTemplate('layout/annexe-acquisition-avant-01-01-2019');

            $html = $renderer->render($view);
            $htmlBrouillon = $renderer->render($viewBrouillon);
            $htmlAcquisition = $renderer->render($viewAcquisition);

            $pdf = $this->tcpdf;
            $pdf->titlePDFCustom = 'Annexe (V de l\'article 150 VH Bis du code général des impôts) ' . $year;

            $pdfBrouillon = $this->tcpdfBrouillon;
            $pdfBrouillon->titlePDFCustom = '!!!! Apercu Annexe (V de l\'article 150 VH Bis du code général des impôts) ' . $year;

            $pdfAcquisition = clone $this->tcpdf;
            $pdfAcquisition->titlePDFCustom = 'Annexe Acquisition avant 1er janvier 2019';


//echo 'toto';
            // set document information
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('Ledgio');

            $pdf->SetTitle('Annexe (V de l\'article 150 VH Bis du code général des impôts)' . $year);
            $pdf->SetSubject('Calcul des plus values');

            $pdfAcquisition->SetTitle('Annexe Acquisition avant 1er janvier 2019');
            $pdfAcquisition->SetSubject('Acquisition');
//$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
            //$pdf->SetFont('arialnarrow', '', 12, '', false);
            $pdf->AddPage('L');
            $pdf->SetFont('Helvetica', '', 8, '', 'false');

            $pdfBrouillon->AddPage('L');
            $pdfBrouillon->SetFont('Helvetica', '', 8, '', 'false');

//        img/pdf/filigrane-brouillon.png
            $image_file = $this->config['path-app'] . '/public/img/pdf/filigrane-brouillon.png';
            $pdfBrouillon->startLayer('layer', true, true, true);
            $pdfBrouillon->Image($image_file, '', '', '', '', '', '', 'C', true, 300, 'C', false, false, 0, '', false, false);


            $pdfAcquisition->AddPage('L');
            $pdfAcquisition->SetFont('Helvetica', '', 8, '', 'false');


            // get the current page break margin
            $bMargin = $pdf->getBreakMargin();
            // get current auto-page-break mode
            $auto_page_break = $pdf->getAutoPageBreak();
            // disable auto-page-break
//        $pdf->SetAutoPageBreak(false, 0);
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdfBrouillon->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdfAcquisition->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);


            //$image_file = $this->config['path-app'] . '/public/img/pdf/filigrane-brouillon.png';
            //$pdfBrouillon->Image($image_file, 0, 0, $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = 2, $dpi = 300, $palign = 'C', $ismask = false, $imgmask = false, $border = 0, $fitbox = 'CM', $hidden = false, $fitonpage = true, $alt = false, $altimgs = array());
            // set bacground image
            // restore auto-page-break status
            $pdf->SetAutoPageBreak($auto_page_break, $bMargin);
            $pdfBrouillon->SetAutoPageBreak($auto_page_break, $bMargin);
            $pdfAcquisition->SetAutoPageBreak($auto_page_break, $bMargin);
// set the starting point for the page content
            $pdf->setPageMark();

            $pdf->writeHTML($html, true, false, true, false, '');
            $pdfBrouillon->writeHTML($htmlBrouillon, true, false, true, false, '');
            $pdfAcquisition->writeHTML($htmlAcquisition, true, false, true, false, '');


            //$pdf->Output();
            $config = $this->getConfig();
//touch('./data/io/data/io/rapport-2019.pdf');
            $pdf->Output($filePath, 'F');
            $pdfBrouillon->endLayer();
            $pdfBrouillon->Output($filePathBrouillon, 'F');
            $pdfAcquisition->Output($filePathAcquisitionAvant2019, 'F');


            if (is_file($filePath)) {

                if ($reportFind) {
                    $reportFind->setPath($filePath);
                    $reportFind->setPathBrouillon($filePathBrouillon);
                    $reportFind->setCreatedDate(new \DateTime());

                    $reportMapper->update($reportFind);

                    if ($reportFind && is_file($reportFind->getPath()) && is_file($reportFind->getPathBrouillon())) {
                        echo 'true';
                        exit;
                    } else {
                        echo 'false';
                        exit;
                    }
                } else {
                    $report = new \Application\Entity\Report();
                    $report->setStatus(0);
                    $report->setYear($year);
                    $report->setUser($user);
                    $report->setPath($filePath);
                    $report->setPathBrouillon($filePathBrouillon);
                    $report->setCreatedDate(new \DateTime());


                    $reportMapper->insert($report);

                    if ($report && is_file($report->getPath())) {
                        echo 'true';
                        exit;
                    } else {
                        echo 'false';
                        exit;
                    }
                }
            } else {
                echo 'titi';
                exit;
                echo 'false';
                exit;
            }


        }

        display:
        if ($reportFind && is_file($reportFind->getPath()) && is_file($reportFind->getPathBrouillon())) {
            echo 'true';
            exit;
        } else {
            echo 'false';
            exit;
        }
    }

    public function getConfig()
    {
        return $this->config;
    }

    public function apercuAction()
    {


        if ($user = $this->currentUser()) {

        } else {
            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        }


        $year = $this->params()->fromRoute('year', null);

        $reportMapper = new \Application\Mapper\ReportMapper($this->getEntityManager());
        $reportFind = $reportMapper->findByYearAndUser($year, $user);


        return new ViewModel(array(
            'year' => $year,
            'reportFind' => $reportFind
        ));
    }

    public function downloadAction()
    {
        if ($user = $this->currentUser()) {

        } else {
            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        }


        // verifier si paye
        //$token = $this->params()->fromRoute('token', null);
        $year = $this->params()->fromRoute('year', null);
        $mode = $this->params()->fromRoute('mode', null);
        $type = $this->params()->fromRoute('type', null);


//        if (empty($token)) {
//            $this->flashMessenger()->addErrorMessage('Aucun rapport n\'est disponible');
//                    $this->redirect()->toRoute(self::ROUTE_DOWNLOAD);
//        }

        if (empty($year)) {
            $this->flashMessenger()->addErrorMessage('Aucun rapport n\'est disponible');
            $this->redirect()->toRoute(self::ROUTE_APERCU);
        }

        $entityManager = $this->getEntityManager();
        /* @var $entityManager \Doctrine\ORM\EntityManager */
        $reportMapper = new \Application\Mapper\ReportMapper($entityManager);

        $reportFind = $reportMapper->findByYearAndUser($year, $user);
//        if ($mode != 'brouillon' && $reportFind->isNotValidated() || $mode == 'final') {
//            echo 'not validate';
//            exit;
//            $this->redirect()->toRoute(self::ROUTE_APERCU);
//        }

        //var_dump(empty($reportFind)); exit;
        if (!$reportFind) {
            sleep(10);
            $reportFind = $reportMapper->findByYearAndUser($year, $user);
        }

//        if (!$reportFind) {
//            sleep(10);
//            $reportFind = $reportMapper->findByYearAndUser($year, $user);
//        }
        if ($mode == 'brouillon') {
            $filePath = $reportFind->getPathBrouillon();
        } else {
            $filePath = $reportFind->getPath();
        }
        $explodeFilePath = explode('/', $filePath);
        $fileName = end($explodeFilePath);

        if (!is_readable($filePath)) {
            // Set 404 Not Found status code
            $this->getResponse()->setStatusCode(404);
            return;
        }

        // Get file size in bytes
        $fileSize = filesize($filePath);

        // Write HTTP headers
        $response = $this->getResponse();
        $headers = $response->getHeaders();


        if ($type == 'inline') {
            $headers->addHeaderLine("Content-Disposition: inline; filename=\"" . $fileName . ".pdf");
            $headers->addHeaderLine("Content-type: application/pdf");
        } else {
            $headers->addHeaderLine(
                "Content-type: application/octet-stream");
            $headers->addHeaderLine(
                "Content-Disposition: attachment; filename=\"" .
                $fileName . "\"");
            $headers->addHeaderLine("Content-length: $fileSize");
            $headers->addHeaderLine("Cache-control: private");
        }

        // Write file content        
        $fileContent = file_get_contents($filePath);
        if ($fileContent != false) {
            $response->setContent($fileContent);
        } else {
            // Set 500 Server Error status code
            $this->getResponse()->setStatusCode(500);
            return;
        }

        // Return Response to avoid default view rendering
        return $this->getResponse();

//        var_dump($reportFind);
//        exit;
//        $countTrade = $ledgioMapper->countTradeByIdUser($user->getId());
//        $countTradeIn = $ledgioMapper->countTradeInByIdUser($user->getId());
//        $countTradeOut = $ledgioMapper->countTradeOutByIdUser($user->getId());
        //var_dump($countTrade); exit;
//        return new ViewModel(array(
//            //'arrayExhanges' => $arrayExhanges,
//            'countTrade' => $countTrade,
//            'countTradeIn' => $countTradeIn,
//            'countTradeOut' => $countTradeOut,
//        ));
    }

    public function validationCommandeAction()
    {
        if ($user = $this->currentUser()) {

        } else {
            return $this->redirect()->toRoute(\Application\Controller\UserController::ROUTE_LOGIN);
        }

        // https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/#set-up-the-environment
        $orderId = $this->params()->fromRoute('orderId', null);
        $year = $this->params()->fromRoute('year', null);


        //var_dump($orderId); exit;
        $client = \Application\Service\Paypal\PaypalClient::client();
        $request = new OrdersGetRequest($orderId);
        $request->headers["prefer"] = "return=representation";
        $response = $client->execute($request);


        /**
         * Enable the following line to print complete response as JSON.
         */
        //print json_encode($response->result);
        print "Status Code: {$response->statusCode}\n";
        print "Status: {$response->result->status}\n";
        print "Order ID: {$response->result->id}\n";
        print "Intent: {$response->result->intent}\n";
        print "Links:\n";
        foreach ($response->result->links as $link) {
            print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
        }
        // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
        print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";

        // save order
        // unlock report
        $reportMapper = new \Application\Mapper\ReportMapper($this->getEntityManager());
        $report = $reportMapper->findByYearAndUser($year, $user);

        if (!$report) {
            $this->flashMessenger()->addErrorMessage('Aucun rapport n\'est disponible');
            $this->redirect()->toRoute(self::ROUTE_APERCU, array('year' => $year));
        }
        if ($report->getOrderId()) {
            $this->flashMessenger()->addErrorMessage('Paiement déjà effectué.');
            $this->redirect()->toRoute(self::ROUTE_APERCU, array('year' => $year));
        }
        $report->setOrderId($orderId);
        $report->setStatus(true);
        $this->getEntityManager()->persist($report);
        $this->getEntityManager()->flush();

        $this->flashMessenger()->addSuccessMessage('Paiement déjà effectué.');
        $this->redirect()->toRoute(self::ROUTE_APERCU, array('year' => $year));
        // To print the whole response body, uncomment the following line
        // echo json_encode($response->result, JSON_PRETTY_PRINT);
    }

}


??

??