<?php


namespace Modules\DemandeAchat\Controller;

use Entity\Model\Centre;
use Entity\Model\DaPlann;
use Entity\Model\Hastutil;
use Entity\Model\Paravrac;
use Entity\Model\Societe;
use Entity\Model\OxaSuiviRequete;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Modules\DemandeAchat\Outil\FormArray;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Entity\Model\DaLigne;
use Helpers\Outil\Sql;
use Modules\DemandeAchat\MenuContextuel\GestionMenuContextuel;
use Modules\DemandeAchat\Repository\DemandeAchat;
use Modules\DemandeAchat\Service\GestionDemandeAchatService;
use Modules\Suivi\Service\SuiviService;
use Modules\GlobalApplication\Repository\LicenceOxalys;

class GestionDemandeAchatController extends Controller
{
    /**
     * @var array<mixed>
     */
    private array $droits;

    public function init(): void
    {
        $paravrac = new Paravrac($this->pdo);
        $this->droits = [
            'DA_CreatModif' => Roles::droitsUtilisateur($this->pdo, 'HA_DA_CRE'),
            'HA_DA_TTDM' => Roles::droitsUtilisateur($this->pdo, 'HA_DA_TTDM'),
            'HA_DA_TTCE' => Roles::droitsUtilisateur($this->pdo, 'HA_DA_TTCE'),
            'HA_DA_TTCT' => Roles::droitsUtilisateur($this->pdo, 'HA_DA_TTCT'),
            'HA_DA_VISU' => Roles::droitsUtilisateur($this->pdo, 'HA_DA_VISU'),
            'HA_CA_CMV' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_CMV'),
            'DEMANDEUR' => Sql::boolSql(
                (new Hastutil($this->pdo))
                    ->find($_SESSION['Session_Login'])['DEMAND']
            ),
            'DA_AFF_CODE_ART' => $paravrac->getGeneric('DA_AFF_CODE_ART') == 'O',
            'DA_AFF_CODE_REF_FAB' => $paravrac->getGeneric('DA_AFF_CODE_REF_FAB') == 'O',
            'DA_AFF_REF_ART_FOUR' => $paravrac->getGeneric('DA_AFF_REF_ART_FOUR') == 'O',
            'ACTIVATION_BPA'    => $paravrac->getGeneric('ACTIVATION_BPA') == 'O',
        ];
    }

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

        $purchaseRequests = [];

        SuiviService::loadFavorisFilter($this->pdo, $post);
        $licenceOxalys = new LicenceOxalys($this->pdo);
        
        $listeRequete = (new OxaSuiviRequete($this->pdo))->fetchAll([], ['filter_egal_ID_USER' => $_SESSION['id_user'], 'filter_egal_TYPE_SUIVI' => 'DA']);

        
        $param = [];
        if (!$this->droits['HA_DA_TTDM']) {
            // si HA_DA_TTDM == false => uniquement DA dont user est demandeur
            $post['demandeur'] = $_SESSION['Session_Login'];
            $param['demandeur_LOCK'] = true;
        }
        
        if (!$post || ($post['tri_NO_DA'] ?? '' == '')) {
            $post['tri_NO_DA'] = 'desc';
        }
        
        (new PaginatorGestion())->generate(0, 'DA_ENTET.NO_DA');
        $purchaseRequests = (new DemandeAchat($this->pdo))->listeDemandeAchat($post);
        $infoPagination = PaginatorGestion::getInfoPagination();
        $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $trad);
        foreach ($purchaseRequests as &$pr) {
            $pr['menuContextuel'] = $menuContextuel->generate($pr, 'GestionDemandeAchat');
            $pr['TERME_DE_PAIEMENT'] = intval($pr['TOT_TP'] ?? []) != 0;
        }

        /* Filtre avancées */
        $advancedFilters = (new GestionDemandeAchatService(
            $this->pdo,
            $this->getTranslationService(),
        ))->setAdvancedFilters($post);

        Ariane::generate(0, $trad->t('Gestion'), $post, PaginatorGestion::getNbrArticle());
        ArianeSub::init();

        $formArray = FormArray::getFormArrays($trad);

        return $this->renderer->render('@DemandeAchat/Gestion/index', [
            'menuActive' => 'CollecteBesoins',
            'post' => $post,
            'infoPagination' => $infoPagination,
            'filtreAvance' => $advancedFilters['filtreAvance'],
            'initFiltreAvance' => $advancedFilters['initFiltreAvance'],
            'listeDA' => $purchaseRequests,
            'listeTypeChiffExec' => $formArray['typeChiffExec'],
            'listeEtatDA' => $formArray['listeEtatDA'],
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'tabTypeDate' => $formArray['tabTypeDate'],
            'user' => (new Hastutil($this->pdo))->find($_SESSION['Session_Login']),
            'societe' => (new Societe($this->pdo))->find($_SESSION['Session_SocUsr']),
            'centreLivraison' => (new Centre($this->pdo))->find($_SESSION['Session_CodeCtrLivraison']),
            'nombreResultat' => \count($purchaseRequests),
            'droits' => $this->droits,
            'isTermPaieActive' => $licenceOxalys->termPaieActive(),
            'param' => $param,
            'listeRequete' => $listeRequete,
        ]);
    }

    public function detailEntetAction(): string
    {
        $purchaseRequest = $this->request->getAttribute('idDA');
        $repo = new DemandeAchat($this->pdo);
        $detailDA = [];
        $listeLigneDemandeAchat = [];

        $listeLigneDemandeAchat = $repo->listeLigneDemandeAchat($purchaseRequest);
        $detailDA = $repo->demandeAchat($purchaseRequest);

        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->renderer->render('@DemandeAchat/Gestion/detailDemandeAchat', [
            'detailDA' => $detailDA,
            'listeLigneDemandeAchat' => $listeLigneDemandeAchat,
            'id' => $purchaseRequest,
            'typeChiffExec' => $formArray['typeChiffExec'],
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'tabTypeDate' => $formArray['tabTypeDate'],
            'droits' => $this->droits,
        ]);
    }

    public function detailLigneAction():string
    {
        $purchaseRequest = $this->request->getAttribute('idDA');
        $idLigne = $this->request->getAttribute('idLigne');

        $ligne = (new DemandeAchat($this->pdo))->listeLigneDemandeAchat($purchaseRequest, $idLigne);

        return $this->renderer->render('@DemandeAchat/Gestion/detailLigne', [
            'detailDA' => ['NO_DA' => $purchaseRequest],
            'ligneDA' => $ligne,
        ]);
    }

    public function popupPlanningAction(): string
    {
        $da = $this->request->getAttribute('da');
        $line = $this->request->getAttribute('line');

        $listePlanning = (new DaPlann($this->pdo))
            ->findAll(
                [
                    'NO_DA' => $da,
                    'NO_PO' => $line
                ],
                [],
                ['tri_DTE_LIV' => 'ASC']
            );

        $ligne = (new DaLigne($this->pdo))
            ->find([
                'NO_DA' => $da,
                'NO_PO' => $line
            ]);
        return $this->renderer->render('@Commande/GareDeTriage/popupPlanning', [
            'listPlanning' => $listePlanning,
            'ligne' => $ligne,
        ]);
    }
}
