<?php

namespace Modules\Facture\Controller;

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

class FactureArchiveController extends Controller
{
    public function init()
    {
        if (!\Helpers\Roles\Predispatch::connectRole()) {
            return $this->redirect($this->contenaire->get('base').'index.php');
        }
    }

    public function listeFactureArchiveAction() : string
    {
        $post = $this->request->getParsedBody();
        $tab = $this->request->getAttribute('tab');

        if ($tab == 'error') {
            $post['filter_STATUT'] = 'E';
        }
        
        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(0, 'lad.NUM_FACT');

        $factureLad = new \Modules\Facture\Repository\LadArchivesFacture($this->pdo);
        $listeArchive = $factureLad->ladArchives($post);
        $infoPagination = \Helpers\Pagination\PaginatorGestion::getInfoPagination();
        
        $urlPDF = trim(\Helpers\Outil\Sql::paravrac($this->pdo, 'PARAMGEN', 'LADARCHIVE_PDF'));
        $urlPDF = Outils::buildPath($urlPDF);
        
        $urlXML = trim(\Helpers\Outil\Sql::paravrac($this->pdo, 'PARAMGEN', 'LADARCHIVE_XML'));
        $urlXML = Outils::buildPath($urlXML);

        $menuContextuel = new AcquisitionFactureMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        
        foreach ($listeArchive as $key => $value) {
            $url_pdf_facture = str_replace('/', '\\', $value['FIC_FACTURE_PDF']);
            /**
             * Securisation des PDF
             */
            $payload = [
                'doc'=> $url_pdf_facture,
                'src' => 'LADARCHIVE_PDF',
                'exp' => time()+60*60
            ];

            $url_pdf_facture = \Firebase\JWT\JWT::encode($payload, $this->JWTKEY, 'HS256');
            $listeArchive[$key]['FIC_FACTURE_PDF'] = $url_pdf_facture;

            $listeArchive[$key]['menuContextuel'] = $menuContextuel->generateArchivage($value);

            $getFileContent = file_get_contents($urlXML.$value['FIC_FACTURE_XML']);
            if ($getFileContent) {
                $xml = new \SimpleXMLElement($getFileContent);
                
                foreach ($xml->Record->ListeAnomalie->Anomalie as $ano) {
                    $listeArchive[$key]['ListeAnomalies'][] = (string)$ano;
                }
            }
        }
        
        if (count($listeArchive)>0) {
            $firstFacture = $listeArchive[0];
        }

        $trad = $this->getTranslationService();
        
        $listeType        = ['F' => $trad->t('Fac'), 'A' => $trad->t('Avr')];

        return $this->renderer->render('@Acquisition-des-Factures/facture-archive', [
            'menuActive'          => 'Facture',
            'menuLeft'            => 'LAD',
            'tab'                 => $tab,
            
            'listeArchive'        => $listeArchive,
            'infoPagination'      => $infoPagination,
            'firstFactureArchive' => $firstFacture?? '',
            'url_pj'              => $urlPDF,
            'listeType'           => $listeType,
        ]);
    }

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

        $factureLad = new \Modules\Facture\Repository\LadArchivesFacture($this->pdo);
        $FicXml = $factureLad->getFicXml($post['idLad'])['FIC_FACTURE_XML'];

        $xmlResult = new \Modules\Facture\WebService\ImportationFacture();
        $xmlResult = $xmlResult->annulerArchivageFacture($FicXml);

        $response = new \SimpleXMLElement($xmlResult->responseData);

        if ($response->Statut=="O") {
            return new Response(200, [
                
            ], (string) \json_encode(['Statut' => 'O']));
        } else {
            $params = [
                'alerte' => $response->MsgErreur,
                'titrePopup'  => 'Erreur',
            ];
            return new Response(443, [
                
            ], $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', ['params' => $params]));
        }
    }

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

        $listeArchive                               = new \Modules\Facture\Repository\LadArchivesFacture($this->pdo);
        $listeArchive                               = $listeArchive->getladArchivesExport($post);
        
        $trad = $this->getTranslationService();
        $tab = [
            $trad->t('Type'),
            $trad->t('Societe'),
            $trad->t('Fournisseur'),
            $trad->t('Montant ht'),
            $trad->t('Montant ttc'),
            $trad->t('Devise'),
            $trad->t('Date scan'),
            $trad->t('Statut'),
            $trad->t('Facture'),
            $trad->t('Référence'),
        ];
        foreach ($listeArchive as &$archive) {
            switch ($archive['TYPE']) {
                case 'F':
                    $archive['TYPE']                = 'Facture';
                    break;
                case 'A':
                    $archive['TYPE']                = 'Avoir';
                    break;
            }
            $archive['DATE_SCAN']                   = DATE::dateConverte($archive['DATE_SCAN']);
            $archive['MONTANT_HT']                  = number_format($archive['MONTANT_HT'], 2, '.', '');
            $archive['MONTANT_TTC']                 = number_format($archive['MONTANT_TTC'], 2, '.', '');

            $archive['NUM_FACT']                    = (int) $archive['NUM_FACT'];

            if ($archive['NUM_FACT'] != 0 && $archive['STATUT'] == 'T') {
                $archive['STATUT_ARCHIVE']          = 'Facture importée';
                $archive['N°_FACTURE']              = $archive['NUM_FACT'];
            } elseif ($archive['NUM_FACT'] == 0 && $archive['STATUT'] == 'E') {
                $archive['STATUT_ARCHIVE']          = 'Erreur à l\'importation';
                $archive['N°_FACTURE']              = '';
            } else {
                $archive['STATUT_ARCHIVE']          = '';
                $archive['N°_FACTURE']              = '';
            }

            $archive                                = array_filter($archive, 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        == 'STATUT_ARCHIVE'
                            ||  $key        == 'REF_FACTURE_FOURN'
                            ||  $key        == 'N°_FACTURE';
            }, ARRAY_FILTER_USE_KEY);
        }
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_facture_archive'.date('Ymd'),
            $listeArchive,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );

        return 'ok';
    }
}
