<?php
namespace Modules\Fournisseur\Controller;

use Skeleton\Controller\Controller;
use Entity\Model\Periodes;
use Modules\Fournisseur\WebService\HistoriqueFournisseur;

class PopupHistoriqueController extends Controller
{

    
    public function popupStatsIncidentAction() : string
    {
        $idFou = $this->request->getAttribute('id');
        
        $trimestre=[
            '1' => '1',
            '2' => '2',
            '3' => '3',
            '4' => '4',
        ];
        
        $periode = new Periodes($this->pdo);
        $periode = $periode->fetchAll();

        foreach ($periode as $annee) {
            $tabAnnee[$annee['CODE_PER']] = $annee['CODE_PER'];
            
            if ($annee['CODE_PER']==date('Y')) {
                break;
            }
        }

        return $this->renderer->render('@Fournisseur/Historique/popupStatsIncidents', [
            "id" => $idFou,
            'trimestre' => $trimestre,
            'annee' => $tabAnnee,
        ]);
    }
    
    public function statsIncidentAction() : string
    {
        $idFou = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();
        
        switch ($post['trim_debut']) {
            case '1':
                $dateDebut = $post['annee_debut'].'0101';
                break;
            case '2':
                $dateDebut = $post['annee_debut'].'0401';
                break;
            case '3':
                $dateDebut = $post['annee_debut'].'0701';
                break;
            case '4':
                $dateDebut = $post['annee_debut'].'1001';
                break;
        }
        
        switch ($post['trim_fin']) {
            case '1':
                $dateFin = $post['annee_fin'].'0331';
                break;
            case '2':
                $dateFin = $post['annee_fin'].'0630';
                break;
            case '3':
                $dateFin = $post['annee_fin'].'0930';
                break;
            case '4':
                $dateFin = $post['annee_fin'].'1231';
                break;
        }
        
        
        $array=[
            'codeFourn' => $idFou,
            'dateDebut' => $dateDebut,
            'dateFin' => $dateFin,
            'trimDebut' => $post['trim_debut'],
            'trimFin' => $post['trim_fin'],
            'anneeDebut' => $post['annee_debut'],
            'anneeFin' => $post['annee_fin'],
        ];
        
        $statsIncident = new HistoriqueFournisseur();
        $statsIncident = $statsIncident->statsIncident($array);
        $reponse = new \SimpleXMLElement($statsIncident->responseData);
        
        $extention = pathinfo($reponse->FichierPDF);
        
        $url = $this->router->generateUri('Ajax.outil.downloadPdf', ['url' => $extention['filename']]);
        return $url;
    }
}
