<?php

namespace Modules\Facture\Repository;

use Helpers\Filter\FilterTable;
use Helpers\QueryBuilder\AbsRepository;

class LadArchivesFacture extends AbsRepository
{
    public function ladArchives($post)
    {
        
        $req =
        "SELECT lad.ID_LAD, lad.TYPE, lad.CODE_STE, lad.CODE_FOURN, lad.TOTAL_HT, lad.TOTAL_TTC, lad.DEVISE, lad.DATE_SCAN, lad.REF_FACTURE_FOURN, lad.DATE_FACTURE_FOURN, lad.FIC_FACTURE_XML, lad.FIC_FACTURE_PDF, lad.STATUT, lad.NUM_FACT
        FROM LAD_ARCHIVE lad with (nolock) 
        LEFT JOIN FOURNISS four with (nolock) ON lad.CODE_FOURN = four.CODE 
        LEFT JOIN SOCIETE soc with (nolock) ON soc.CODE_STE = lad.CODE_STE
        WHERE 1=1";

        $arrayReq= [];

        $whereArray = FilterTable::splitFilter($post, 0, 0, 1);
        if (is_array($whereArray) && isset($whereArray[0]) && $whereArray[0]!= '') {
            $filtre = (string)str_replace('SOCIETE', 'lad.CODE_STE', $whereArray[0]);
            $filtre = (string)str_replace('DeviseFac', 'lad.DEVISE', $filtre);
            $req .= $filtre;
            if (is_array($whereArray[1]) && count($whereArray[1]) > 0) {
                $arrayReq=  array_merge($arrayReq, $whereArray[1]);
            }
        }
        
        /** @phpstan-ignore-next-line */
        if (!$whereArray || ($whereArray && $whereArray['tri'] == '')) {
            $whereArray = ['tri' => ' ORDER BY lad.NUM_FACT desc', 0 => '', 1 => []];
        }
        $req .= $whereArray['tri'];

        $paginatorGestion = new \Helpers\Pagination\PaginatorGestion();
        $paginatorGestion->injecterSqlCount($req, $post, $arrayReq, $this->pdo);
        
        return $this->fetchAssocAll($req, $arrayReq);
    }
    
    public function getFicXml($idLad)
    {
        
        $req =
        "SELECT FIC_FACTURE_XML
        FROM LAD_ARCHIVE with (nolock)
        WHERE ID_LAD = :idLad";

        $arrayReq= [':idLad' => $idLad];

        $facture = $this->pdo->prepare($req);
        $facture->execute($arrayReq);
        return $facture->fetch();
    }

    public function getladArchivesExport($post)
    {
        $req        = " SELECT      lad.NUM_FACT, lad.TYPE, soc.RAIS_SOC + ' (' + lad.CODE_STE + ')' AS SOCIETE, 
                                    four.RS + ' (' + lad.CODE_FOURN + ')' AS FOURNISSEUR, lad.TOTAL_HT AS MONTANT_HT, 
                                    lad.TOTAL_TTC AS MONTANT_TTC, lad.DEVISE, lad.DATE_SCAN, lad.STATUT, lad.REF_FACTURE_FOURN
                        FROM        LAD_ARCHIVE lad with (nolock) 
                        LEFT JOIN   FOURNISS four with (nolock) ON lad.CODE_FOURN = four.CODE 
                        LEFT JOIN   SOCIETE soc with (nolock) ON soc.CODE_STE = lad.CODE_STE
                        ORDER BY    lad.NUM_FACT DESC
                    ";

        $arrayReq   = [];
        
        $shortList  = $this->pdo->prepare($req);
        $shortList->execute($arrayReq);
        
        return  $shortList->fetchAll($this->pdo::FETCH_ASSOC);
    }
}
