<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use dektrium\user\models\LoginForm;
use dektrium\user\models\UserLog;
use dektrium\user\models\RegistrationForm;
use dektrium\user\models\User;
use dektrium\user\traits\AjaxValidationTrait;
use dektrium\user\traits\EventTrait;
use yii\web\Session;
use dektrium\user\helpers\Password;

class SecurityController extends Controller {

    public $defaultAction = 'login';

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'register', 'verify', 'forgotpassword', 'otpnewpassword', 'passwordupdate'],
                        'allow' => true,
                        'roles' => ['?', '@']
                    ],
                ]
            ],
        ];
    }

    public function actions() {
        return [
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'authenticate'],
            ]
        ];
    }

    public function actionLogin() {
        if (Yii::$app->user->isGuest) {
            $l_model = \Yii::createObject(LoginForm::className());
           
            if (Yii::$app->request->isAjax && $l_model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = 'json';
                return ActiveForm::validate($l_model);
            }
            if ($l_model->load(\Yii::$app->getRequest()->post()) && $l_model->validate()) {
                if ($l_model->login()) {
                    $log = new UserLog();
                    $log->loger();
                }
                if(Yii::$app->user->getReturnUrl() != '/') {
                    return $this->redirect(Yii::$app->user->getReturnUrl());
                } else {
                    return $this->redirect(['myaccount/index']);
                }
            }
            if (\Yii::$app->request->isAjax) {
                return $this->renderAjax('wlogin', [
                            'l_model' => $l_model,
                            'module' => $this->module,
                ]);
            } else {
                return $this->render('index', [
                            'l_model' => $l_model,
                ]);
            }
        } else {
            \Yii::$app->session->setFlash('growl', "You are already login!");
            return $this->redirect(['/']);
        }
    }

    public function actionRegister() {
        $r_model = \Yii::createObject(RegistrationForm::className());

        if (Yii::$app->request->isAjax && $r_model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($r_model);
        }
        if ($r_model->load(\Yii::$app->request->post()) && $r_model->register()) {
            //\Yii::$app->getSession()->setFlash('growl', "A message sent to your email address. It contains a confirmation link that you must click to complete registration!");
            return $this->redirect('verify.php');
        }

        return $this->render('register', [
                    'r_model' => $r_model,
        ]);
    }
    
    public function actionVerify() {
        $mobileno = \Yii::$app->session->get('phoneno');
        $userid = \Yii::$app->session->get('userid');
        $otp = \Yii::$app->session->get('otp');
        if($mobileno != '' && $otp != '') {
        if(Yii::$app->request->post()) {
         if(Yii::$app->request->post('otpvalue') != '') {   
        if(!strcmp($otp,Yii::$app->request->post('otpvalue'))) {
            $session = Yii::$app->session;
            unset($session['phoneno']);
            unset($session['userid']);
            unset($session['otp']);
			
			$connection = Yii::$app->db;
			$command = $connection->createCommand()->update('user', ['confirmed_at' => time()], ['phoneno' => $mobileno, 'id' => $userid])->execute();
			$connection->close();

            \Yii::$app->session->setFlash('Commfirm', "Your account registration has been Verify successfully.");             
            return $this->redirect('login.php');             
        } else {
            \Yii::$app->session->setFlash('danger', "Invalid OTP please try again.");
            return $this->redirect(Yii::$app->request->referrer);
        }
        } else if(Yii::$app->request->post('resend_otp') != '') {
            $authKey = "251670AsGjrn9mKMHz5c122490";
            //Multiple mobiles numbers separated by comma
            $mobileNumber = $mobileno;
            
            //Sender ID,While using route4 sender id should be 6 characters long.
            $senderId = "CLAIAS";
            //Your message to send, Add URL encoding here.
            $rndno=$otp;
            $message = "Your OTP Code is ".$rndno.". Thank you for signing up with Classic IAS Academy.";
            
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
              CURLOPT_URL => "https://control.msg91.com/api/sendotp.php?otp=$rndno&sender=$senderId&message=$message&mobile=$mobileNumber&authkey=$authKey",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => "POST",
              CURLOPT_POSTFIELDS => "",
              CURLOPT_SSL_VERIFYHOST => 0,
              CURLOPT_SSL_VERIFYPEER => 0,
            ));
            
            $response = curl_exec($curl);
            $err = curl_error($curl);
            
            curl_close($curl);
            
            if ($err) {
              echo "cURL Error #:" . $err;
            }
           \Yii::$app->session->setFlash('sendre', "Sucessfully send OTP to your Mobile Number.");    
          return $this->redirect(Yii::$app->request->referrer); 
        } else {
             \Yii::$app->session->setFlash('danger', "OTP Reqiured!");
             return $this->redirect(Yii::$app->request->referrer); 
        }
        }
        return $this->render('verify',[
              'phoneno' => $mobileno,
              'ottp' => $otp,
            ]);
        } else {
            return $this->render('register');
        }        
    } 
    
    public function actionForgotpassword() {
        if(Yii::$app->request->post()) {
       if(Yii::$app->request->post('phone') != '') {
        //check whether user exists in the database
        $user_model = User::find()->where(['phoneno' => Yii::$app->request->post('phone')])->one();
        
        if($user_model != '') { 
            
        	if($user_model->confirmed_at == '') {
        		\Yii::$app->session->setFlash('danger', "Account not Active !");
             return $this->redirect(Yii::$app->request->referrer);
        	} else {
        	
            //Your authentication key
            $authKey = "251670AsGjrn9mKMHz5c122490";
            //Multiple mobiles numbers separated by comma
            $mobileNumber = Yii::$app->request->post('phone');
            //Sender ID,While using route4 sender id should be 6 characters long.
            $senderId = "CLAIAS";
            //Your message to send, Add URL encoding here.
            $rndno=rand(100000, 999999);
            $message = urlencode("Your OTP Code is ".$rndno.". for new password with Classic IAS Academy.");
            $route = "route=4";
            //Prepare you post parameters
            $postData = array(
                'authkey' => $authKey,
                'mobiles' => $mobileNumber,
                'message' => $message,
                'sender' => $senderId,
                'route' => $route
            );
            //API URL
            $url="https://control.msg91.com/api/sendhttp.php";
            
            // init the resource
            $ch = curl_init();
            curl_setopt_array($ch, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $postData
                //,CURLOPT_FOLLOWLOCATION => true
            ));
            
            
            //Ignore SSL certificate verification
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            
            
            //get response
            $output = curl_exec($ch);
            \Yii::$app->session->set('phoneno',$mobileNumber);
            \Yii::$app->session->set('userid',$user_model->id);
            \Yii::$app->session->set('otp',$rndno);
            \Yii::$app->session->setFlash('sendre', "Sucessfully send OTP to your Mobile Number.");    
            return $this->redirect('otp-new-password.php');   
        	}
        
        } else {
        	\Yii::$app->session->setFlash('danger', "Given Phone Number is not associated with any account.");
             return $this->redirect(Yii::$app->request->referrer);
        }
        
        } else {
           \Yii::$app->session->setFlash('danger', "Enter Phone Number to create a new password for your account.");
             return $this->redirect(Yii::$app->request->referrer); 
        }
        } else {
        return $this->render('forgotpassword');
        }
    }
    
     public function actionOtpnewpassword() {
         $mobileno = \Yii::$app->session->get('phoneno');
        $userid = \Yii::$app->session->get('userid');
        $otp = \Yii::$app->session->get('otp');
        if($mobileno != '' && $otp != '') {
        if(Yii::$app->request->post()) {
         if(Yii::$app->request->post('otpvalue') != '') {   
        if(!strcmp($otp,Yii::$app->request->post('otpvalue'))) {
            return $this->redirect('passwordupdate.php');             
        } else {
            \Yii::$app->session->setFlash('danger', "Invalid OTP please try again.");
            return $this->redirect(Yii::$app->request->referrer);
         }
        } else if(Yii::$app->request->post('resend_otp') != '') {
            $authKey = "251670AsGjrn9mKMHz5c122490";
            //Multiple mobiles numbers separated by comma
            $mobileNumber = $mobileno;
            
            //Sender ID,While using route4 sender id should be 6 characters long.
            $senderId = "CLAIAS";
            //Your message to send, Add URL encoding here.
            $rndno=$otp;
            $message = "Your OTP Code is ".$rndno.". Thank you for signing up with Classic IAS Academy.";
            
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
              CURLOPT_URL => "https://control.msg91.com/api/sendotp.php?otp=$rndno&sender=$senderId&message=$message&mobile=$mobileNumber&authkey=$authKey",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => "POST",
              CURLOPT_POSTFIELDS => "",
              CURLOPT_SSL_VERIFYHOST => 0,
              CURLOPT_SSL_VERIFYPEER => 0,
            ));
            
            $response = curl_exec($curl);
            $err = curl_error($curl);
            
            curl_close($curl);
            
            if ($err) {
              echo "cURL Error #:" . $err;
            }
           \Yii::$app->session->setFlash('sendre', "Sucessfully send OTP to your Mobile Number.");    
          return $this->redirect(Yii::$app->request->referrer); 
        } else {
             \Yii::$app->session->setFlash('danger', "OTP Reqiured!");
             return $this->redirect(Yii::$app->request->referrer); 
        }
        }
        return $this->render('otpnewpassword',[
              'phoneno' => $mobileno,
              'ottp' => $otp,
            ]);
        } else {
            return $this->render('register');
        }        
    }
    
    public function actionPasswordupdate() {
        if(Yii::$app->request->post()) {
        if(Yii::$app->request->post('newpassword') != '' && Yii::$app->request->post('confirm_password') != '' && Yii::$app->session->get('phoneno') != '') {
	    //password and confirm password comparison
        if(Yii::$app->request->post('newpassword') != Yii::$app->request->post('confirm_password')) {
            \Yii::$app->session->setFlash('danger', "Confirm password must match with the password.");
             return $this->redirect(Yii::$app->request->referrer); 
        } else {
			//check whether identity code exists in the database
            $user_model = User::find()->where(['phoneno' => Yii::$app->session->get('phoneno')])->andwhere(['id' => Yii::$app->session->get('userid')])->one();
            if($user_model != '') {
               $password = Yii::$app->request->post('newpassword');
				//update data with new password
				$connection = Yii::$app->db;
			$command = $connection->createCommand()->update('user', ['password_hash' => MD5($password)], ['phoneno' => Yii::$app->session->get('phoneno'), 'id' => Yii::$app->session->get('userid')])->execute();
			$connection->close();

            $session = Yii::$app->session;
            unset($session['phoneno']);
            unset($session['userid']);
            unset($session['otp']);             
            \Yii::$app->session->setFlash('Commfirm', "Your account password has been reset successfully. Please login with your new password.");
            return $this->redirect('login.php');  
				
            } else {
               \Yii::$app->session->setFlash('danger', "You does not authorized to reset new password of this account."); 
               return $this->redirect(Yii::$app->request->referrer);
            }
        }
    } else {
       \Yii::$app->session->setFlash('danger', "All fields are mandatory, please fill all the fields."); 
       return $this->redirect(Yii::$app->request->referrer);
    }
        } else {
     return $this->render('passwordupdate');
       }
    }        

}
