<?php
// repositories/UserRepository.php

use Doctrine\ORM\EntityRepository;

class GeneralUserRepository extends EntityRepository
{

    // get the jobs for given limit, offset

   

    private function getUserForEdit($email)
    {
        $dql = "SELECT r from GeneralUser r where r.email=:email";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('email', $email);
        return $query->getResult();
    }
   

    public function updateGenerallUser($email, $body)
    {
        $entityManager = $this->getEntityManager();

        //password hash

        require_once __DIR__ . '/../passwordHash.php';

        $pass = new passwordHash();
        $password = $pass->hash($body['password']);

        //generate jwt
        require_once __DIR__ . '/../functions/auth.php';

        $jwt = new Authentication();
        $token = $jwt->getJwtToken($body['email']);

        $result = $this->getUserForEdit($email);

        if (sizeof($result) == 1) {

            $result[0]->setPassword($password);
            $result[0]->setToken($token);

            $result[0]->setRole($body['role']);

            $result[0]->setActive(1);

            $entityManager->persist($result[0]);

            $entityManager->flush();

            return 'Successfully updated';
        } else {
            return 'Username not found';
        }
    }

  

    public function addGeneralUser($body, $role)
    {
        $entityManager = $this->getEntityManager();

        //password hash

        require_once __DIR__ . '/../passwordHash.php';

        //generate random password

        $password_new = $this->generatePassword();
        $body['password'] = $password_new;
        $pass = new passwordHash();
        $password = $pass->hash($password_new);
        //$password = $password_new;

        //generate jwt
        require_once __DIR__ . '/../functions/auth.php';

        $email = addslashes(strip_tags(trim($body['email'])));


        $user = new GeneralUser();

        if (sizeof($this->checkEmail($email)) == 0) {

            $user->setEmail($email);
            $user->setPassword($password);


            $user->setRole($role);

            $user->setActive(1);

            $entityManager->persist($user);

            $entityManager->flush();

            if (null != $user->getId()) {
                // require_once __DIR__ . '/../utility.php';
                // $sm = new SendSms();
                // ($sm->send_sms_register($body, $role)) {
                return 'success';
                // }

            }
        } else {
            return 'Email already exists';
        }
    }

    public function checkEmail($email)
    {
        $dql = 'SELECT r FROM GeneralUser r WHERE r.email=:email';
        $query = $this
            ->getEntityManager()
            ->createQuery($dql)
            ->setParameter('email', $email);
        return $query->getResult();
    }

    public function login($unit, $body, $c)
    {

        $email = addslashes(strip_tags(trim($body['email'])));
        $password = addslashes(strip_tags(trim($body['password'])));

        $flag = 0;

        require_once __DIR__ . '/../passwordHash.php';

        $data = $this->checkEmail($email);

        if (sizeof($data) == 1) {

            //taking original password
            $original_password = $data[0]->getPassword();

            //compairing password: return true / false
            $pass = new passwordHash();
            $password_check = $pass->check_password($original_password, $password);

            if ($password_check == true) {
                $flag = 1;
                //Now we know that user is authenticated so we will send the token and userdata to the client side

                //generate jwt
                require_once __DIR__ . '/../functions/auth.php';

                $entityManager = $this->getEntityManager();

                //no simultaneous login
                /* $jwt = new Authentication();
                $token = $jwt->getJwtToken($email);

                //set token

                $data[0]->setToken($token);
                $entityManager->persist($data[0]);

                $entityManager->flush();  */

                $token = $data[0]->getToken();

                $resp = array();

                $user_details = array();



                $user_details['email'] = $data[0]->getEmail();
                $user_details['role'] = $data[0]->getRole();


                if ($user_details['role'] === 'STUDENT') {

                    $student = $entityManager->getRepository('Student')->getStudentByEmail($email);
                    $user_details['id'] = $student['id'];
                    $api_key = $c['STUDENT_API_KEY'];
                    $user_details['apikey'] = $api_key;
                    $user_details['name'] = $student['name'];
                    $user_details['course'] = $student['course'];
                    $user_details['stream'] = $student['stream'];
                    $user_details['semester'] = $student['semester'];
                    $user_details['roll_no'] = $student['roll_no'];
                    $user_details['university_roll_no'] = $student['university_roll_no'];
                    $user_details['access'] = ["STUDENT"];
                    $user_details['scope'] = ["add", "edit", "delete", "update"];
                } else if ($user_details['role'] === 'FACULTY') {
                    $api_key = $c['FACULTY_API_KEY'];


                    $user_details['is_teaching'] = $entityManager->getRepository('Employee')->checkTeacher($email);
                    $emp = $entityManager->getRepository('Employee')->getEmployeeForEdit($email);
                    $user_details['id'] = $emp[0]->getId();
                    $user_details['name'] = $emp[0]->getName();
                    $user_details['dept_code'] = $emp[0]->getDeptCode();
                    $user_details['access'] = $entityManager->getRepository('AccessControl')->getAccessArray($email);
                    $user_details['apikey'] = $api_key;
                    $user_details['scope'] = ["add", "edit", "delete", "update"];
                } else if ($user_details['role'] === 'ALUMNI') {
                    // $api_key = $c['ALUMNI_API_KEY'];

                    // $user_details['apikey'] = $api_key;

                    // $res = $entityManager->getRepository('AlumniUser')->isAlumniVerified($email);
                    // if ($res == false) {
                    //     return false;
                    // }
                }


                $resp['user'] = $user_details;
                $jwt = new Authentication();
                $resp['token'] = $jwt->getJwtToken($user_details, $c);

                if ($user_details['role'] === $unit) {
                    return $resp;
                } else {
                    return false;
                }
            } else {
                $falg = 0;

                return 'Email/Password doesnot match';
            }
        } else {
            $flag = 0;
            return 'Email/Password doesnot match';
        }
    }

