<?php

namespace Modules\DemandeAchat\Controller;

use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Sql;
use Modules\DemandeAchat\Repository\ModificationPrixLignes;
use Helpers\Trad\Trad;
use Helpers\Parametres\Constante;

class ModificationPrixLigneDemandeAchatController extends Controller
{

    public function modificationPrixLignesAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $mode = $this->request->getAttribute('mode');
        $MODULE = $this->request->getAttribute('MODULE');

        $modifPrix = new ModificationPrixLignes($this->pdo);
        $demandeAchat = $modifPrix->demandeAchat($idDA);
        $lignesDA = $modifPrix->listeLigneDemandeAchat($idDA, $demandeAchat['CODE_STE']);

        $GestionContainerFile = new \Modules\Outil\Outil\GestionContainerFile('', $this->JWTKEY);
        $GestionContainerFile->creationContainerFile($lignesDA);

        $trad = $this->getTranslationService();

        switch ($MODULE) {
            case 'SignatureDA':
                $hastutil = new \Entity\Model\Hastutil($this->pdo);
                $H1 = Trad::strBuild($trad->t("Liste des DA actuellement à signer pour @1@ (@2@)"), $hastutil->find($_SESSION['Session_Login'])['NOM'], $_SESSION['Session_Login']);
                break;
            case 'DelegationSignatureDA':
                $H1 = $trad->t("Délégations des signatures");
                break;
            default:
                $H1 = $trad->t('Demandes d\'achat');
                break;
        }

        $pathAnnuler = $this->router->generateUri('DemandeAchat.ModificationDemandeAchat.index', ['onglet' => 'Article', 'MODULE' => $MODULE, 'idDA' => $idDA, 'mode' => $mode]);

        if ($mode == 'Creation') {
            $titreH2 = $trad->t('Création de lignes de demande d\'achat');
        } else {
            $titreH2 = $trad->t('Modification de la demande d\'achat') . ' : ' . $idDA;
        }

