<?php

namespace Modules\Stock\Controller;

use Entity\Model\Tiers;
use Exception;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Filter\FiltreAvance\GeneratorCs;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Modules\Stock\Enum\EmptyEnum;
use Modules\Stock\Helper\CodeHelper;
use Modules\Stock\Repository\TiersRepo;
use Modules\Stock\Trait\Controller\StockContollerTrait;
use Modules\Stock\Validator\TiersValidator;
use Skeleton\Controller\Controller;

class TiersController extends Controller
{
    use StockContollerTrait;

    /**
     * @throws Exception
     */
    public function gestionAction(): string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        Ariane::generate(0, $trad->t('Gestion'), [], null, $this->router->generateUri('Stock.Tiers.gestion'));

        (new PaginatorGestion())->generate(20, 'CODE');
        $tiersResults = (new TiersRepo($this->pdo))->listTiers($post);
        $infoPagination = PaginatorGestion::getInfoPagination();

        $filtreAvance = new GeneratorCs($post, 'TIERS', 'CODE', $this->pdo, $trad);
        $filtreAvance->setFiltre('CODE', 'text', $trad->t('Code'));
        $filtreAvance->setFiltre('RS', 'text', $trad->t('Nom destinataire'));
        $filtreAvance->setFiltre('ADR', 'text', $trad->t('Adresse'));
        $filtreAvance->setFiltre('CPOSTAL', 'text', $trad->t('Code postal'));
        $filtreAvance->setFiltre('VILLE1', 'text', $trad->t('Ville'));
        $filtreAvance->setFiltre('PAYS', 'text', $trad->t('Pays'));
        $filtreAvance->setFiltre('DTE_OUV', 'date', $trad->t('Date ouverture'));
        $filtreAvance->setFiltre('DTE_FER', 'date', $trad->t('Date fermeture'));

        return $this->renderer->render('@Stock/Tiers/gestion', [
            'post'             => $post,
            'menuActive'       => 'Stock',
            'tiersResults'     => $tiersResults,
            'infoPagination'   => $infoPagination,
            'initFiltreAvance' => $filtreAvance->getInit(),
            'filtreAvance'     => $filtreAvance->getFiltres(),
            'emptyParam'       => EmptyEnum::EMPTY_PARAM->value,
            'hasCreateEditAccessRights' => (bool) Roles::droitsUtilisateur($this->pdo, 'ST_TIE_CM')
        ]);
    }

    /**
     * @throws Exception
     */
    public function nouveauFormAction(): string
    {
        $trad = $this->getTranslationService();

        Ariane::generate(
            1,
            $trad->t('Création d\'un tiers'),
            [],
            null,
            $this->router->generateUri('Stock.Tiers.nouveauForm')
        );

        return $this->renderer->render('@Stock/Tiers/nouveau_form', [
            'dateJour' => date('Ymd'),
        ]);
    }

    /**
     * @throws Exception
     */
    public function nouveauAction(): Response
    {
        $post = $this->request->getParsedBody();

        $tiers = $post['TIERS'];
        $validator = new TiersValidator($this->pdo, $this->getTranslationService());
        $validator
            ->validateCode($tiers)
            ->validateRs($tiers)
            ->validateAdr($tiers)
            ->validatePays($tiers)
            ->validateCpostal($tiers)
            ->validateVille1($tiers)
            ->validateDteOuv($tiers)
            ->validateDteFer($tiers)
        ;

        if ($validator->isValid()) {
            $tiers['TEL'] = '';
            $tiers['CTCT'] = '';
            $tiers['NO_TVA_IC'] = '';
            $tiers['VILLE'] = $tiers['CPOSTAL'] . ' ' . $tiers['VILLE1'];

            $this->pdo->beginTransaction();
            (new Tiers($this->pdo))->merge($tiers);
            $this->pdo->commit();

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

    /**
     * @throws Exception
     */
    public function modifierFormAction(): string|Response
    {
        $trad = $this->getTranslationService();
        $code = CodeHelper::getCodeFromParam($this->request->getAttribute('code'));
        if (!$tiers = (new Tiers($this->pdo))->find(['CODE' => $code])) {
            return $this->create404Response('Ce tiers n\'existe pas');
        }

        Ariane::generate(
            1,
            $trad->t('Modification d\'un tiers'),
            [],
            null,
            $this->router->generateUri('Stock.Tiers.modifierForm')
        );

        return $this->renderer->render('@Stock/Tiers/modifier_form', [
            'tiers' => $tiers,
            'emptyParam' => EmptyEnum::EMPTY_PARAM->value,
        ]);
    }

    /**
     * @throws Exception
     */
    public function modifierAction(): Response
    {
        $post = $this->request->getParsedBody();
        $code = CodeHelper::getCodeFromParam($this->request->getAttribute('code'));
        if (!$tiers = (new Tiers($this->pdo))->find(['CODE' => $code])) {
            return $this->createJsonResponse(['statut' => 'Not found', 'message' => 'Ce tiers n\'existe pas'], 404);
        }

        $tiers = array_merge($tiers, $post['TIERS']);
        $validator = new TiersValidator($this->pdo, $this->getTranslationService());
        $validator
            ->validateRs($tiers)
            ->validateAdr($tiers)
            ->validatePays($tiers)
            ->validateCpostal($tiers)
            ->validateVille1($tiers)
            ->validateDteOuv($tiers)
            ->validateDteFer($tiers)
            ->validateCode($tiers, false)
        ;

        if ($validator->isValid()) {
            $this->pdo->beginTransaction();
            (new Tiers($this->pdo))->merge($tiers);
            $this->pdo->commit();

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