<?php

namespace Modules\Facture\Controller;

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();
        
        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $infoPagination = $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\Roles::getDroit($this->pdo, 'LADARCHIVE_PDF', 'PARAMGEN', false));
    
        if (substr($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());
        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);
        }

        
        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',
            
            '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'),
        ];
        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        == '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';
    }
}
