<?php

namespace Modules\Facture\Controller;

use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Date;
use Helpers\Fichier\Fichier;
use Modules\Facture\MenuContextuel\AcquisitionFactureMenuContextuel;

class FactureImporterController extends Controller
{
    public function init()
    {
        if (!\Helpers\Roles\Predispatch::connectRole()) {
            return $this->redirect($this->contenaire->get('base').'index.php');
        }
    }
    
    /**
     * Cette fonction va nous permettre de lister les factures dans un premier temps
     * ainsi que nous transferer des factures sur choix multiples
     */
    public function listeFactureImportAction() : string
    {
        Ariane::generate(0, 'Acquisition des factures');
        $post = $this->request->getParsedBody();

        $xmlResult = new \Modules\Facture\WebService\ImportationFacture();
        $xmlResultLister= $xmlResult->listeFacture();

        $facture = new \SimpleXMLElement($xmlResultLister->responseData);

        $firstFacture = $facture->ListeFactures->Facture;

        $urlPDF       = \Helpers\Outil\Roles::getDroit($this->pdo, 'LADFACTSPOT_PDF', 'PARAMGEN', false);

        
         /**
         * Tester si le slache est bien mis a la fin sinon on le rajoute car il peut y avoir un souci lors du concat
         */
        if (substr((string)$urlPDF, -1) != '/') {
            $urlPDF .='/';
        }

        if (strpos($urlPDF, '%') !== false) {
            $img =  explode('%', $urlPDF);
            $imageACharger = ($_SESSION [$img[1]]??'') . str_replace("/", '\\', $urlPDF);
            $urlPDF = str_replace('%'.$img[1].'%', '', $imageACharger);
        }

        $menuContextuel = new AcquisitionFactureMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        
        $arrayMenuContextuel = [];
        // DOSSIER 33599 : Contrôle de la présence du fichier
        foreach ($facture->ListeFactures->Facture as $values) {
            $savePDF = '';
            if (trim($values->FIC_FACTURE_PDF)!= '' && substr(strtoupper(trim($values->FIC_FACTURE_PDF)), -4) != '.PDF') {
                $values->FIC_FACTURE_PDF = $values->FIC_FACTURE_PDF.'.PDF';
            }
            $savePDF = $urlPDF.$values->FIC_FACTURE_PDF;
            
            /**
             * Securisation des PDF
             */
            $payload = [
                'doc'=> $values->FIC_FACTURE_PDF,
                'src'=> 'LADFACTSPOT_PDF',
                'exp' => time()+60*60
            ];
            
            $values->FIC_FACTURE_PDF = \Firebase\JWT\JWT::encode($payload, $this->JWTKEY, 'HS256');
            
            $values->pdfNotFound = !file_exists($savePDF);

            // TODO ajouter le menu contextuel à la facture => voir s'il est nécessaire de la garder en XML element

            $menuTmp = $menuContextuel->generateImport($values);
            $arrayMenuContextuel[(string)$values->FIC_FACTURE_PDF] = $menuTmp;
        }
        
        \Helpers\Outil\Document::getUrlDocument($urlPDF);

        if (isset($post['clcheckbox']) && count($post['clcheckbox']) > 0) {
            $xmlResultTransfer = $xmlResult->transferFacture($post['clcheckbox']);
        }

        return $this->renderer->render('@Acquisition-des-Factures/facture-a-importer', [
            'menuActive'        => 'Facture',
            
            'firstFactureValue' => $firstFacture,
            'facture'           => $facture,
            'url_pj'            => $urlPDF,
            'arrayMenuContextuel' => $arrayMenuContextuel
        ]);
    }

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

        $trad = $this->getTranslationService();
 
        $xmlResult = new \Modules\Facture\WebService\ImportationFacture();
        $xmlResult = $xmlResult->archiverFacture($post['ficPDF'] ?? '');
        
        $response = new \SimpleXMLElement($xmlResult->responseData);
        if ($response->Statut=="O") {
            return new Response(200, [
                
            ], (string) \json_encode(['Statut' => 'O']));
        } else {
            $params = [
                'alerte' => $response->MsgErreur,
                'titrePopup'  => $trad->t('Erreur'),
            ];
            return new Response(443, [
                
            ], $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', ['params' => $params]));
        }
    }


    public function annulerTransfertAction() : string
    {
        // TODO REVOIR CETTE FONCTIONNALITE LORS D'UNE PUBLICATION SUR OXAPROC
        $post = $this->request->getParsedBody();
        
        $xmlResult = new \Modules\Facture\WebService\ImportationFacture();        // $xmlResult= $xmlResult->annulerTransfertFacture($post['ficPDF']);
        $xmlResult= $xmlResult->listeFacture($post['ficPDF']);
        return $this->renderer->render('@Acquisition-des-Factures/facture-a-importer', [
            'menuActive' => 'Facture',
            'menuLeft'   => 'LAD'
        ]);
    }

