<?php

use Doctrine\ORM\EntityRepository;

class TempOtpRepository extends EntityRepository
{

    public function addOtp($body)
    {
        $entityManager = $this->getEntityManager();
        $email = addslashes(strip_tags(trim($body['email'])));
        $data = $entityManager->getRepository('Student')->getStudentByEmail($email);
        if (sizeof($data) > 0) {
            $phone = $data['phone'];
            $r = $this->checkEmail($phone);
            $otp = $this->generateOTP();

            if (sizeof($r) == 0) {
                $ot = new TempOtp();
                $ot->setEmail($phone);
                $ot->setOtp($otp);
                $entityManager->persist($ot);
                $entityManager->flush();
            } else {
                $r[0]->setOtp($otp);
                $entityManager->persist($r[0]);
                $entityManager->flush();
            }

            //sms for otp
            $b['phone'] = $phone;
            $b['otp'] = $otp;

            require_once __DIR__ . '/../utility.php';
            $sm = new SendSms();
            if ($sm->send_sms_forgot_password($b)) {
                $np = substr($phone, 6, 4);
                return "An OTP has been sent to your mobile number: ******" . $np;
           }else{
                return "Server is busy. Please try again later";
            }

        } else {
            return false;
        }
    }

    private function checkEmail($email)
    {
        $dql = 'SELECT r From TempOtp r where r.email=:email';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('email', $email);
        return $query->getResult();
    }

    private function generateOTP()
    {
        $otp = mt_rand(100000, 999999);
        $dql = 'SELECT r From TempOtp r where r.otp=:otp';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('otp', $otp);
        $result = $query->getResult();
        if (sizeof($result) !== 0) {
            $this->generateOTP();
        } else {
            return $otp;
        }

    }

    public function checkOtp($email, $otp)
    {
        $entityManager = $this->getEntityManager();
        $data = $entityManager->getRepository('Student')->getStudentByEmail($email);
        if (sizeof($data) > 0) {
            $phone = $data['phone'];
            $dql = 'SELECT r From TempOtp r where r.otp=:otp AND r.email=:email';
            $query = $this->getEntityManager()
                ->createQuery($dql)
                ->setParameter('otp', $otp)
                ->setParameter('email', $phone);
            $result = $query->getResult();
            if (sizeof($result) == 1) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

}
