<?php

namespace Modules\Connexion\Service;

use Entity\Model\Hastutil;
use Entity\Model\MUChif;
use Entity\Model\OxalinkUser;
use Helpers\Securite\Securite;

class ControlePwdService
{
    const LOGIN         = 'L';
    const SIGNATURE     = 'S';
    const HAPLUS        = 'H';
    const OXALINK       = 'K';
    const KEYCONSTANT   = 'RAYA';

    private string $keyPWD;
    private string $keyMdp;
    //private string $dateMdp;

    public function __construct(
        public \PDO $pdo,
        private string $login,
        bool $oxalink = false,
        bool $signature = false
    ) {
        $this->keyPWD = $login.'|'.($signature? self::SIGNATURE:self::LOGIN).'|'.($oxalink? self::OXALINK:self::HAPLUS);

        if ($oxalink) {
            $user = (new OxalinkUser($this->pdo))->find($login, ['C_MDP', 'D_MDP']);

            $this->keyMdp   = $user['C_MDP'];
            //$this->dateMdp  = $user['D_MDP'];
        } else {
            $hastutil  = (new Hastutil($this->pdo))->find($this->login, ['DATDMMDP', 'DTMPAS', 'C_MDP_LOG', 'C_MOT_PAS']);

            if ($signature) {
                $this->keyMdp   = $hastutil['C_MOT_PAS'];
                //$this->dateMdp  = $hastutil['DTMPAS'];
            } else {
                $this->keyMdp   = $hastutil['C_MDP_LOG'];
                //$this->dateMdp  = $hastutil['DATDMMDP'];
            }
        }
    }

    public function checkPassword(?string $password = null) :bool
    {
        if (!$password) {
            return false;
        }


        if ($this->encodingPwd($password) == $this->getPwd()) {
            return true;
        }

        return false;
    }
    
    private function encodingPwd(string $password):string
    {
        $keySalage = hash('md5', 'S');
        return hash('sha256', trim($password).trim($keySalage));
    }
    
    private function getPwd():string
    {
        $allKey = (new MUChif($this->pdo))->findAll(['M_U_ID' => $this->keyPWD]);
        
        $arrayLine = [];
        foreach ($allKey as $key) {
            $arrayLine[(int)mb_substr($key['ALPHA1'], 0, 3)] = mb_substr($key['ALPHA1'], 3);
        }

        $pwdChiffre = implode('', $arrayLine);
        $ControlKey = self::KEYCONSTANT.$this->keyMdp;

        return Securite::decodeChiffrageFromMagic($pwdChiffre, $ControlKey);
    }
}
