<?php

namespace Modules\Ajax\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\CaracCompl\CaracCompl;
use Helpers\Log\LogSysteme;
use Helpers\Outil\Outils;
use Skeleton\Controller\Controller;

class CaracComplController extends Controller
{
    /**
     * @return Response
     */
    public function calcCCAction()
    {
        $post = $this->request->getParsedBody();

        $init       = $post['init']??'';
        $typeDoc    = $post['typeDoc']??'';
        $idDoc      = $post['idDoc']??'';
        $idLigne    = $post['idLigne']??'';
        $idPanier   = $post['idPanier']??'0';
        $article    = $post['article']??'';
        $ssFamille  = $post['ssFamille']??'';
        $famille    = $post['famille']??'';

        
        $caracCompl = new CaracCompl($this->pdo, $article, $ssFamille, $famille);
        if ($init) {
            $listeCC = $caracCompl->getListeCCInit(true);
        } else {
            $listeCC = $caracCompl->getCCDocc($typeDoc, $idDoc, $idLigne, $idPanier, true);
        }

        foreach ($post as $key => $val) {
            if (strpos($key, 'input_') === 0) {
                $post[substr($key, 6)] = $val;
            }
        }
        
        $post['MNT_LIG_TTC'] = ($post['PU'] * $post['QTE']) * (1+($post['TVA']/100));
        $post['MNT_LIG_HT'] = $post['PU'] * $post['QTE'];

        $cleanPost = array_map(function ($v) {
            if (floatval($v) == '0' || $v == '') {
                return '';
            } else {
                return floatval($v);
            }
        }, $post);

        $listeValue = [];
        foreach ($listeCC as $cc) {
            $exp_calcul = Outils::replaceVariable($cc['CC_CALC_EXP'], $post, '<>');
            
            $resultat = 0;
            try {
                eval("\$resultat = {$exp_calcul};");
            } catch (\Throwable $e) {
                LogSysteme::prefixErrorLog('CaracComp eval: '. $e->getMessage());
                $resultat = 0;
            }
            
            $listeValue[] = [
                'ID_CC' => $cc['CC_ID'],
                'VALUE' => number_format($resultat, $cc['PD_LONG'], '.', ' '),
            ];
        }

        

        return new Response(200, [
            
        ], (string) \json_encode([
            'statut' => 'O',
            'listeValueObject' => $listeValue,
        ]));
    }
}
