<?php
namespace Modules\Suivi\Controller;

use Entity\Model\OxaSuiviRequete;
use Entity\Model\TpEnt;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Validator\Validator;
use Modules\Panier\Service\ControlePanierService;
use Modules\Panier\Service\PanierLigneService;
use Modules\Suivi\Service\ChargeDocToPanierService;
use Modules\Suivi\Service\DuplicateCdeService;
use Modules\Suivi\Service\DuplicateDAService;
use Modules\Suivi\Service\RelanceService;
use Skeleton\Controller\Controller;
use Helpers\Session\ParseBase1;

class SuiviController extends Controller
{
    /**
     * @return Response|string
     */
    public function addRequeteAction()
    {
        $module = $this->request->getAttribute('module');
        $post   = $this->request->getParsedBody();
        
        $validator = new Validator($this->pdo, $this->getTranslationService());
        $validator->isStringAvecEspace($this->getTranslationService()->t('Libellé de la recherche'), $post['LIB_FAV'], 1, 255);

        if ($validator->isValid()) {
            $libFav = $post['LIB_FAV'];
            unset($post['LIB_FAV']);
            unset($post['page']);
            unset($post['postJson']);
            unset($post['idRequete']);
            foreach ($post as $k => $v) {
                if (strpos($k, 'text_') === 0) {
                    unset($post[$k]);
                }
            }

            (new OxaSuiviRequete($this->pdo))->insert([
                'ID_REQUETE'    => 'ID' . $_SESSION['id_user'] . '_' . time(),
                'ID_USER'       => $_SESSION['id_user'],
                'CODE_STE'      => $post['filter_egal_CODE_STE'] ?? $post['societe'],
                'TYPE_SUIVI'    => $module,
                'LIBELLE'       => $libFav,
                'VALEUR'        => json_encode($post),
                'COMPTEUR'      => '0',
                'DATE_CREA'     => date('Ymd'),
                'DATE_MODIF'    => date('Ymd')
            ]);

            return new Response(443);
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid'   => $validator->getError(),
                'desactiveRow'  => true,
            ]);
        }
    }

    public function deleteRequeteAction() : string
    {
        $idRequete = $this->request->getAttribute('idRequete');

        (new OxaSuiviRequete($this->pdo))->delete($idRequete);

        return '';
    }

    public function relanceAction() : string
    {
        $typeRelance    = $this->request->getAttribute('typeRelance');
        $idDoc          = $this->request->getAttribute('idDoc');

        return $this->renderer->render('@suivi/Global/relance', [
            'arrayRelance' => (new RelanceService($this->router, $typeRelance, $idDoc))->relance()
        ]);
    }

    /**
     * @return Response|string
     */
    public function ajaxRelanceAction()
    {
        $post       = $this->request->getParsedBody();

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

        $validator->adresseMail($trad->t('Destinataire'), $post['destinataire'], 1, 300, true);
        $validator->isStringAvecEspace($trad->t('Sujet'), $post['sujet'], 0, 150);
        $validator->isStringAvecEspace($trad->t('Corps'), $post['corps'], 0, 3000);

        if ($validator->isValid()) {
            $post['message'] = $post['corps'];
            $post['destinataires'] =  $post['destinataire'];

            if ($post['pj']??'') {
                $post['pj'] = [0 => (new ParseBase1())->getRep()->tmp.($post['pj'])];
            }
            $envoiMail = \Modules\Ajax\Controller\MailController::envoiMail($post);

            if ($envoiMail->Retour=="O") {
                return $this->renderer->render('@popup-erreur/information', [
                    'message' => $trad->t('Le mail a été envoyé.')
                ]);
            } else {
                return new Response(443, [], (string)json_encode([
                    'erreur' => $envoiMail->MsgErreur,
                ]));
            }
        } else {
            return new Response(443, [], (string)json_encode([
                'erreur' => $validator->getError(),
            ]));
        }
    }

    /**
     * @return Response
     */
    public function ajaxChargeDocToPanierAction()
    {
        $action         = $this->request->getAttribute('action');
        $typeDoc        = $this->request->getAttribute('typeDoc');
        $idDoc          = $this->request->getAttribute('idDoc');
        $actuFrs        = $this->request->getAttribute('actuFrs');
        $post           = $this->request->getParsedBody();
        $trad           = $this->getTranslationService();

        $post       = json_decode($post['postJson']??'', true);
        
        if ($typeDoc == 'DA') {
            $duplicateObj = new DuplicateDAService($this->pdo, $trad, $idDoc, $action, $post);
        } else {
            $duplicateObj = new DuplicateCdeService($this->pdo, $trad, $idDoc, $action, $post);
        }
        $duplicateObj->duplicateItem();
        
        
        $controlePanierService = new ControlePanierService($this->pdo, $this->pdoOxaFT);
        $controlePanierService->controlePanier($actuFrs == '1'? true:false);

        return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Panier.Panier.index')]));
    }

    /**
     * @return mixed
     */
    public function popChargeDocToPanierAction(
        TpEnt $tpEnt
    ) {
        $action         = $this->request->getAttribute('action');
        $typeDoc        = $this->request->getAttribute('typeDoc');
        $idDoc          = $this->request->getAttribute('idDoc');
        $trad           = $this->getTranslationService();

        
        $chargeToDoc    = new ChargeDocToPanierService($this->pdo, $this->renderer, $this->router, $this->getTranslationService());

        $post           = $this->request->getParsedBody(true);
        
        $returnStep1 = $chargeToDoc->controleDocument($this->pdoOxaFT, $action, $typeDoc, $idDoc, $post);
        if ($returnStep1) {
            return $returnStep1;
        }
        
        $returnStep2 = $chargeToDoc->controlePJClause($action, $typeDoc, $idDoc, $post);
        if ($returnStep2) {
            return $returnStep2;
        }
                
        // Step 3, redirection vers le panier / ou pour les DA, on demande quel genre de redirection vers le panier
        if ($typeDoc == 'DA') {
            return $this->renderer->render('@suivi/Global/popupModeChargement', [
                'typeDoc'               => $typeDoc,
                'idDoc'                 => $idDoc,
                'action'                => $action,
                'postJson'              => json_encode($post),
                'hasTP'                 => count($tpEnt->findAll(['NUM_CDE' => $idDoc, 'TYPEOBJ' => 'DA_ENTET'])) > 0 ? true : false
            ]);
        } else {
            $duplicateObj = new DuplicateCdeService($this->pdo, $trad, $idDoc, $action, $post);
            $duplicateObj->duplicateItem();

            return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Panier.Panier.index')]));
        }
    }

    public function cancelAction() : string
    {
        $chargeToDoc = new ChargeDocToPanierService($this->pdo, $this->renderer, $this->router, $this->getTranslationService());
        $chargeToDoc->deletePanier();

        return $this->renderer->render('@popup-erreur/information', [
            'message' => $this->getTranslationService()->t('Le chargement a été annulé.'),
        ]);
    }

    public function popupConfirmationAction() : string
    {
        $post       = $this->request->getParsedBody();

        return $this->renderer->render('@suivi/Global/popupConfirmation', [
            'message'       => $post['Message'],
            'path'          => $post['Path'],
            'pathRefresh'   => $post['pathRefresh'],
            'div'           => $post['div'],
            'form'          => $post['form'],
        ]);
    }
}
