<?php

namespace Modules\Parametrage\Facture\Controller;

use Modules\Parametrage\Facture\Service\ParamFactureService;
use Skeleton\Controller\Controller;
use Helpers\Trad\ITrad;
use Modules\Parametrage\Facture\Repository\ParametrageLAD;

class ParametrageAjaxController extends Controller
{
    public string $menuActive = '';
    public string $menuLeft = '';
    public ITrad $trad;

    public function ligneArticlesAction(): string
    {
        // Au premier affichage, affichage des 5 premières lignes
        $post = $this->request->getParsedBody();
        $codeFournisseur = $this->request->getAttribute('codeFournisseur');
        $post['societe'] = $this->request->getAttribute('societe');

        $parametrageRepository = new ParametrageLAD($this->pdo);
        $listes = $parametrageRepository->listeArticlesAutoFournisseur($codeFournisseur, $post);

        if (!isset($listes[0]['ART_SANS_CMD'])) {
            $parametrageRepository->deleteFournisseurArticlePourcentage(['COD_FRS' => $listes[0]['CODE']]);
        } elseif (!ParamFactureService::calculPourcentage($listes[0]['ART_SANS_CMD'])) {
            $parametrageRepository->recalculPourcentage($listes[0]['CODE'], $listes[0]['ART_SANS_CMD']);
            $listes = $parametrageRepository->listeArticlesAutoFournisseur($codeFournisseur, $post);
        }


        $trad = $this->getTranslationService();

        return $this->renderer->render('@ParamFac/ligneArticles', [
            "trad" => $trad,
            "listes" => $listes
        ]);
    }
}
