<?php

namespace API\Bouyco\Repository;

use Entity\Model\Dilispec;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\QueryBuilder\AbsRepository;

class OiaRepo extends AbsRepository
{
    const TABLE = [
        'IMPORTOA',
        'INT_EDIFICE_IMP_CDES',
        'INT_EDIFICE_IMP_FOURNISS',
        'INT_EDIFICE_IMP_FOURNISS_CONTACT',
    ];

    /**
     * @param string $tableName
     * @return int|mixed
     */
    public function getLastId(string $tableName)
    {
        if (in_array($tableName, self::TABLE)) {
            $lastInsertIdStmt = "SELECT TOP (1) ID FROM {$tableName} with (nolock) ORDER BY ID DESC";
            $query = $this->pdo->prepare($lastInsertIdStmt);
            $query->execute();
            return $query->fetch($this->pdo::FETCH_ASSOC);
        } else {
            return 0;
        }
    }
    /**
     * @param string $tableName
     * @return void
     */
    public function truncateTable(string $tableName): void
    {
        $this->pdo->prepare("TRUNCATE TABLE {$tableName}")->execute();
    }

    /**
     * @param array<mixed> $ids
     * @return array<mixed>
     * @throws \Exception
     */
    public function getSAPSoc($ids)
    {
        $params = [];
        $stmt = "
            SELECT
                CODE,
                TYPE_INT
            FROM
                FOURNISS with (nolock)
            WHERE
        ";
        $where = $this->makeWhereIn('CODE', $ids, $params);
        $stmt .= $where;

        $query = $this->pdo->prepare($stmt);
        $query->execute($params);

        $res = $query->fetchAll($this->pdo::FETCH_ASSOC);

        $list = [];
        if (is_array($res)) {
            foreach ($res as $line) {
                if ($line['TYPE_INT'] === 'SAP') {
                    $list[] = $line['CODE'];
                }
            }
        }

        return $list;
    }

    /**
     * @param string $code
     * @return mixed
     */
    public function getCodeGroupeCompte($code)
    {
        $dilispec = new Dilispec($this->pdo);
        $res = $dilispec->find([
            'TYPEDICO' => 'SAPGRPCPTE',
            'CODEDICO' => $code
        ], ['LIB01DICO'], [], $this->pdo::FETCH_ASSOC);

        return $res['LIB01DICO'];
    }

