<?php

namespace Modules\Facture\Repository;

use Entity\Model\Enum\EFacDematFlowStatus;
use Entity\Model\FacAnterieure;
use Entity\Model\FacDematFlow;
use Entity\Model\FactEnt;
use Entity\Model\XtEve;

class FactureRepo extends AbsFacture
{
    
    public function annulerFacture(string $numAnnul, string $numRectif) :void
    {
        $this->pdo->beginTransaction();

        $qbFlow = new FacDematFlow($this->pdo);

        $flow = $qbFlow->find(['NUM_FACT' => $numAnnul]);
        if ($flow) {
            $qbFlow->updateStatus($flow['ID'], EFacDematFlowStatus::Annuler);
        }

        $reponse = \Modules\Facture\WebService\GestionFacture::clotureLitige(
            $numAnnul,
            '',
            ''
        );
        
        if ($reponse->Statut != 'O') {
            throw new \Exception((string) $reponse);
        }
        
        (new FactEnt($this->pdo))->update(
            ['ANNULE' => true],
            ['NUM_FACT' => $numAnnul]
        );

        (new FacAnterieure($this->pdo))->insert([
            'NUM_FAC' => $numRectif,
            'NUMFAC_ANTERIEURE' => $numAnnul,
        ]);

        (new XtEve($this->pdo))->insertEntity([ // Event Journal
            'TYPEOBJ' => 'FAC_ENT',
            'ID_1' => $numAnnul,
        ]);

        $this->pdo->commit();
    }
    

    public function resolveSocByAdrElec(string $adr) :?string
    {
        return $this->fetchAssocOne(
            "SELECT SOCIETE.CODE_STE
            FROM SOCIETE
            JOIN CENTRE ON CENTRE.CODE_STE = SOCIETE.CODE_STE
            JOIN FAC_DEMAT_ADRELEC 
                ON FAC_DEMAT_ADRELEC.ID = CENTRE.ID_ADR_FACELEC
                AND FAC_DEMAT_ADRELEC.ADR_FACELEC = :adr",
            [':adr' => $adr]
        )['CODE_STE'] ?? null;
    }
}