        return $this->renderer->render('@DemandeAchat/ModificationPrixLignes/modificationPrixLignes', [
            'menuActive' => 'CollecteBesoins',
            'menuLeft' => 'GestionDemandeAchat',
            'idDA' => $idDA,
            'mode' => $mode,
            'MODULE' => $MODULE,
            'H1' => $H1,
            'titreH2' => $titreH2,
            'ongletFicheDA' => true,
            'pathAnnuler' => $pathAnnuler,
            'demandeAchat' => $demandeAchat,
            'lignesDA' => $lignesDA,
        ]);
    }

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

        $DaEntet = new \Entity\Model\DaEntet($this->pdo);
        $DaLigne = new \Entity\Model\DaLigne($this->pdo);
        $modifPrix = new ModificationPrixLignes($this->pdo);
        $Parametr = new \Entity\Model\Parametr($this->pdo);

        $listeNoPo = $modifPrix->listeNoPoDemandeAchat($idDA);
        $Parametr = $Parametr->get();

        $validator = $this->createValidator();

        /** Validator **/
        $CTRL_PUDA = Sql::boolSql($Parametr->CTRL_PUDA);
        $BLO_PUDA = $CTRL_PUDA && Sql::boolSql($Parametr->BLO_PUDA);
        $trad = $this->getTranslationService();
        $erreurNonBloquante = '';
        foreach ($listeNoPo as $ligne) {
            $noPO = $ligne['NO_PO'];
            // TODO demander confirmation si on ne contrôle que les lignes modifiées
            // if($ligne['PU'] != $valuesContainerFile['PU-'.$noPO] || $ligne['TX_REMISE'] != $valuesContainerFile['TX_REMISE-'.$noPO]){
            if (isset($post['PU-' . $noPO]) || isset($post['TX_REMISE-' . $noPO])) {
                if (isset($post['PU-' . $noPO])) {
                    if (($CTRL_PUDA && Sql::boolSql($Parametr->SAI_PUDA) && !$BLO_PUDA) && ($post['PU-' . $noPO] == 0 || $post['PU-' . $noPO]  == '')) {
                        $erreurNonBloquante .= '<br />' . Trad::strBuild($trad->t('Ligne @1@ : Le prix unitaire est nul.'), $noPO);
                    }
                    $validator->isFloat(Trad::strBuild($trad->t('Ligne @1@ : Prix Unitaire'), $noPO), $post['PU-' . $noPO], Constante::formatPU, $BLO_PUDA);
                }
                if (isset($post['TX_REMISE-' . $noPO])) {
                    $validator->isFloat(Trad::strBuild($trad->t('Ligne @1@ : Taux de remise'), $noPO), $post['TX_REMISE-' . $noPO], 3.2, false, '100');
                }
            }
        }

        if ($validator->isValid() && ($erreurNonBloquante == '' || $post['submitForce'])) {
            $totalHT = 0;
            $totalTTC = 0;
            $mntLig = 0;
            $ttcLig = 0;
            $majOK = 1;
            foreach ($listeNoPo as $ligne) {
                $noPO = $ligne['NO_PO'];
                if (isset($post['PU-' . $noPO]) || isset($post['PU-' . $noPO])) {
                    $puLig = $post['PU-' . $noPO] ?? $ligne['PU'];
                    $txRemiseLig = $post['TX_REMISE-' . $noPO] ?? $ligne['TX_REMISE'];
                    $mntLig = $post['HT-' . $noPO] ?? $ligne['MNT_LIG'];
                    $ttcLig = $mntLig * (1 + $ligne['TVA'] / 100);
                    $tbl_TEMPINIT = explode('|', $ligne['TEMPINIT']);
                    // Enregistrement des lignes modifiées en BDD
                    $updateValues = [
                        'PU' => $puLig,
                        'TX_REMISE' => $txRemiseLig,
                        'MNT_LIG' => $mntLig,
                        'TEMPINIT' => str_pad(number_format($puLig, 5, '.', ''), 16, ' ', STR_PAD_LEFT) . '|' . str_pad(number_format($txRemiseLig, 2, '.', ''), 6, ' ', STR_PAD_LEFT) . '|' . $tbl_TEMPINIT[2] . '|' . $tbl_TEMPINIT[3],
                    ];
                    $whereLigne =  [
                        'NO_DA' => $idDA,
                        'NO_PO' => $noPO
                    ];
                    if (!$DaLigne->update($updateValues, $whereLigne)) {
                        $majOK = 0;
                    }
                }

                $totalHT = $totalHT + $mntLig;
                $totalTTC = $totalTTC + $ttcLig;
            }

            if ($majOK) {
                $updateEntet = [
                    'TOTAL_DA' => $totalHT,
                    'TOTAL_DA_TTC' => $totalTTC,
                ];
                $whereEntet =  [
                    'NO_DA' => $idDA,
                ];
                if (!$DaEntet->update($updateEntet, $whereEntet)) {
                    $majOK = 0;
                }
            }

            if (!$majOK) {
                $params = [
                    'alerte' => $trad->t("Erreur lors de l'exécution de l'opération."),
                ];
                return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                    'params' => $params,
                ]);
            }

            return new Response(443, [], (string) \json_encode([
                'statut' => 'O',
            ]));
        } else {
            $params = [
                'alerte' => $validator->getError(),
                'avertissement' => $erreurNonBloquante,
                'action' => 'enregistrementPrix',
            ];
            return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                'params' => $params,
            ]);
        }
    }

    public function getMontantLigneAction(): Response
    {
        $post = $this->request->getParsedBody();

        $montantLigne = $post['qte'] * $post['pu'];
        $montantRemise = number_format(($montantLigne - $montantLigne * $post['txRemise'] / 100), 2, '.', '');

        $GestionContainerFile = new \Modules\Outil\Outil\GestionContainerFile('', $this->JWTKEY);
        $params2Modif = [
            'MNT_LIG-' . $post['numLigne'] => $montantRemise,
        ];
        $GestionContainerFile->modificationFichier($params2Modif);

        return new Response(200, [], (string) \json_encode(['montantRemise' => $montantRemise]));
    }
}