    public function changePasswod($body)
    {
        $email = addslashes(strip_tags(trim($body['email'])));

        $data = $this->checkEmail($email);
    }

    public function changePasswordMail($body)
    {
        $email = addslashes(strip_tags(trim($body['email'])));
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'From: Your name <info@address.com>' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        mail($email, 'subject', 'text', $headers);
    }

    public function checkEmailToken($email, $token)
    {
        $dql = 'SELECT r FROM GeneralUser r WHERE r.email= :email AND r.token= :token';
        $query = $this
            ->getEntityManager()
            ->createQuery($dql)
            ->setParameter('email', $email)
            ->setParameter('token', $token);

        $count = sizeof($query->getResult());

        if ($count == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function getApiKey($email)
    {
        $dql = 'SELECT r From GeneralUser r where r.email=?1';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter(1, $email);
        $result = $query->getResult();
        $role = strtoupper($result[0]->getRole());
        if ($role == 'FACULTY') {
            return getenv("HTTP_ROLE_FACULTY");
        } else if ($role == 'EXECUTIVE') {
            return getenv("HTTP_ROLE_STUDENT");
        } else if ($role == 'OTHERS') {
            return getenv("HTTP_ROLE_OTHERS");
        }
    }

    private function generatePassword()
    {
        return strtoupper(bin2hex(openssl_random_pseudo_bytes(3)));
    }

    public function changePassword($email, $body)
    {
        $entityManager = $this->getEntityManager();

        //password hash

        require_once __DIR__ . '/../passwordHash.php';

        $pass = new passwordHash();
        $new_password = $pass->hash(addslashes(strip_tags(trim($body['new_password']))));
        $old_password = $pass->hash(addslashes(strip_tags(trim($body['old_password']))));

        $result = $this->getUserForEdit($email);

        if ($pass->check_password($result[0]->getPassword(), $old_password)) {
            $result[0]->setPassword($new_password);
            $entityManager->persist($result[0]);
            $entityManager->flush();
            return true;
        } else {
            return false;
        }
    }

    public function forceChangePassword($body)
    {
        $entityManager = $this->getEntityManager();

        $email = addslashes(strip_tags(trim($body['email'])));

        //password hash

        require_once __DIR__ . '/../passwordHash.php';

        //get a new password
        $password = $this->generatePassword();

        $body['password'] = $password;

        $pass = new passwordHash();
        $new_password = $pass->hash($password);

        $result = $this->getUserForEdit($email);
        if (sizeof($result) > 0) {
            $result[0]->setPassword($new_password);
            $entityManager->persist($result[0]);
            $entityManager->flush();

            $role = $result[0]->getRole();

            //get the phone number for the user

            if ($role == 'STUDENT') {
                $phone = $entityManager->getRepository('Student')->getStudentPhoneNumber($email);
            } else if ($role == 'FACULTY') {
                $phone = $entityManager->getRepository('Employee')->getEmployeePhoneNumber($email);
            }

            $body['phone'] = $phone;

            //now send the message again

            require_once __DIR__ . '/../utility.php';
            $sm = new SendSms();
            //$sm->send_sms_register($body, $role);
            return 'A new password has been sent to the user';
        } else {
            return false;
        }
    }

    public function forgotPassword($body)
    {
        $entityManager = $this->getEntityManager();

        // send a otp to the phone number

        $data = $entityManager->getRepository('TempOtp')->addOtp($body);

        return $data;
    }

    public function forgotPasswordOtp($body)
    {
        $entityManager = $this->getEntityManager();

        // send a otp to the phone number

        $email = addslashes(strip_tags(trim($body['email'])));
        $otp = addslashes(strip_tags(trim($body['otp'])));

        $data = $entityManager->getRepository('TempOtp')->checkOtp($email, $otp);

        return $data;
    }

    public function forgotPasswordFinal($body)
    {
        $entityManager = $this->getEntityManager();

        // send a otp to the phone number

        $email = addslashes(strip_tags(trim($body['email'])));
        $otp = addslashes(strip_tags(trim($body['otp'])));
        $password = addslashes(strip_tags(trim($body['password'])));

        $data = $entityManager->getRepository('TempOtp')->checkOtp($email, $otp);

        if ($data == true) {
            $data1 = $this->changePasswordForgot($email, $password);
        } else {
            $data1 = false;
        }

        return $data1;
    }

    private function changePasswordForgot($email, $password)
    {
        $entityManager = $this->getEntityManager();

        //password hash

        require_once __DIR__ . '/../passwordHash.php';

        $pass = new passwordHash();
        $new_password = $pass->hash($password);
        $result = $this->getUserForEdit($email);
        $result[0]->setPassword($new_password);
        $entityManager->persist($result[0]);
        $entityManager->flush();
        return true;
    }
}
