<?php

declare(strict_types=1);

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        $clinique = Clinique::getCliniqueByEmployeeId((int) $id_employee);

        if (!$clinique) {
            return;
        }
        $carriers = [
            $clinique->id_carrier,
            $clinique->id_carrier_home,
        ];

        $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`
                    WHERE `o`.`id_carrier` IN (" . \implode(',', $carriers) . ")
                    AND `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')
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`), DAY(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC",
            true,
            false
        );
        $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`
                    WHERE `o`.`id_carrier` IN (" . \implode(',', $carriers) . ")
                    AND `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')
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`), DAY(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC",
            true,
            false
        );

        $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`
                    WHERE `o`.`id_carrier` IN (" . \implode(',', $carriers) . ")
                    AND `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')
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`), DAY(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC",
            true,
            false
        );
        $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`
                    WHERE `o`.`id_carrier` IN (" . \implode(',', $carriers) . ")
                    AND `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')
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`), DAY(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC",
            true,
            false
        );

        $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`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ")
                    AND `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 24 MONTH,'%Y-%m-01') AND `o`.`invoice_date` <= NOW()
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC",
            true,
            false
        );

        // TODO : Rendre les catégories alimentation paramétrables
        $alimCatIds = [17, 25, 32, 28, 29, 30, 31, 617, 620, 615, 621, 652, 653, 655, 654, 642, 624];

        $statsAlim = $db->executeS(
            'SELECT YEAR(`o`.`invoice_date`) AS annee, MONTH(`o`.`invoice_date`) AS mois,
                    SUM(`od`.`total_price_tax_excl`) AS ca_alim_hors_reductions
                    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` = `o`.`id_order`
                    INNER JOIN `ps_product` `p` ON `p`.`id_product` = `od`.`product_id`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ")
                    AND `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 24 MONTH,'%Y-%m-01') AND `o`.`invoice_date` <= NOW()
                    AND `p`.`id_category_default` IN (" . \implode(',', $alimCatIds) . ')
                    GROUP BY YEAR(`o`.`invoice_date`), MONTH(`o`.`invoice_date`)
                    ORDER BY `o`.`invoice_date` DESC',
            true,
            false
        );

        $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`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ")
                    AND `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 24 MONTH,'%Y-%m-01') AND `o`.`invoice_date` <= NOW()
                    GROUP BY YEAR(`os`.`date_add`), MONTH(`os`.`date_add`)
                    ORDER BY `os`.`date_add` DESC",
            true,
            false
        );
        $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' => \round($statRow['ca_reel']),
                'ca_alim' => '-',
                'frais_bancaires' => '-',
                'reductions' => \round($statRow['reductions']),
                'ca_hors_reductions' => \round($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,
                    'ca_alim' => '-',
                    'frais_bancaires' => '-',
                    'reductions' => 0,
                    'ca_hors_reductions' => 0,
                ];
            }

            $statDataMensuel[$key]['nb_remboursements'] = $rembRow['nb_remboursements'];
            $statDataMensuel[$key]['remboursements_produits'] = \round($rembRow['remboursements_produits']);
            $statDataMensuel[$key]['ca_reel'] -= $statDataMensuel[$key]['remboursements_produits'];
            $statDataMensuel[$key]['ca_hors_reductions'] -= $statDataMensuel[$key]['remboursements_produits'];
        }

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

        foreach ($statsAlim as $statRow) {
            if ((int) $statRow['annee'] < 2023) {
                continue;
            }

            $key = $statRow['annee'] . '-' . \str_pad($statRow['mois'], 2, '0', \STR_PAD_LEFT);
            $caAlim = \floor($statRow['ca_alim_hors_reductions']);
            // Supprime les remboursements
            $caAlim -= \floatval($statDataMensuel[$key]['remboursements_produits'] ?? 0);
            // Supprime les réductions
            $caAlim -= \floatval($statDataMensuel[$key]['reductions'] ?? 0);
            // Correction des frais bancaires
            $fraisBancaires = ($statDataMensuel[$key]['ca_hors_reductions'] * 1.2 * 0.004)
                + ($statDataMensuel[$key]['nb_commandes'] * 0.1);
            $remuneration = \floor($caAlim * 0.2) - $fraisBancaires;
            $multiplicateur = \round($remuneration / \floor($caAlim * 0.2), 4);
            $caAlim *= $multiplicateur;
            $statDataMensuel[$key]['ca_alim'] = \floor($caAlim);
            $statDataMensuel[$key]['frais_bancaires'] = \ceil($fraisBancaires);
        }

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

        $dataSet = [];

        // On va parcourir les 12 derniers mois
        for ($i = 0; $i < 24; ++$i) {
            $interval = DateInterval::createFromDateString('-' . $i . ' month');
            if (!$interval) {
                throw new Exception('Bad interval');
            }

            $date = new DateTime();
            $date->setTimestamp((int) \mktime(12, 0, 0, (int) $currentMonth, 1, (int) $currentYear));
            if ($i) {
                $date->add($interval);
            }

            $nb_commandes = $statDataMensuel[$date->format('Y-m')]['nb_commandes'] ?? '-';
            $nb_remboursements = $statDataMensuel[$date->format('Y-m')]['nb_remboursements'] ?? '-';
            $ca_reel = $statDataMensuel[$date->format('Y-m')]['ca_reel'] ?? '-';
            $ca_alim = $statDataMensuel[$date->format('Y-m')]['ca_alim'] ?? '-';
            // $ca_reel_precedent = $statDataMensuel[($currentYear - 1) . '-' . $date->format('m')]['ca_reel'] ?? null;
            // $variation_ca_precedent = !empty($ca_reel_precedent) ? (100 * (1 - ($ca_reel / $ca_reel_precedent))) . '%' : '-';
            $frais_bancaires = $statDataMensuel[$date->format('Y-m')]['frais_bancaires'] ?? '-';
            $reductions = $statDataMensuel[$date->format('Y-m')]['reductions'] ?? '-';
            $remboursement_produits = $statDataMensuel[$date->format('Y-m')]['remboursements_produits'] ?? '-';
            $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: #1c6fb6;'>" . (\is_numeric($ca_alim) ? \round(\floatval($ca_alim)) . '&nbsp;€' : '-') . '</span>',
                "<span style='color: #3b3b3b;'>" . $nb_commandes . '</span>',
                "<span style='color: #1c6fb6;'>" . $ca_reel . '&nbsp;€</span>',
                // "<span style='color: " . ($variation_ca_precedent >= 0 ? "#4d8956" : "#ae293c") . ";'>" . round($variation_ca_precedent) . "&nbsp;%</span>",
                "<span style='color: #ae293c;'>" . $frais_bancaires . '&nbsp;€</span>',
                "<span style='color: #ae293c;'>" . $reductions . '&nbsp;€</span>',
                "<span style='color: #3b3b3b;'>" . $nb_remboursements . '</span>',
                "<span style='color: #ae293c;'>" . $remboursement_produits . '&nbsp;€</span>',
                "<span style='color: grey;'>" . $ca_hors_reductions . '&nbsp;€</span>',
            ];
        }

        $ret[] = [
            'type' => 'datatable-columns',
            'tab' => 'resume',
            'title' => 'Statistiques mensuelles',
            'params' => [
                'rows' => [
                    '',
                    '<strong>CA alim net estimé HT</strong>',
                    '<strong>Commandes</strong>',
                    '<strong>CA HT</strong>',
                    // "<strong style='color: grey;'>% CA vs Année-1</strong>",
                    "<strong style='color: grey;'>Frais bancaires</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,
                'ca_alim' => 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`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ')
                    AND `o`.`invoice_date` >= "' . ($year - $i) . '-01-01" AND `o`.`invoice_date` <= "' . ($year - $i) . '-' . date('m-d') . ' 23:59:59"
                    GROUP BY YEAR(`o`.`invoice_date`)',
                false
            );
            $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`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ')
                    AND `os`.`date_add` >= "' . ($year - $i) . '-01-01" AND `os`.`date_add` <= "' . ($year - $i) . '-' . date('m-d') . ' 23:59:59"
                    GROUP BY YEAR(`os`.`date_add`)',
                false
            );
            // TODO
            $infos3 = $db->getRow(
                'SELECT
                    SUM(`od`.`total_price_tax_excl`) AS ca_alim
                    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` = `o`.`id_order`
                    INNER JOIN `ps_product` `p` ON `p`.`id_product` = `od`.`product_id`
                    WHERE `o`.`id_carrier` IN (' . \implode(',', $carriers) . ')
                    AND `o`.`invoice_date` >= "' . ($year - $i) . '-01-01" AND `o`.`invoice_date` <= "' . ($year - $i) . '-' . date('m-d') . ' 23:59:59"
                    AND `p`.`id_category_default` IN (' . \implode(',', $alimCatIds) . ')
                    GROUP BY YEAR(`o`.`invoice_date`)',
                false
            );

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

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

        // Applique les réductions sur le CA alim
        foreach ($infos as &$yearInfo) {
            $yearInfo['ca_alim'] -= $yearInfo['remboursements_produits'];
            $yearInfo['ca_alim'] -= $yearInfo['reductions'];
            // Frais bancaires
            $fraisBancaires = ($yearInfo['ca_hors_reductions'] * 1.2 * 0.004)
                + ($yearInfo['nb_commandes'] * 0.1);
            $yearInfo['ca_alim'] -= $fraisBancaires;
        }

        $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>CA alim net estimé HT</strong><br>du 01/01/" . $yearRecap . ' au ' . $endOfRecapYear,
                    'value' => \round($infos[$yearRecap]['ca_alim']) . ' €',
                ],
                */
                [
                    '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, (string) ($yearRecap - 1), $endOfRecapYear),
                'value' => \round($caReelYearBefore) . ' €',
            ];
        }

        $ret[] = $statAnnee;

        // ///////////////////////////////////////
        // / Statistiques par labo
        $manufacturersMateriel =
            $db->executeS(
                'SELECT `id_manufacturer` FROM `ps_manufacturer` WHERE `name` = "MATERIEL"',
                true,
                false
            );

        if (!is_array($manufacturersMateriel)) {
            $manufacturersMateriel = [];
        } else {
            $manufacturersMateriel = \array_map(
                fn (array $row) => (int) $row['id_manufacturer'],
                $manufacturersMateriel
            );
        }

        $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` = `o`.`id_order`
                    INNER JOIN `ps_product` `p` ON `p`.`id_product` = `od`.`product_id`
                    INNER JOIN `ps_manufacturer` `m` ON `m`.`id_manufacturer` = `p`.`id_manufacturer`
                    WHERE `o`.`id_carrier` IN (" . \implode(',', $carriers) . ")
                    AND `o`.`invoice_date` >= DATE_FORMAT(NOW() - INTERVAL 366 DAY, '%Y-%m-%d')
                    AND `p`.`id_manufacturer` NOT IN (" . \implode(',', $manufacturersMateriel) . ')
                    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',
            true,
            false
        );
        $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 = [];

        $i = 0;
        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;€']);
            ++$i;
        }

        $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<mixed>|string
     */
    public function getContent()
    {
        if (!$this->objOutput) {
            return [];
        }

        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
