<?php

namespace Modules\Additional\Specifique\Client71\Modules\Panier\Service;

use Entity\Model\OxaUserPanier;
use Entity\Model\OxaUserPanierLigne;
use Helpers\ChampsSupplementaire\ChampSupp;
use Modules\Panier\Service\PanierService;

class UpdateValueCtrLivraison
{

    public static function getCentreLivraison(\PDO $pdo, string $societe, string $si):string
    {
        $isSecto = \Helpers\Outil\Roles::droit($pdo, 'SISECTOR', 'PARAMSTE');
        $siSte = str_pad(($isSecto? $societe:''), 7, ' ', STR_PAD_RIGHT).$si;
        $csSI = ChampSupp::getEnregByValueSpecific([
            'COD_TAB'   => 'SECTIMPU',
            'COD_ENR'    => $siSte,
            'typedico'  => 'PARAMLEONG',
            'codedico'  => 'NCS_SECTIMPU_TYPE_CHANTIER',
        ], $pdo);

        if ($csSI['VALEUR'] == 'p' || $csSI['VALEUR'] == 'P') {
            return substr($si, 0, 1) . substr($si, 2);
        } else {
            return '';
        }
    }

    public static function initCentreLivraisonSI(\PDO $pdo, ?string $si = null, ?string $idLigne = null, bool $returnValue = false):mixed
    {
        $entetePanier = (new OxaUserPanier($pdo))->find([
            'id_user' => $_SESSION['id_user'],
            'id_panier' => $_SESSION['id_panier'],
        ]);
        
        $newsCentre = self::getCentreLivraison($pdo, $entetePanier['CODE_STE']??'', $si??'');
        if (!$newsCentre) {
            return $returnValue? '':false;
        }
        
        if ($idLigne) {
            if ($returnValue) {
                return $newsCentre;
            }

            (new OxaUserPanierLigne($pdo))->update([
                'CodeCtrLivraison' => $newsCentre
            ], [
                'id_user' => $_SESSION['id_user'],
                'id_panier' => $_SESSION['id_panier'],
                'id_lig' => $idLigne,
            ]);
        } else {
            return (new PanierService($pdo))->initCentre($pdo, $newsCentre);
        }

        return false;
    }
}
