<?php

namespace Modules\Stock\Controller\Parametrage;

use Entity\Model\Parametr;
use Exception;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use Helpers\Validator\Validator;
use Modules\Stock\Trait\Controller\StockContollerTrait;
use Skeleton\Controller\Controller;

class ParametreController extends Controller
{
    use StockContollerTrait;

    public function deviseFormAction(): string
    {
        $trad = $this->getTranslationService();

        Ariane::generate(0, $trad->t('Paramétrage global'), [], null, $this->router->generateUri('Stock.Parametrage.deviseForm'));

        return  $this->renderer->render('@Stock/Parametrage/Parametre/devise', [
            'menuActive' => 'Stock',
            'current_route' => $this->router->getNameRoute(),
            'menuLeft' => 'Stock.GestionParametrage.numerotation',
            'parametre' => (new Parametr($this->pdo))->find(['CLE' => 1]),
        ]);
    }


    /**
     * @throws Exception
     */
    public function deviseAction(): string|Response
    {
        $parametr = new Parametr($this->pdo);
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();
        $validator = new Validator($this->pdo, $trad);

        $parametre = $post['PARAMETR'];
        $validator->isStringSansEspace($trad->t('Devise de stockage'), $parametre['STDEVSTK'], 0, 10);

        if ($validator->isValid()) {
            $parametre['STGSTEUR'] = Sql::toBool($parametre['STGSTEUR']);
            $parametr->updateEntity(['CLE' => 1, ...$parametre]);

            return $this->createJsonResponse([
                'statut' => 'OK',
                'redirectRoute' => $this->router->generateUri('Stock.Parametrage.deviseForm')
            ]);
        } else {
            return $this->createBloquantJsonErrorResponse([], $validator->getError());
        }
    }
}
