<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (08/08/2018 17:54)
 */
class WebserviceSpecificManagementMobileStats implements WebserviceSpecificManagementInterface
{
    /** @var WebserviceOutputBuilderCore */
    protected $objOutput;

    /** @var mixed */
    protected $output;

    /** @var WebserviceRequestCore */
    protected $wsObject;

    public function setObjectOutput(WebserviceOutputBuilderCore $obj)
    {
        $this->objOutput = $obj;

        return $this;
    }

    public function getObjectOutput()
    {
        return $this->objOutput;
    }

    public function setWsObject(WebserviceRequestCore $obj)
    {
        $this->wsObject = $obj;

        return $this;
    }

    public function getWsObject()
    {
        return $this->wsObject;
    }

    public function manage(): void
    {
        /** @var WebserviceRequestCore $wsObject */
        $wsObject = $this->getWsObject();
        $id_employee = method_exists($wsObject, 'getIdEmployee') ? $this->getWsObject()->getIdEmployee() : 0;

        $ret = [];

        $db = Db::getInstance();

        /////////////////////////////////////////
        /// Graphiques de CA
        $stats = $db->executeS(
            "SELECT DATE_FORMAT(`o`.`invoice_date`, '%Y-%m-%d') AS `date`,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl`) AS ca
                    FROM `ps_order_invoice` `i`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `i`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 8 DAY, '%Y-%m-%d') AND `o`.`invoice_date` <= CONCAT(DATE_FORMAT(NOW() - INTERVAL 1 DAY, '%Y-%m-%d') , ' 23:59:59')
                    AND mc.id_employee = " . (int) $id_employee . '
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`), DAY(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC'
        );
        $remboursements = $db->executeS(
            "SELECT DATE_FORMAT(`os`.`date_add`, '%Y-%m-%d') AS `date`,
                    0 - `os`.`total_products_tax_incl` AS ca
                    FROM `ps_order_slip` `os`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `os`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `os`.`date_add` >= DATE_FORMAT(NOW() - INTERVAL 8 DAY, '%Y-%m-%d') AND `os`.`date_add` <= CONCAT(DATE_FORMAT(NOW() - INTERVAL 1 DAY, '%Y-%m-%d') , ' 23:59:59')
                    AND mc.id_employee = " . (int) $id_employee . '
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`), DAY(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC'
        );

