<?php

namespace Modules\Consultation\Repository;

use Helpers\QueryBuilder\AbsRepository;
use PDO;

class ImportInfo extends AbsRepository
{
    /**
     * @var resource $pdoStorage
     */
    private $pdoStorage;

    /**
     * __construct
     *
     * @param  \PDO $pdo
     * @param  resource $pdoStorage
     */
    public function __construct(PDO $pdo, $pdoStorage)
    {
        parent::__construct($pdo);
        $this->pdoStorage = $pdoStorage;
    }
    
    /**
     * importContributors
     *
     * @param  string $idAO
     * @param  array<mixed> $contributors
     * @return array<mixed>
     */
    public function importContributors(string $idAO, array $contributors): array
    {
        // on crée la table temporaire qui nous permettra de faire les contrôles sur l'insert initial
        $query = "SELECT NO_AO, CONTRIB, '' AS STATUT
                    INTO #AO_CONTRIB
                FROM AO_CONTRIB WITH(NOLOCK)
                WHERE NO_AO = 0; ";

        // on réalise un premier insert dans la table temporaire
        $query .= "INSERT INTO #AO_CONTRIB (NO_AO, CONTRIB, STATUT)
        VALUES ";

        foreach ($contributors as $contributor) {
            $query .= '(' . $idAO . ', \'' . $contributor . '\', \'\'), ';
        }
        $query = \rtrim($query, ', ');

        // on update la table temporaire avec le champ 'statut' pour organiser les résultats
        $query .= "UPDATE T
                SET T.STATUT = 
                    CASE 
                        WHEN ISNULL (F.CODE, '') = ''
                        THEN 'E'
                        WHEN ISNULL (C.CONTRIB, '') = ''
                        THEN 'O'
                        ELSE 'D' 
                    END
                FROM #AO_CONTRIB T
                    LEFT OUTER JOIN HASTUTIL F ON F.CODE = T.CONTRIB
                    LEFT OUTER JOIN AO_CONTRIB C ON C.NO_AO = $idAO AND C.CONTRIB = T.CONTRIB;";

        // on insère les fournisseurs vérifiés et non-doublons dans la liste des fournisseurs de la campagne
        $query .= "INSERT INTO AO_CONTRIB (NO_AO, CONTRIB)
                SELECT NO_AO, CONTRIB FROM #AO_CONTRIB T WHERE T.STATUT = 'O';";

        // on exécute la requête en connexion persistante
        $stmt = sqlsrv_query($this->pdoStorage, $query);

        // on récupère le compte de fournisseurs importés et insérés
        $query = "SELECT COUNT(*) AS count FROM #AO_CONTRIB T WITH(NOLOCK) WHERE T.STATUT = 'O';";

        $stmt = sqlsrv_query($this->pdoStorage, $query);
        /** @phpstan-ignore-next-line */
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $count = $row['count'];
        }

        // on récupère la liste des contributeurs inexistants
        $query = "SELECT T.CONTRIB,
                    CASE 
						WHEN F.NOM IS NULL
						THEN 'Code inexistant'
						ELSE F.NOM
					END AS NOM 
                FROM #AO_CONTRIB T WITH(NOLOCK)
                    LEFT JOIN HASTUTIL F WITH(NOLOCK) ON T.CONTRIB = F.CODE
                WHERE T.STATUT = 'E'";

        $stmt = sqlsrv_query($this->pdoStorage, $query);
        /** @phpstan-ignore-next-line */
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $missingContributors[$row['CONTRIB']] = $row['NOM'];
        }

        // on récupère la liste des contributeurs qui étaient déjà enregistrés dans la consultation
        $query = "SELECT T.CONTRIB, F.NOM
                FROM #AO_CONTRIB T WITH(NOLOCK)
                    LEFT JOIN HASTUTIL F WITH(NOLOCK) ON T.CONTRIB = F.CODE
                WHERE T.STATUT = 'D'";

        $stmt = sqlsrv_query($this->pdoStorage, $query);
        /** @phpstan-ignore-next-line */
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $alreadyRegisteredContributors[$row['CONTRIB']] = $row['NOM'];
        }

        return [
            'count' => $count ?? 0,
            'missingContributors' => $missingContributors ?? [],
            'alreadyRegisteredContributors' => $alreadyRegisteredContributors ?? [],
        ];
    }
}
