<?php

namespace App\Services;
use DB;

class EservicesLoginService {

    /**
     * @param string $username, $password
     */

    public static function checkUser(string $username, string $password, $etaId = 0)
    {
        $user = DB::table('users')
        ->where('username', $username)
        ->first();

        if(!empty($user)) {
            $verify = password_verify($password, $user->password);
            if ($verify) {
                $geststudent_r = DB::table('geststudent_r')
                ->where('matricule', $user->matricule)
                ->first();

                $mesEtablissement = explode(',', $geststudent_r->mesEtablissement);
                if(!($geststudent_r->idEtablissement == $etaId || in_array($etaId, $mesEtablissement))){
                    return null;
                }

                $user->{'idEtablissement'} = $geststudent_r->idEtablissement;
                if($user->type_user != 4){
                    $user->{'cheminPhoto'} = $geststudent_r->cheminPhoto;
                    $user->{'nom'}         = $geststudent_r->nom;
                    $user->{'prenom'}      = $geststudent_r->prenom;
                    $user->{'email'}       = $user->email;
                    $user->{'phone'}       = $user->phone;

                    // Modules de l'etablissement
                    $user->{'mesModules'} = DB::table('etablissement')
                    ->where(['idEtablissement'=> $geststudent_r->idEtablissement])
                    ->first()->mesModules;
                }
                return $user;
            }else{
                return false;
            }
        }else{
            $user = DB::table('users_student')
            ->where('username', $username)
            ->first();

            if(!empty($user)) {
                $verify = password_verify($password, $user->password);
                if ($verify) {
                    if($user->idEtablissement != $etaId){
                        return null;
                    }
                    return $user;
                } else {
                    return false;
                }
            }else{
                return false;
            }
        }
    }

}
