<?php
namespace Modules\Commande\Controller;

use Entity\Model\CaLigne;
use Entity\Model\CaPlPr;
use Modules\Commande\Repository\Solder;
use Modules\GlobalApplication\Repository\LicenceOxalys;
use Skeleton\Controller\Controller;
use Helpers\Ariane\ArianeSub;
use Modules\Commande\Repository\Commande;
use Entity\Model\Contfour;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Trad\Trad;
use Modules\Commande\WebService\Commande as WebServiceCommande;
use Entity\Model\CaEntet;
use Helpers\ChampsSupplementaire\ChampSupp;
use Modules\Commande\MenuContextuel\GestionMenuContextuel;
use Modules\Commande\Repository\Avenant;

class CommandeController extends Controller
{
    public function commandeAction(
        LicenceOxalys $licenceOxalys
    ): string {
       // $post = $this->request->getParsedBody();
        $numCde = $this->request->getAttribute('idCommande');

        $avenant = $this->request->getAttribute('idAvenant');
        
        $modeHisto = false;
        if ($avenant || $avenant === '0') {
            $modeHisto = true;
        }
        
        $trad = $this->getTranslationService();
        
        if ($modeHisto) {
            $avenantRepo = new Avenant($this->pdo);
            $commande = $avenantRepo->getEnteteAvenant($numCde, $avenant);
        } else {
            $commande = new Commande($this->pdo);
            $commande = $commande->commandeEntete($numCde);

            $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), []);
            $commande['menuContextuel'] = $menuContextuel->lightGenerate($commande);
        }
        

        /*$contact = new Contfour($this->pdo);
        $contact = $contact->fetch([], ['CODE_FOU' => $commande['CODE_FOU'], 'IND_FOU' => '0']);*/
        
        $tabPeriodicite = [
            'M' => $trad->t('Mensuelle'),
            'T' => $trad->t('Trimestrielle'),
            'S' => $trad->t('Semestrielle'),
            'A' => $trad->t('Annuelle'),
        ];
        
        $tabPeriode = [
            'D' => $trad->t('Début de période'),
            'F' => $trad->t('Fin de période'),
        ];
        
        $tabTypeDate = [
            'D' => $trad->t('Date'),
            'S' => $trad->t('Semaine'),
            'M' => $trad->t('Mois'),
        ];

        //ArianeSub::generate(0, 1, $trad->t('Informations commande'), $this->router->generateUri('Commande.Commande.commande', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 1);
        
        $trad = $this->getTranslationService();
        ArianeSub::init();
        ArianeSub::generate(0, 0, $trad->t('Articles commande'), $this->router->generateUri('Commande.Commande.article', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 0);
        ArianeSub::generate(0, 1, $trad->t('Informations commande'), $this->router->generateUri('Commande.Commande.commande', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 1);
        if (!$modeHisto) {
            ArianeSub::generate(0, 2, $trad->t('Documents rattachés'), $this->router->generateUri('GlobalApplication.DocumentRattaches.document', ['MODULE' => 'Commande', 'id' => $numCde]), 0);
        }
        ArianeSub::generate(0, 3, $trad->t('Pièces-jointes'), $this->router->generateUri('Commande.PieceJointe.index', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 0);
        ArianeSub::generate(0, 4, $trad->t('Clauses'), $this->router->generateUri('Commande.Clause.index', ['idCommande' => $numCde, 'idAvenant' => $avenant]));

        if (!$modeHisto) {
            ArianeSub::generate(0, 5, $trad->t('Interactions'), $this->router->generateUri('Commande.Interaction.interactions', ['idCommande' => $numCde]));
        }
        if ($licenceOxalys->termPaieActive()) {
            ArianeSub::generate(0, 6, $trad->t('Termes de paiement'), $this->router->generateUri('Commande.TermeDePaiementCommande.index', ['idCommande' => $numCde, 'MODULE' => 'Commande']));
        }
        $idcsAvenant = '';
        if ($avenant) {
            $idcsAvenant = ChampSupp::autoCompletCodeEnr($numCde, '', 'CA_ENTET');
            ;
            $noAvt = (int)$avenant;

            $idcsAvenant .= $noAvt>=10? $noAvt:' '.$noAvt;
        } elseif ($avenant==='0') {
            $idcsAvenant = ChampSupp::autoCompletCodeEnr($numCde, '', 'CA_ENTET');
        }

        return $this->renderer->render('@Commande/Commande/index', [
            'menuActive' => 'CollecteBesoins',
            'numCde' => $numCde,
            'commande' => $commande,
            'tabPeriodicite' => $tabPeriodicite,
            'tabPeriode' => $tabPeriode,
            'tabTypeDate' => $tabTypeDate,
            'modeHisto' => $modeHisto,
            'idAvenant' => $avenant,
            'idcsAvenant' => $idcsAvenant,
        ]);
    }

    public function soldeFinancierLigneAction() : string
    {
        $numCde = $this->request->getAttribute('idCommande');

        $trad = $this->getTranslationService();


        $droit = [
            'HA_CA_SFM' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_SFM', $_SESSION["Session_Login"]),
            'HA_CA_DFM' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_DFM', $_SESSION["Session_Login"]),
        ];

        $caEntet = new CaEntet($this->pdo);
        $cde = $caEntet->find($numCde);

        $libelleButton = $cde['ETAT_FIN'] == 'F'? $trad->t('Désolder l\'entête'):$trad->t('Solder l\'entête');
        $libelleButton = $trad->t('(Dé)solder l\'entête');
        
        $solder = new Solder($this->pdo);
        $ligneCA = $solder->listeLigneCde($numCde);
        
        Ariane::generate(1, $trad->t('Solde financier des lignes'));
        ariane::setFocus($numCde);

        return $this->renderer->render('@Commande/soldeFinancier/index', [
            'menuActive' => 'eproc',
            'menuLeft' => 'eproc',
            'numCde' => $numCde,
            'ligneCA' => $ligneCA,
            'droit' => $droit,
            'cde' => $cde,
            'libelleButton' => $libelleButton,
        ]);
    }

    public function ajaxSolderFinancierLigneAction() : string
    {
        $numCde = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();

        $listeLigne = [];
        $action = 'S';
        foreach ($post as $key => $val) {
            if (strpos($key, 'NO_PO') === 0) {
                $noPo = $val;

                $validator->isCheck($post['SOLDER'.$noPo]);
                if ($post['SOLDER'.$noPo]) {
                    $value = true;
                } else {
                    $value = false;
                    $action = 'D';
                }

                $listeLigne[] = [
                    'NO_PO' => $noPo,
                    'SOLDER' => $value,
                ];
            }
        }
        
        $commandeWsdl = new WebServiceCommande();
        $xmlResult = $commandeWsdl->soldeFinancier($numCde, false, $action, $listeLigne);
        $reponse = new \SimpleXMLElement($xmlResult->responseData);

        $trad = $this->getTranslationService();
        if ($reponse->Statut == "O") {
            $message =  $trad->t('Les lignes ont bien été traitées.');
        } else {
            $message =  $reponse->MsgErreur;
        }

        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'refresh' => true,
            'div_refresh' => 'soldeFinancier',
            'iconePopup' => 'information',
            'form_refresh' => ''
        ]);
    }
        
    /**
     * popupSolderFinancierAction
     *
     * @return string
     */
    public function popupSolderFinancierAction()
    {
        $numCde = $this->request->getAttribute('idCommande');

        return $this->renderer->render('@Commande/soldeFinancier/popupSolder', [
            'numCde' => $numCde,
        ]);
    }

    public function ajaxSolderFinancierAction() : string
    {
        $numCde = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();
        
        $caEntet = new CaEntet($this->pdo);
        $cde = $caEntet->find($numCde);
        $trad = $this->getTranslationService();
        
        if ($cde['ETAT_FIN'] == 'F') {
            $statut = 'D';
            $messageOk = $trad->t('La commande a été désoldée.');
        } else {
            $statut = 'S';
            $messageOk = $trad->t('La commande a été soldée.');
        }

        $commandeWsdl = new WebServiceCommande();
        $xmlResult = $commandeWsdl->soldeFinancier($numCde, true, $statut, [], $post['commentaire']);
        $reponse = new \SimpleXMLElement($xmlResult->responseData);
        
        if ($reponse->Statut == "O") {
            $message =  $messageOk;
        } else {
            $message =  $reponse->MsgErreur;
        }
        
        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'refresh' => true,
            'div_refresh' => 'soldeFinancier',
            'iconePopup' => 'information',
            'form_refresh' => ''
        ]);
    }

    public function popupPlanningAction() :string
    {
        return $this->renderer->render('@Commande/Commande/popupPlanning', [
            'listCaLigne' =>
                (new Commande($this->pdo))->listLignePlanning(
                    $this->request->getAttribute('id')
                ),
        ]);
    }
}