    /**
     * @param array<mixed> $data
     * @param int|bool $lastId
     * @return int|mixed
     */
    public function importOia($data, $lastId = false)
    {
        if (!$lastId) {
            $result = $this->getLastId('IMPORTOA');
            $startFromId = ($result['ID'] + 1);
        } else {
            $startFromId = $lastId;
        }

        $listEntity = [];
        foreach ($data as $item) {
            $dateDebut = $item['dateDebutValidite'] ? (new \DateTime($item['dateDebutValidite']))->format('Ymd') : '00000000';
            $dateFin = $item['dateFinValidite'] ? (new \DateTime($item['dateFinValidite']))->format('Ymd') : '00000000';
            $listEntity[] = [
                'ID' => $startFromId,
                'CODE_NIVEAU' => substr($item['codeNiveau'] ?? '', 0, 10),
                'CODE_OIA' => substr($item['codeOIA'] ?? '', 0, 50),
                'CODE_SOCIETE' => substr($item['codeSocieteSap'] ?? '', 0, 50),
                'CODE_SI' => substr($item['codeCentreLegacy'], 0, 50),
                'CODE_GESTION' => substr($item['codeOIA'] ?? '', 0, 50),
                'TYPE_SAP' => substr($item['typeSap'] ?? '', 0, 50),
                'LIBELLE_OIA' => substr($item['libOIA'] ?? '', 0, 50),
                'ADRESSE_VOIE' => substr($item['adrVoie'] ?? '', 0, 100),
                'ADRESSE_VOIE_COMP' => substr($item['adrVoieComplement'] ?? '', 0, 100),
                'ADRESSE_POINT_REMISE' => substr($item['adrPointRemise'] ?? '', 0, 100),
                'ADRESSE_POINT_REMISE_COMP' => substr($item['adrPointRemiseComplement'] ?? '', 0, 100),
                'CODE_POSTAL' => substr($item['adrCodePostal'] ?? '', 0, 50),
                'PAYS' => substr($item['adrCodePays'] ?? '', 0, 50),
                'VILLE' => substr($item['adrLocalite'] ?? '', 0, 45),
                'TEL' => substr($item['adTelephone'] ?? '', 0, 50),
                'FAX' => substr($item['adTelecopie'] ?? '', 0, 50),
                'MAIL' => substr($item['adMail'] ?? '', 0, 50),
                'DATE_DEBUT_VALIDITE' => $dateDebut,
                'DATE_FIN_VALIDITE' => $dateFin,
                'STATUT_SYSTEME' => substr($item['statutSysteme'] ?? '', 0, 50),
                'CODE_INTERNE_PERE' => substr($item['codeOIAPereInterne'] ?? '', 0, 50),
                'CODE_CENTRE_PROFIT' => substr($item['codeCentreProfit'] ?? '', 0, 50),
                'LIBELLE_CENTRE_PROFIT' => substr($item['libCentreProfit'] ?? '', 0, 50),
                'CODE_INTERNE' => substr($item['codeOAIInterne'] ?? '', 0, 50),
                'ADRESSE_DESTINATAIRE' => substr($item['adrDestinataire'] ?? '', 0, 100),
                'IDCELEMENTACHAT'   => substr($item['idcElementAchat'] ?? '', 0, 100),
                'CPL_SOC_SI'    => substr($item['codeSocieteSap'].$item['codeCentreLegacy'], 0, 100)
            ];
            $startFromId++;
        }

        $this->multiInsert('IMPORTOA', $listEntity);

        return $startFromId;
    }

    /**
     * @param array<mixed> $orders
     * @return void
     */
    public function importOrderBlocked($orders): void
    {
        $listEntity = [];

        foreach ($orders as $order) {
            $listEntity[] = [
                'NO_CDE' => substr($order['numeroCommande'], 2),
                'NO_CDEC' => substr($order['numeroCommande'], 0, 50)
            ];
        }

        $this->multiInsert('INT_EDIFICE_IMP_CDES', $listEntity);
    }

