<?php

namespace Modules\Parametrage\API\Controller;

use Entity\Model\Dilispec;
use GuzzleHttp\Psr7\Response;
use Helpers\Form\FormBuilder;
use Skeleton\Controller\Controller;

class ParametrageApiCsdController extends Controller
{
    private function getDiliCode() :string
    {
        return 'CSD';
    }

    /**
     * @return \GuzzleHttp\Psr7\Response|string
     * @throws \Exception
     */
    public function indexAction()
    {
        return $this->renderer->render('@ParamAPI/Api/formApiParam', [
            'form' => $this->getForm(),
            'subject' => (new Dilispec($this->pdo))->getMap(
                $this->getDiliCode()
            ),
            'label' => 'CSD',
        ]);
    }
    
    public function updateAction() :Response
    {
        $post = $this->request->getParsedBody();

        $validator = $this->createFormValidator();
        $form = $this->getForm();

        $post = $validator->validateForm($form, $post);
        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //____________

        $qb = new Dilispec($this->pdo);

        $this->pdo->beginTransaction();

        $mainKey = ['TYPEDICO' => $this->getDiliCode()];
        $qb->delete($mainKey);
        foreach ($post as $key => $value) {
            $qb->insert($mainKey + [
                'CODEDICO' => $key,
                'LIB01DICO' => $value,
            ]);
        }
        $qb->insert($mainKey + [
            'CODEDICO' => 'TYPE_ENVIRONNEMENT',
            'LIB01DICO' => 'P',
        ]);
        
        $this->pdo->commit();

        return new Response(200);
    }

//______________________________________________________________________________
// Sub-routine

    /**
     * @return array<\stdClass>
     */
    private function getForm()
    {
        return (new FormBuilder())
            ->addText('API_KEY', 200)
            ->addSelect('FOURNISS_FIELD', [
                'NO_SIRET' => 'TAXE 1',
                'TAXE2' => 'TAXE 2',
                'TAXE3' => 'TAXE 3',
                'TAXE4' => 'TAXE 4',
            ])
            ->build()
        ;
    }
}
