<?php

namespace Modules\Stock\Controller;

use DateTime;
use Entity\Model\Sarticle;
use Entity\Model\SSiteSto;
use Exception;
use Modules\Stock\Helper\DateHelper;
use Modules\Stock\Repository\CumulAnnuelRepo;
use Modules\Stock\Repository\CumMensRepo;
use Skeleton\Controller\Controller;

class StatisticsController extends Controller
{
    /**
     * @throws Exception
     */
    public function cumulsConsoAction(): string
    {
        $cumMensRepo = new CumMensRepo($this->pdo);
        $site = $this->request->getAttribute('site');
        $codeArt = $this->request->getAttribute('codeArt');
        $conso12derniersMoisGlissants = $cumMensRepo->getConso12DerniersMoisGlissants($codeArt, $site);

        $conso12derniersMoisGlissants = array_map(function (array $conso) {
            $mois = substr($conso['DATEVALEUR'], -2);
            $conso['MOIS'] = (new DateHelper($this->getTranslationService()))->getNomMois($mois);
            $conso['ANNEE'] = substr($conso['DATEVALEUR'], 0, 4);

            return $conso;
        }, $conso12derniersMoisGlissants);

        $cumulGlissant = array_sum(array_column($conso12derniersMoisGlissants, 'CONSO'));
        $moyenneGlissante = $cumulGlissant / 12;
        $consoMoisEnCours = $cumMensRepo->getConsoMoisEnCours($codeArt, $site);
        $conso3dernieresAnnees = array_map(function (array $conso) {
            $today = new DateTime('now');
            $currentYear = $today->format('Y');

            if ($currentYear !== $conso['ANNEE']) {
                $conso['AVG'] = (int) $conso['CONSO'] / 12;
            } else {
                $currentMonth = (int) $today->format('n');
                $currentDayOfMonth = (int) $today->format('j');
                $nbDaysInCurrentMonth = (int) $today->format('t');
                $prorataTemporis = (($currentMonth - 1) + ($currentDayOfMonth / $nbDaysInCurrentMonth));

                $conso['AVG'] = (int) $conso['CONSO'] / $prorataTemporis;
            }

            return $conso;
        }, (new CumulAnnuelRepo($this->pdo))->getConso3DernieresAnnees($codeArt, $site));

        return $this->renderer->render('@Stock/Statistics/cumuls_conso', [
            'cumulGlissant' => $cumulGlissant,
            'moyenneGlissante' => $moyenneGlissante,
            'consoMoisEnCours' => $consoMoisEnCours,
            'conso3dernieresAnnees' => $conso3dernieresAnnees,
            'siteStock' => (new SSiteSto($this->pdo))->find($site),
            'conso12derniersMoisGlissants' => $conso12derniersMoisGlissants,
            'stockArticle' => (new Sarticle($this->pdo))->find(['CODE_ART' => $codeArt])
        ]);
    }
}
