<?php

namespace Modules\DemandeAchat\Controller;

use Entity\Model\SocUser;
use Modules\DemandeAchat\Outil\FormArray;
use Modules\DemandeAchat\Service\CreationDemandeAchatService;
use Modules\DemandeAchat\Validator\CreationValidator;
use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Trad\ITrad;

class CreationDemandeAchatController extends Controller
{
    private CreationDemandeAchatService $service;

    /**
     * trad
     *
     * @var ITrad
     */
    private $trad;

    public function init(): void
    {
        $this->service = new CreationDemandeAchatService(
            $this->pdo,
            $this->getTranslationService()
        );

        $this->trad = $this->getTranslationService();
    }

    public function creationAction(): string
    {
        $post = $this->request->getParsedBody();
        $user = (new \Entity\Model\Hastutil($this->pdo))
            ->find($_SESSION['Session_Login']);

        /*** INITIALISATION ***/
        if (!$post) {
            $post = $this->service
                ->initPurchaseRequest();
        }

        if (($post['MODIF_STE'])) {
            /* initialisation en fonction de la société */
            if ($post['CODE_STE'] == $_SESSION['Session_SocUsrProfil']) {
                // Si société de l'utilisateur
                /* Centre de livraison */
                $post['CTR_LIV'] = $user['CTRLIV'];
                /* Centre émetteur */
                $post['DAENT_CENTRE_EMETTEUR'] = $user['CTR_ADR'];
                /* Axes imputations */
                $post['SECTIMP'] = $user['SI'];
                $post['CODECOMP'] = $user['CDC'];
                $post['SSCPTEANA'] = $user['SCA'];
            } else {
                $company = (new SocUser($this->pdo))
                    ->find([
                        'COD_USR' => $_SESSION['Session_Login'],
                        'COD_STE' => $post['CODE_STE']
                    ]);
                /* Centre de livraison */
                $post['CTR_LIV'] = $company['CTRLIVR'] ?? '';
                /* Centre émetteur */
                $post['DAENT_CENTRE_EMETTEUR'] = $company['CTREMET'] ?? '';
                /* Axes imputations */
                $post['SECTIMP'] = $company['CODSI'] ?? '';
                $post['CODECOMP'] = $company['CODCDC'] ?? '';
                $post['SSCPTEANA'] = $company['CODSCA'] ?? '';
            }
        }

        $params = $this->service->getCreationParams($post);

        /************ PARAMETRAGE VUE *****************/
        $formArray = FormArray::getFormArrays($this->trad);

        Ariane::generate(2, $this->trad->t('Nouvelle demande d\'achat'));

        return $this->renderer->render('@DemandeAchat/Creation/Heading/heading', [
            'menuActive' => 'CollecteBesoins',
            'menuLeft' => 'GestionDemandeAchat',
            'da' => $post,
            'params' => $params,
            'tabLangues' => $this->service->getLanguages(),
            'tabTypeChiffExecution' => $formArray['typeChiffExec'],
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'tabTypeDate' => $formArray['tabTypeDate'],
            'tabTransport' => $this->service->getTransportOptions(),
        ]);
    }

    public function validationAction()
    {
        $post = $this->request->getParsedBody();

        $validator = new CreationValidator($this->pdo, $this->trad);

        $validator->validateCreateFormEntet($post['NO_DA'] ?? '', $post);

        if (!$validator->isValid()) {
            if (!$post['submitForce']) {
                $params = [
                    'alerte' => $validator->getError(),
                    'avertissement' => $validator->getErrorNonBloquant(),
                    'action' => 'creation',
                ];
                return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                    'params' => $params,
                ]);
            }
            if ($validator->getError() != '') {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        }

        $result = $this->service->createPurchaseRequestHeading($post);

        if ($result['status'] == 'O') {
            return $this->createJsonResponse([
                'statut' => 'O',
                'path' => $this->router->generateUri(
                    'DemandeAchat.ModificationDemandeAchat.index',
                    [
                        'onglet' => 'Article',
                        'MODULE' => 'GestionDemandeAchat',
                        'idDA' => $result['NO_DA'],
                        'mode' => 'Creation'
                    ]
                ),
            ], 443);
        }

        return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
            'params' => [
                'alerte' => $result,
            ],
        ]);
    }

    public function transportAction(): Response
    {
        $post = $this->request->getParsedBody();
        $params = $this->service->getCreationParams($post);

        return $this->createJsonResponse([
            'result' => $this->renderer->render('@DemandeAchat/Creation/Heading/_requestor', [
                'menuActive' => 'CollecteBesoins',
                'menuLeft' => 'GestionDemandeAchat',
                'da' => $post,
                'params' => $params,
                'tabTransport' => $this->service->getTransportOptions(),
            ])
        ]);
    }

    public function changeCompanyAction(): Response
    {
        $post = $this->request->getParsedBody();
        $params = $this->service->getCreationParams($post);
        $formArray = FormArray::getFormArrays($this->trad);

        return $this->createJsonResponse([
            'result' => $this->renderer->render('@DemandeAchat/Creation/Heading/_request', [
                'menuActive' => 'CollecteBesoins',
                'menuLeft' => 'GestionDemandeAchat',
                'da' => $post,
                'params' => $params,
                'tabLangues' => $this->service->getLanguages(),
                'tabTypeChiffExecution' => $formArray['typeChiffExec'],
                'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                'tabPeriodicite' => $formArray['tabPeriodicite'],
                'tabPeriode' => $formArray['tabPeriode'],
                'tabJoursAppli' => $formArray['tabJoursAppli'],
                'tabTypeDate' => $formArray['tabTypeDate'],
                'tabTransport' => $this->service->getTransportOptions(),
            ])
        ]);
    }
}