        $statsLastYear = $db->executeS(
            "SELECT DATE_FORMAT(o.date_add + INTERVAL 365 DAY, '%Y-%m-%d') AS `date`,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl`) AS ca
                    FROM `ps_order_invoice` `i`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `i`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 373 DAY, '%Y-%m-%d') AND `o`.`invoice_date` <= CONCAT(DATE_FORMAT(NOW() - INTERVAL 366 DAY, '%Y-%m-%d') , ' 23:59:59')
                    AND `mc`.`id_employee` = " . (int) $id_employee . '
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`), DAY(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC'
        );
        $remboursementsLastYear = $db->executeS(
            "SELECT DATE_FORMAT(`os`.`date_add`, '%Y-%m-%d') AS `date`,
                    0 - `os`.`total_products_tax_incl` AS ca
                    FROM `ps_order_slip` `os`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `os`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `os`.`date_add` >= DATE_FORMAT(NOW() - INTERVAL 373 DAY, '%Y-%m-%d') AND `os`.`date_add` <= CONCAT(DATE_FORMAT(NOW() - INTERVAL 366 DAY, '%Y-%m-%d') , ' 23:59:59')
                    AND mc.id_employee = " . (int) $id_employee . '
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`), DAY(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC'
        );

        $valuesByDate = [];

        if (!is_array($stats)) {
            $stats = [];
        }

        if (!is_array($remboursements)) {
            $remboursements = [];
        }

        if (!is_array($statsLastYear)) {
            $statsLastYear = [];
        }

        if (!is_array($remboursementsLastYear)) {
            $remboursementsLastYear = [];
        }

        foreach ($stats as $i => $stat) {
            $valuesByDate[$stat['date']] = [round($stat['ca']), 0];
        }
        // On récupère les valeurs pour chaque date (cette année et l'an dernier !)
        foreach ($remboursements as $i => $remboursement) {
            if (!isset($valuesByDate[$remboursement['date']])) {
                $valuesByDate[$remboursement['date']] = [0, 0];
            }
            $valuesByDate[$remboursement['date']][0] -= round($remboursement['ca']);
        }
        foreach ($statsLastYear as $i => $stat) {
            if (!isset($valuesByDate[$stat['date']])) {
                $valuesByDate[$stat['date']] = [0, 0];
            }
            $valuesByDate[$stat['date']][1] = round($stat['ca']);
        }
        foreach ($remboursementsLastYear as $i => $remboursement) {
            if (!isset($valuesByDate[$remboursement['date']])) {
                $valuesByDate[$remboursement['date']] = [0, 0];
            }
            $valuesByDate[$remboursement['date']][1] -= round($remboursement['ca']);
        }

        $dates = [];
        $values = [
            [],
            [],
        ];

        $now = new DateTimeImmutable();
        for ($i = 1; $i <= 7; ++$i) {
            $date = $now->sub(new DateInterval('P' . $i . 'D'))->format('Y-m-d');

            $dates[] = $date;
            $values[0][] = isset($valuesByDate[$date]) ? $valuesByDate[$date][0] : 0;
            $values[1][] = isset($valuesByDate[$date]) ? $valuesByDate[$date][1] : 0;
        }

        $ret[] = [
            'type' => 'plotlies',
            'tab' => 'resume',
            'title' => 'Statistiques mensuelles',
            'params' => [
            ],
            'data' => [
                [
                    'title' => 'Cette semaine',
                    'layout' => [
                        'title' => 'Cette semaine (CA en € HT)',
                        'showlegend' => true,
                        'legend' => [
                            'orientation' => 'h',
                        ],
                        'margin' => ['l' => 20, 'r' => 20],
                        'xaxis' => [
                            'type' => 'date',
                            'fixedrange' => true,
                        ],
                        'yaxis' => [
                            'fixedrange' => true,
                        ],
                        'dragmode' => false,
                    ],
                    'config' => ['displayModeBar' => false],
                    'data' => [
                        ['x' => $dates, 'y' => $values[0], 'type' => 'scatter', 'mode' => 'lines', 'line' => ['color' => 'rgb(25,113,184)'], 'name' => date('Y')],
                        ['x' => $dates, 'y' => $values[1], 'type' => 'scatter', 'mode' => 'lines', 'line' => ['color' => 'rgb(161,210,224)'], 'name' => date('Y') - 1],
                    ],
                ],
            ],
        ];

        /////////////////////////////////////////
        /// Construction du tableau de stats mensuels
        $stats = $db->executeS(
            "SELECT YEAR(`o`.`invoice_date`) AS annee, MONTH(`o`.`invoice_date`) AS mois,
                    COUNT(`o`.`id_order`) AS nb_commandes,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl`) AS ca_reel,
                    SUM(`i`.`total_discount_tax_excl`) AS reductions,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl` + `i`.`total_discount_tax_excl`) AS ca_hors_reductions
                    FROM `ps_order_invoice` `i`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `i`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 24 MONTH,'%Y-%m-01') AND `o`.`invoice_date` <= NOW()
                    AND `mc`.`id_employee` = " . (int) $id_employee . '
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC'
        );

        $remboursements = $db->executeS(
            "SELECT YEAR(`os`.`date_add`) AS annee, MONTH(`os`.`date_add`) AS mois,
                    COUNT(`os`.`id_order_slip`) AS nb_remboursements,
                    SUM(`os`.`total_products_tax_excl`) AS remboursements_produits
                    FROM `ps_order_slip` `os`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `os`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 24 MONTH,'%Y-%m-01') AND `o`.`invoice_date` <= NOW()
                    AND `mc`.`id_employee` = " . (int) $id_employee . '
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC'
        );
        $statDataMensuel = [];

        if (!is_array($stats)) {
            $stats = [];
        }

        foreach ($stats as $statRow) {
            $statDataMensuel[$statRow['annee'] . '-' . str_pad($statRow['mois'], 2, '0', STR_PAD_LEFT)] = [
                'nb_commandes' => $statRow['nb_commandes'],
                'nb_remboursements' => 0,
                'remboursements_produits' => 0,
                'ca_reel' => $statRow['ca_reel'],
                'reductions' => $statRow['reductions'],
                'ca_hors_reductions' => $statRow['ca_hors_reductions'],
            ];
        }

        if (!is_array($remboursements)) {
            $remboursements = [];
        }

        foreach ($remboursements as $rembRow) {
            $key = $rembRow['annee'] . '-' . str_pad($rembRow['mois'], 2, '0', STR_PAD_LEFT);

            if (!isset($statDataMensuel[$key])) {
                $statDataMensuel[$key] = [
                    'nb_commandes' => 0,
                    'nb_remboursements' => 0,
                    'remboursements_produits' => 0,
                    'ca_reel' => 0,
                    'reductions' => 0,
                    'ca_hors_reductions' => 0,
                ];
            }

            $statDataMensuel[$key]['nb_remboursements'] = $rembRow['nb_remboursements'];
            $statDataMensuel[$key]['remboursements_produits'] = $rembRow['remboursements_produits'];
            $statDataMensuel[$key]['ca_reel'] -= $rembRow['remboursements_produits'];
            $statDataMensuel[$key]['ca_hors_reductions'] -= $rembRow['remboursements_produits'];
        }

        // Année courante
        $currentYear = date('Y');
        $currentMonth = date('m');

        $dataSet = [];

        // On va parcourir les 12 derniers mois
        for ($i = 0; $i < 24; ++$i) {
            $date = new DateTime();
            $date->setTimestamp(intval(mktime(12, 0, 0, intval($currentMonth), 1, intval($currentYear))));
            if ($i) {
                $date->add(DateInterval::createFromDateString('-' . $i . ' month'));
            }

            $nb_commandes = isset($statDataMensuel[$date->format('Y-m')]['nb_commandes']) ? $statDataMensuel[$date->format('Y-m')]['nb_commandes'] : '-';
            $nb_remboursements = isset($statDataMensuel[$date->format('Y-m')]['nb_remboursements']) ? $statDataMensuel[$date->format('Y-m')]['nb_remboursements'] : '-';
            $ca_reel = isset($statDataMensuel[$date->format('Y-m')]['ca_reel']) ? $statDataMensuel[$date->format('Y-m')]['ca_reel'] : '-';
            $ca_reel_precedent = isset($statDataMensuel[($currentYear - 1) . '-' . $date->format('m')]['ca_reel']) ? $statDataMensuel[($currentYear - 1) . '-' . $date->format('m')]['ca_reel']
                : null;
            $variation_ca_precedent = !empty($ca_reel_precedent) ? (100 * (1 - ($ca_reel / $ca_reel_precedent))) . '%' : '-';
            $reductions = isset($statDataMensuel[$date->format('Y-m')]['reductions']) ? $statDataMensuel[$date->format('Y-m')]['reductions'] : '-';
            $remboursement_produits = isset($statDataMensuel[$date->format('Y-m')]['remboursements_produits']) ? $statDataMensuel[$date->format('Y-m')]['remboursements_produits'] : '-';
            $ca_hors_reductions = isset($statDataMensuel[$date->format('Y-m')]['ca_hors_reductions']) ? $statDataMensuel[$date->format('Y-m')]['ca_hors_reductions'] : '-';

            $dataSet[] = [
                "<small style='color: grey;'>" . $date->format('m/Y') . (0 == $i ? ' (en cours)' : '') . '</small>',
                "<span style='color: #3b3b3b;'>" . $nb_commandes . '</span>',
                "<span style='color: #1c6fb6;'>" . round($ca_reel) . '&nbsp;€</span>',
                //"<span style='color: " . ($variation_ca_precedent >= 0 ? "#4d8956" : "#ae293c") . ";'>" . round($variation_ca_precedent) . "&nbsp;%</span>",
                "<span style='color: #ae293c;'>" . round($reductions) . '&nbsp;€</span>',
                "<span style='color: #3b3b3b;'>" . $nb_remboursements . '</span>',
                "<span style='color: #ae293c;'>" . round($remboursement_produits) . '&nbsp;€</span>',
                "<span style='color: grey;'>" . round($ca_hors_reductions) . '&nbsp;€</span>',
            ];
        }

        $ret[] = [
            'type' => 'datatable-columns',
            'tab' => 'resume',
            'title' => 'Statistiques mensuelles',
            'params' => [
                'rows' => [
                    '',
                    '<strong>Commandes</strong>',
                    '<strong>CA réel HT</strong>',
                    //"<strong style='color: grey;'>% CA vs Année-1</strong>",
                    "<strong style='color: grey;'>Remise fidélité HT</strong>",
                    '<strong>Remboursements</strong>',
                    "<strong style='color: grey;'>Remboursements HT</strong>",
                    "<strong style='color: grey;'>CA hors reduc. HT</strong>",
                ],
            ],
            'data' => $dataSet,
        ];

        /////////////////////////////////////////
        /// Stats sur l'année
        $year = date('Y');
        $infos = [];
        for ($i = 0; $i <= 1; ++$i) {
            $infos[$year - $i] = [
                'nb_commandes' => 0,
                'reductions' => 0,
                'ca_hors_reductions' => 0,
                'nb_remboursements' => 0,
                'remboursements_produits' => 0,
            ];

            $infos1 = $db->getRow(
                'SELECT 
                    COUNT(`o`.`id_order`) AS nb_commandes,
                    SUM(`i`.`total_discount_tax_excl`) AS reductions,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl`) AS ca_reel_ht,
                    SUM(`i`.`total_paid_tax_excl` - `i`.`total_shipping_tax_excl` + `i`.`total_discount_tax_excl`) AS ca_hors_reductions
                    FROM `ps_order_invoice` `i`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `i`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= "' . ($year - $i) . '-01-01" AND `o`.`invoice_date` <= "' . ($year - $i) . '-' . date('m-d') . ' 23:59:59"
                    AND `mc`.`id_employee` = ' . (int) $id_employee . '
                    GROUP BY YEAR(`o`.`invoice_date`)'
            );
            $infos2 = $db->getRow(
                'SELECT 
                    COUNT(`os`.`id_order_slip`) AS nb_remboursements,
                    SUM(`os`.`total_products_tax_excl`) AS remboursements_produits
                    FROM `ps_order_slip` `os`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `os`.`id_order`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `os`.`date_add` >= "' . ($year - $i) . '-01-01" AND `os`.`date_add` <= "' . ($year - $i) . '-' . date('m-d') . ' 23:59:59"
                    AND `mc`.`id_employee` = ' . (int) $id_employee . '
                    GROUP BY YEAR(`os`.`date_add`)'
            );

            $infos[$year - $i] = array_merge(
                $infos[$year - $i],
                is_array($infos1) ? $infos1 : [],
                is_array($infos2) ? $infos2 : []
            );
        }

        if (null == $infos[$year - 1]) {
            $infos[$year - 1] = [
                'nb_commandes' => 0,
                'reductions' => 0,
                'ca_hors_reductions' => 0,
                'nb_remboursements' => 0,
                'remboursements_produits' => 0,
                'ca_reel_ht' => 0,
            ];
        }

        $yearRecap = date('Y');
        $endOfRecapYear = (new DateTime() < new DateTime($yearRecap . '-12-31') ? new DateTime() : new DateTime($yearRecap . '-12-31'))
            ->format('d/m/Y');

        $caReelYear = $infos[$yearRecap]['ca_reel_ht'] - $infos[$yearRecap]['remboursements_produits'];
        $caReelYearBefore = $infos[$yearRecap - 1]['ca_reel_ht'] - $infos[$yearRecap - 1]['remboursements_produits'];

        if ($caReelYearBefore) {
            $percent = round(100 * (($caReelYear / $caReelYearBefore) - 1)) . '%';
        } else {
            $percent = null;
        }

        $statAnnee = [
            'type' => 'simple-list',
            'tab' => 'resume',
            'title' => 'Année ' . $yearRecap,
            'data' => [
                [
                    'label' => '<strong>Commandes effectuées</strong>',
                    'value' => $infos[$yearRecap]['nb_commandes'],
                ],
                [
                    'label' => "<strong>Chiffre d'affaire brut HT</strong><br>du 01/01/" . $yearRecap . ' au ' . $endOfRecapYear,
                    'value' => round($infos[$yearRecap]['ca_hors_reductions']) . ' €',
                ],
                [
                    'label' => 'Remise fidélité HT',
                    'value' => "<span style='color: #c26d6c;'>" . round($infos[$yearRecap]['reductions']) . ' € (' . round(100 * $infos[$yearRecap]['reductions'] / $infos[$yearRecap]['ca_hors_reductions'])
                        . ' %)</span>',
                ],
                [
                    'label' => '<strong>Remboursements effectuées</strong>',
                    'value' => $infos[$yearRecap]['nb_remboursements'],
                ],
                [
                    'label' => '<strong>Produits remboursés HT</strong><br>du 01/01/' . $yearRecap . ' au ' . $endOfRecapYear,
                    'value' => '<span class="badge color-red">' . round($infos[$yearRecap]['remboursements_produits']) . ' €</span>',
                ],
                [
                    'label' => "<strong>Chiffre d'affaires réel HT</strong><br>du 01/01/" . $yearRecap . ' au ' . $endOfRecapYear,
                    'value' => '<span class="badge color-blue">' . round($infos[$yearRecap]['ca_reel_ht'] - $infos[$yearRecap]['remboursements_produits']) . ' €</span>',
                ],
            ],
        ];

        if (null !== $percent) {
            $statAnnee['data'][] = [
                'label' => 'soit ' . ($percent >= 0 ? '<span style="color: green;">+' : '<span style="color: red;">') . $percent . '</span> comparé au<br>CA période précédente<br>du 01/01/'
                    . ($yearRecap - 1) . ' au ' . str_replace($yearRecap, strval($yearRecap - 1), $endOfRecapYear),
                'value' => round($caReelYearBefore) . ' €',
            ];
        }

        $ret[] = $statAnnee;

        /////////////////////////////////////////
        /// Statistiques par labo
        $stats = $db->executeS(
            "SELECT DATE_FORMAT(`o`.`invoice_date`, '%m/%Y') as `date`,
                    `m`.`name` AS `labo`,
                    COUNT(`o`.`id_order`) AS `nb_commandes`,
                    SUM(`od`.`total_price_tax_excl`) AS `ca`
                    FROM `ps_order_invoice` `i`
                    INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `i`.`id_order`
                    INNER JOIN `ps_order_detail` `od` ON `od`.`id_order_invoice` = `i`.`id_order_invoice`
                    INNER JOIN `ps_product` `p` ON `p`.`id_product` = `od`.`product_id`
                    LEFT JOIN `ps_manufacturer` `m` ON `m`.`id_manufacturer` = `p`.`id_manufacturer`
                    INNER JOIN `ps_myvetshop_clinique` `mc` ON (`o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`)
                    WHERE `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 366 DAY, '%Y-%m-%d')
                    AND `mc`.`id_employee` = " . (int) $id_employee . "
                    AND `m`.`name` != 'MATERIEL'
                    GROUP BY `p`.`id_manufacturer`, YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC, SUM(`od`.`total_price_tax_excl`) DESC"
        );
        $statLaboMensuel = [];
        $caParLabo = [];

        if (!is_array($stats)) {
            $stats = [];
        }

        foreach ($stats as $statRow) {
            if (!isset($caParLabo[$statRow['labo']])) {
                $caParLabo[$statRow['labo']] = 0;
            }

            $caParLabo[$statRow['labo']] += $statRow['ca'];

            if (!isset($statLaboMensuel[$statRow['date']])) {
                $statLaboMensuel[$statRow['date']] = [];
            }

            $statLaboMensuel[$statRow['date']][$statRow['labo']] = [
                'nb_commandes' => $statRow['nb_commandes'],
                'ca' => $statRow['ca'],
            ];
        }

        arsort($caParLabo, SORT_NUMERIC);

        $labs = array_slice(array_keys($caParLabo), 0, 5);
        $otherLabs = array_slice(array_keys($caParLabo), 5);
        $labRows = array_merge([''], $labs, ['Autres']);
        $labDataSet = [];

        foreach ($statLaboMensuel as $date => $listLabos) {
            $caAutre = 0;
            $ventes = [
                "<small style='color: grey;'>" . $date . (0 == $i ? ' (en cours)' : '') . '</small>',
            ];

            foreach ($labs as $lab) {
                if (isset($listLabos[$lab])) {
                    $ventes[] = "<span style='color: #1c6fb6;'>" . round($listLabos[$lab]['ca']) . '&nbsp;€</span>';
                } else {
                    $ventes[] = "<span style='color: #1c6fb6;'>0&nbsp;€</span>";
                }
            }

            foreach ($otherLabs as $lab) {
                if (isset($listLabos[$lab])) {
                    $caAutre += round($listLabos[$lab]['ca']);
                }
            }

            $labDataSet[] = array_merge($ventes, [$caAutre . '&nbsp;€']);
        }

        $ret[] = [
            'type' => 'datatable-columns',
            'tab' => 'resume',
            'title' => 'CA HT des 5 meilleurs labos',
            'params' => [
                'rows' => $labRows,
            ],
            'data' => $labDataSet,
        ];

        header('Content-Type: application/json');
        echo json_encode($ret);
        exit();
    }

    /**
     * This must be return an array with specific values as WebserviceRequest expects.
     *
     * @return array
     */
    public function getContent(): array
    {
        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
