<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * UserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserRepository extends EntityRepository
{
    /**
     * Check login credential
     *
     * @param string $email
     * @param string $password
     */
    public function login($email, $password) {
        if ($user = $this->findOneBy(['email' => $email])) {
           if ($user->getPassword() === sha1($password . $user->getSalt())) {
                if ($user->getActive()) {
                    return $user;
                }
                return false;
            }
            return false;
        }
        return false;
    }

    public function logout($id, $date){
        if($user = $this->find($id)) {
            $em = $this->getEntityManager();
            $user->setLastLogin($date);
            $em->persist($user);
            $em->flush();
            return true;
        }
        return false;
    }
     
  
   /**
     * Create user
     * 
     * @param array $user
     */
    protected function add($user) {
        $em = $this->getEntityManager();
        $entity = new \Entities\User();
        $entity->setFirstName($user['first_name']);
        $entity->setLastName($user['last_name']);
        $entity->setEmail($user['email']);
        $entity->setSalt(md5($user['password'] . time()));
        $entity->setPassword(sha1($user['password'] . $entity->getSalt()));
        $entity->setActive($user['active']);
        $entity->setAdmin($user['admin']);
        $em->persist($entity);
        $em->flush();
    }
    
    public function dumpUsers() {
        $users = [
            [
                'first_name' => 'Seifeddine',
                'last_name'  => 'Ferchichi',
                'email'      => 'webmaster@ferchichi-seifeddine.tn',
                'password'  => 'seifou@123',
                'admin'   => true,
                'active'  => true
            ],
        ];
        
        foreach($users as $user) {
            $this->add($user);
        }
    }
}