<?php

namespace Modules\GlobalApplication\Repository;

use Helpers\Outil\Sql;
use PDO;

class Numerotation
{

    /**
     * getNumeroReserver
     *
     * @param  PDO $pdo
     * @param  string $societe
     * @param  string $typeDoc
     *  'DA' => Demande Achat,
     *  'AO' => Consultation,
     *  'CA' => Commande,
     *  'BR' => Bon réception/retour,
     *  'EX' => Expédition,
     *  'FA' => Facture
     * @return string
     */
    public static function getNumeroReserver(PDO $pdo, string $societe, string $typeDoc) : string
    {
        $idSession = Sql::getNumSession();
        $req = "exec STD_UTI_DONNE_MOI_UN_NUMERO_DOCUMENT 0, '', '', :user, :idSession, :societe, :typeDoc, '' ;";

        $arrayReq = [
            ':user'         => $_SESSION["Session_Login"],
            ':idSession'    => $idSession,
            ':societe'      => $societe,
            ':typeDoc'      => $typeDoc,
        ];

        $requete = $pdo->prepare($req);
        $requete->execute($arrayReq);

        return $requete->fetch()[''];
    }
    
    public static function deleteReserver(\PDO $pdo, string $typeDoc, string $numero) : void
    {
        $convertType = [
            'CA'    => 'NO_CA',
            'DA'    => 'NO_DA',
            'FA'    => 'NO_FA',
            'AO'    => 'NO_AO',
            'BR'    => 'NO_BR',
        ];

        $req = "DELETE FROM NORESERV WHERE ".$convertType[$typeDoc]." = :numero";

        $arrayReq = [
            ':numero'       => $numero,
        ];

        $requete = $pdo->prepare($req);
        $requete->execute($arrayReq);
    }
    
    /**
     * cleanReservationTable
     *
     * @param  PDO $pdo
     * @param  string $typeDoc
     * @param  string $login
     * @return void
     */
    public static function cleanReservationTable(PDO $pdo, string $typeDoc, string $login): void
    {
        $convertType = [
            'CA'    => 'NO_CA',
            'DA'    => 'NO_DA',
            'FA'    => 'NO_FA',
            'AO'    => 'NO_AO',
            'BR'    => 'NO_BR',
        ];

        $query = "DELETE FROM NORESERV
        WHERE UTIL = :login
            AND {$convertType[$typeDoc]} <> 0";

        $params = [
            ':login' => $login,
        ];

        $requete = $pdo->prepare($query);
        $requete->execute($params);
    }
}