    /**
     * @param array<mixed> $fourniss
     * @return void
     */
    public function importFourniss($fourniss): void
    {
        $takeSubIfMainEmpty = function ($main, $sub) {
            return empty($main) ? $sub : $main;
        };

        $listFrnEntity = [];
        $listCntEntity = [];

        foreach ($fourniss as $item) {
            $frn = $item;
            $org = $frn['navOrg']['results'][0];
            $contacts = $frn['navCnt']['results'];
            $listFrnEntity[] = [
                'NUMEROTAXE1' => substr($frn['numeroTaxe1'] ?? '', 0, 30),
                'NUMEROTAXE2' => substr($frn['numeroTaxe2'] ?? '', 0, 30),
                'NUMEROTAXE3' => substr($frn['numeroTaxe3'] ?? '', 0, 30),
                'NUMEROTAXE4' => substr($frn['numeroTaxe4'] ?? '', 0, 30),
                'DATESUPPRESSION' => substr($takeSubIfMainEmpty($frn['dateSuppression'], $org['dateSuppression']) ?? '', 0, 10),
                'IDCSUPPRESSION' => substr($takeSubIfMainEmpty($frn['idcSuppression'], $org['idcSuppression']) ?? '', 0, 1),
                'DATEBLOCAGE' => substr($takeSubIfMainEmpty($frn['dateBlocage'], $org['dateBlocage']) ?? '', 0, 10),
                'IDCBLOCAGE' => substr($takeSubIfMainEmpty($frn['idcBlocage'], $org['idcBlocage']) ?? '', 0, 1),
                'ADRCODEPOSTAL' => substr($frn['adrCodePostal'] ?? '', 0, 10),
                'ADRCODEPAYS' => substr($frn['adrCodePays'] ?? '', 0, 3),
                'ADRLOCALITE' => substr($frn['adrLocalite'] ?? '', 0, 35),
                'ADRRUE1' => substr($frn['adrRue1'] ?? '', 0, 50),
                'ADRRUE2' => substr($frn['adrRue2'] ?? '', 0, 50),
                'ADRRUE3' => substr($frn['adrRue3'] ?? '', 0, 50),
                'ADRRUE4' => substr($frn['adrRue4'] ?? '', 0, 50),
                'ADRBOITEPOSTALE' => substr($frn['adrBoitePostale'] ?? '', 0, 50),
                'ADRLIBREGION' => substr($frn['adrLibRegion'] ?? '', 0, 50),
                'CODEFOURNISSEURSAP' => substr($frn['codeFournisseurSap'] ?? '', 0, 30),
                'CODEGROUPECOMPTE' => substr($this->getCodeGroupeCompte($frn['codeGroupeCompte']) ?? '', 0, 30),
                'LIBFOURNISSEUR' => substr($frn['libFournisseur'] ?? '', 0, 45),
                'LIBFOURNISSEURCOMPLEMENT' => substr($frn['libFournisseurComplement'] ?? '', 0, 45),
                'CODECONDITIONPAIEMENT' => substr($org['codeConditionPaiement'] ?? '', 0, 7),
                'CODEINCOTERM' => substr($org['codeIncoterm'] ?? '', 0, 7),
                'CODEDEVISE' => substr($org['codeDevise'] ?? '', 0, 3),
                'NUMEROTVAINTRACOM' => substr($frn['numeroTvaIntraCom'] ?? '', 0, 15),
                'REMARQUE' => substr($frn['remarque'] ?? '', 0, 20),
                'CODEDUNS' => substr($frn['codeDuns'] ?? '', 0, 100),
                'CODELANGUE' => substr($frn['codeLangue'] ?? '', 0, 3),
                'TELFIXE' => substr($frn['telFixe'] ?? '', 0, 16),
                'TELEX' => substr($frn['telex'] ?? '', 0, 16),
                'FAX' => substr($frn['fax'] ?? '', 0, 16),
                'EMAIL' => substr($frn['email'] ?? '', 0, 100),
                'MNTMINIMAL' => $org['mntMinimal'] ?? '',
            ];

            foreach ($contacts as $cnt) {
                if (!empty($cnt['libFournisseur']) ||
                    !empty($cnt['prenom']) ||
                    !empty($cnt['fonction']) ||
                    !empty($cnt['telFixe']) ||
                    !empty($cnt['telPortable'] ||
                    !empty($cnt['fax']) ||
                    !empty($cnt['email']))
                ) {
                    $listCntEntity[] = [
                        'NOM' => substr($cnt['libFournisseur'] ?? '', 0, 25),
                        'PRENOM' => substr($cnt['prenom'] ?? '', 0, 25),
                        'FONCTION' => substr($cnt['fonction'] ?? '', 0, 40),
                        'TELFIXE' => substr($cnt['telFixe'] ?? '', 0, 16),
                        'TELPORTABLE' => substr($cnt['telPortable'] ?? '', 0, 16),
                        'FAX' => substr($cnt['fax'] ?? '', 0, 16),
                        'EMAIL' => substr($cnt['email'] ?? '', 0, 100),
                        'CODEFOURNISSEURSAP' => substr($frn['codeFournisseurSap'] ?? '', 0, 30),
                    ];
                }
            }
        }

        $this->multiInsert('INT_EDIFICE_IMP_FOURNISS', $listFrnEntity);
        $this->multiInsert('INT_EDIFICE_IMP_FOURNISS_CONTACT', $listCntEntity);
    }

    /**
     * @param array<mixed> $data
     * @return void
     */
    public function createRejectedData($data)
    {
        $list = [];

        foreach ($data as $item) {
            $list[] = [
                'ID'            => $item['id'],
                'REJECT_REASON' => $item['rejectReason'],
            ];
        }

        $this->multiInsert('INT_EDIFICE_EXP_REJETS', $list);
    }
}
