<?php
namespace Modules\API\APIExterne\Controller;

use API\Altares\IntuizPartenaire;
use API\Partenaire\Service\PartenaireService;
use GuzzleHttp\Psr7\Response;
use Helpers\Highcharts\Highcharts;
use Helpers\Log\LogSysteme;
use Helpers\Trad\Trad;
use Modules\Fournisseur\Controller\FournisseurController;
use Skeleton\Controller\Controller;
use Entity\Model\Fourniss;

class IntuizController extends Controller
{

    private function getPartn() :IntuizPartenaire
    {
        return $this->contenaire
            ->get(PartenaireService::class)
            ->getByCode('ALTARES');
    }

    public function rattacherAction() :Response
    {
        $fournissId = $this->request->getAttribute('fournissId');
        $fourniss = (new Fourniss($this->pdo))->find($fournissId);
        if (empty($fourniss)) {
            return new Response(404);
        }

        try {
            $this->getPartn()
                ->linkFourniss($fourniss);
        } catch (\Exception $e) {
            // TODO : Une erreur s'est produite, vérifié que le numéro siret est correcte
            LogSysteme::prefixErrorLog($e->__toString());
            $trad = $this->getTranslationService();
            return new Response(400, [], Trad::strBuild(
                $trad->t('Le numéro SIRET "@1@" est inconnu'),
                $fourniss['NO_SIRET']
            ));
        }
        
        return $this->createJsonResponse([
            'action' => 'pageRefresh',
        ]);
    }

    public function detacherAction() :Response
    {
        $idFournisseur = $this->request->getAttribute('fournissId');
        
        $this->getPartn()->unlinkFourniss($idFournisseur);
        
        return new Response(200);
    }

    public function detailAction() : string
    {
  
        $post = $this->request->getParsedBody();
        $fournissId = $this->request->getAttribute('fournissId');

        $fourniss = (new Fourniss($this->pdo))->find($fournissId);
        if ($fourniss == null) {
            throw new \Exception('Invalid fourniss id "'.$fournissId.'"');
        }

        $altares = $this->getPartn();
        (new FournisseurController($this->renderer, $this->pdo, $this->router, $this->contenaire))
            ->arianeSubGenerate($fournissId, $altares->getCode(), $post);
        
        $info = $altares->getFullDetail($fournissId);

        $mapScoreSecteur = array_column(
            $info['HistoriqueScore']['listScoreSecteur'],
            null,
            'dateValeur',
        );
        
        $scoreMoyen = array_sum(
            array_column(
                $info['HistoriqueScore']['listScore'],
                'scoreVingt'
            )
        ) / count($info['HistoriqueScore']['listScore']);
        $listScore = $info['HistoriqueScore']['listScore'];
        usort($listScore, function ($a, $b) {
            return $a['dateValeur'] <=> $b['dateValeur'];
        });
        $array = [];
        foreach ($listScore as $score) {
            $array['value'][ $score['dateValeur'] ] = [
                'score' => $score['scoreVingt'],
                'scoreP' => $mapScoreSecteur[ $score['dateValeur'] ]['scoreVingt'],
            ];
            $array['categorie'][] = $score['dateValeur'];
        }
        
        $trad = $this->getTranslationService();
        return $this->renderer->render('@API/Altares/detail', $info + [
            // 'menuLeft' => 'GestionFournisseur',
            // 'menuActive' => 'Fournisseur',
            'hightchart' => Highcharts::generate($array + [
                'titre' => $trad->t('Evolution du score par mois'),
                'type' => 'column',
                'detailColone' => [
                    'score' => [
                        'nom' => $trad->t('Fournisseur'),
                        'type' => 'spline',
                        'axeLier' => 'gauche',
                    ],
                    'scoreP' => [
                        'nom' => $trad->t('Secteur d\'activité'),
                        'type' => 'spline',
                        'axeLier' => 'gauche',
                    ],
                    
                ],
                'legendGraph' => [
                    [
                        'texte' => $trad->t('Score sur 20'),
                        'format' => '',
                        'axe' => 'gauche'
                    ],
                ],
            ], $this->pdo, $this->getTranslationService()),
            'fourniss' => $fourniss,
            'scoreMoyen' => $scoreMoyen,
            //'dataHighchart' => Highcharts::generate($array, $this->pdo),
        ]);
    }

    public function batchAction(string $numeroTraitement = null) : string
    {
        return $this->getPartn()->batch($numeroTraitement ?? (time() . ''));
    }
}
