<?php

namespace Modules\Ajax\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\CaracCompl\CaracCompl;
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'];

        $listeValue = [];
        foreach ($listeCC as $cc) {
            $exp_calcul = Outils::replaceVariable($cc['CC_CALC_EXP'], $post, '<>');

            $resultat = 0;
            try {
                eval("\$resultat = {$exp_calcul};");
            } catch (\ParseError $p) {
                $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,
        ]));
    }
}