    public function transfertFactureAction() : string
    {

        $post = $this->request->getParsedBody();
        
        $xmlResult         = new \Modules\Facture\WebService\ImportationFacture();
        $xmlResult         = $xmlResult->transferFacture($post['clcheckbox']??[], $post['NUM_RECORD'] ?? '', $post['FIC_XML'] ?? '');
        $factureTransferer = new \SimpleXMLElement($xmlResult->responseData);
        
        return $this->renderer->render('@Acquisition-des-Factures-popup/popup-up-transfert-facture-importer', [
            'creerPar'           => $_SESSION['Session_Login'],
            'factureTransferer' => $factureTransferer,
            'post'              => json_encode($post),
        ]);
    }
    
    public function alertePdfNotFoundAction() : string
    {
        // Popup d'erreur de la commande de régularisation
        $post = $this->request->getParsedBody();

        return $this->renderer->render('@Acquisition-des-Factures-popup/alertePdfNotFound', [
            'onclickOui' => $post['onclickOui'],
            'onclickNon' => $post['onclickNon'],
            
        ]);
    }

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

        $xmlResult                                  = new \Modules\Facture\WebService\ImportationFacture();
        $xmlResultLister                            = $xmlResult->listeFacture();

        $bills                                      = new \SimpleXMLElement($xmlResultLister->responseData);

        $imported_bills                             = $bills->ListeFactures->Facture;

        $listeImport                                = array_map('get_object_vars', iterator_to_array($imported_bills, false));

        foreach ($listeImport as &$import) {
            switch ($import[ 'TYPE' ]) {
                case 'F':
                    $import[ 'TYPE' ]               = 'Facture';
                    break;
                case 'A':
                    $import[ 'TYPE' ]               = 'Avoir';
                    break;
            }
            $import[ 'DATE_SCAN' ]                    = DATE::dateConverte($import[ 'DATE_SCAN' ]);
            $import[ 'DATE_FACTURE_FOURN' ]           = DATE::dateConverte($import[ 'DATE_FACTURE_FOURN' ]);

            $import[ 'FOURNISSEUR' ]                = $import[ 'FOURNISSEUR_RS' ]. '(' . $import[ 'FOURNISSEUR_CODE' ] . ')';

            $import[ 'TOTAL_HT' ]                   = (int) $import[ 'TOTAL_HT' ];
            $import[ 'TOTAL_TTC' ]                  = (int) $import[ 'TOTAL_TTC' ];

            $import[ 'MONTANT_HT' ]                 = number_format($import[ 'TOTAL_HT' ], 2, '.', '');
            $import[ 'MONTANT_TTC' ]                = number_format($import[ 'TOTAL_TTC' ], 2, '.', '');

            if ($import[ 'NUM_FACT' ] != 0) {
                $import[ 'STATUS_IMPORT' ]          = 'Facture déjà importée';
            } elseif ($import[ 'STATUT_LAD' ] == 'T' && $import[ 'NUM_FACT'] == 0) {
                $import[ 'STATUS_IMPORT' ]          = 'Facture transférée';
            } elseif ($import ['STATUT_LAD' ] == 'E' && $import[ 'NUM_FACT' ] != 0) {
                $import[ 'STATUS_IMPORT' ]          = 'Anomalie sur cette facture';
            }

            if ($import[ 'NUM_FACT' ] != 0) {
                $import[ 'N_FACTURE' ]              = $import[ 'NUM_FACT' ];
            } else {
                $import[ 'N_FACTURE' ]              = 'Undefined';
            }

            $import                                 = array_filter($import, function ($key) {
                // Filter table to display only infos needed
                return          $key        == 'TYPE'
                            ||  $key        == 'SOCIETE'
                            ||  $key        == 'FOURNISSEUR'
                            ||  $key        == 'MONTANT_HT'
                            ||  $key        == 'MONTANT_TTC'
                            ||  $key        == 'DEVISE'
                            ||  $key        == 'DATE_SCAN'
                            ||  $key        == 'STATUS_IMPORT'
                            ||  $key        == 'N_FACTURE';
            }, ARRAY_FILTER_USE_KEY);

            // Define the lines to display to match with screen infos
            $import                                 = [
                'N° FACTURE'                => $import[ 'N_FACTURE' ],
                'TYPE'                      => $import[ 'TYPE' ],
                'SOCIETE'                   => $import[ 'SOCIETE' ],
                'FOURNISSEUR'               => $import[ 'FOURNISSEUR' ],
                'MONTANT_HT'                => $import[ 'MONTANT_HT' ],
                'MONTANT_TTC'               => $import[ 'MONTANT_TTC' ],
                'DEVISE'                    => $import[ 'DEVISE' ],
                'DATE_SCAN'                 => $import[ 'DATE_SCAN' ],
                'STATUS_IMPORT'             => $import[ 'STATUS_IMPORT' ],
            ];
        }

        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_facture_import',
            $listeImport,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }
}
