<?php
namespace nota\controllers;

use frontend\models\ResendVerificationEmailForm;
use frontend\models\VerifyEmailForm;
use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use common\models\MemberForm;
use frontend\models\ProfileForm;
use nota\models\PasswordResetRequestForm;
use nota\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use nota\models\MemberFormIPL;
use nota\models\Usermember;
use nota\models\KasirShift;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use common\helper\SendemailBatal;
use yii\helpers\Html;
use yii\helpers\BaseInflector;
use common\helper\Helper;
use yii\db\Expression;


/**
 * Site controller
 */
class SiteController extends Controller
{
	public $layout = "main2";
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

	public function actionIndex()
    {
    	$shift = KasirShift::getActiveShift();

		if (!$shift) {
		    return $this->redirect(['kasir-shift/buka']);
		}

    	return $this->render('index');	
        
    }
	
	public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new MemberFormIPL();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }
	
	public function actionLogout()
{
    $userId = Yii::$app->user->id;

    $shiftOpen = KasirShift::find()
        ->where([
            'user_id' => $userId,
            'status' => 'open'
        ])
        ->one();

    if ($shiftOpen) {

        Yii::$app->session->setFlash(
            'error',
            'Shift masih terbuka! Silakan tutup kasir terlebih dahulu.'
        );

        return $this->redirect([
            'kasir-shift/tutup',
            'id' => $shiftOpen->id
        ]);
    }

    Yii::$app->user->logout();
    return $this->goHome();
}
	public function actionLogout2()
    {
    	/* $iduser = Yii::$app->user->identity->id;
		$idPelanggan= SessionFrontendUser::find()
                ->select(['*'])
				->where(['user_id' => $iduser])
                ->one();
		$idPelanggan->user_id;
		$idPelanggan->delete($idPelanggan->user_id);
		//exit;
		 */
        Yii::$app->user->logout();

        return $this->goHome();
    }
	
	public function actionBaranglist($q = null, $id = null) {
                \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                   $out = ['results' => ['id' => '', 'text' => '']];
            if (!is_null($q)) {
                $query = new \yii\db\Query;
				$query->distinct(true)
                ->select(['m_barang.iId as id', 'CONCAT(m_barang.vNama) AS text', 'm_barang.foxid AS description'])
                    ->from('m_barang')
                    ->leftjoin('t_stock','m_barang.iId = t_stock.iBarangid and t_stock.iCabangid = 1')
                    ->where(['like', 'm_barang.vNama', $q])
                    ->orwhere(['like','m_barang.foxid',$q])
                   ->andWhere(['not', ['m_barang.foxid' => null]])
                    ->limit(20);
                $command = $query->createCommand(Yii::$app->db);
                $data = $command->queryAll();
                $out['results'] = array_values($data);
            }
            elseif ($id > 0) {
                $out['results'] = ['id' => $id, 'text' => \app\models\Barang::find($id)->vNama,'decription' =>  \app\models\Barang::find($id)->foxid];
            }
            return $out;
        }
	

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    /**
     * Verify email address 
     *
     * @param string $token
     * @throws BadRequestHttpException
     * @return yii\web\Response
     */
    public function actionVerifyEmail($id, $token)
    {
    	//die;
    	$user = Usermember::find()->where([
            'id'=>$id,
            'verification_token'=>$token,
            'status'=>2,
            ])->one();
			
			
		//print_r($user);exit;			
		if (empty($user)) {          
            
             $userAktif = Usermember::find()->where([
            'id'=>$id,
            'verification_token'=>$token,
            'status'=>10,
            ])->one();

             if ($userAktif) {
                if($userAktif->idKelas == 0){
                	Yii::$app->getSession()->setFlash('success', 
					"
					Akun anda sudah aktif, silahkan login menggunakan email anda! <br><br>
					<a class='btn confer-btn' href='https://play.google.com/store/apps/details?id=app.mobile.iplcluster'>
			        Buka Aplikasi !
			        </a> 
			        <a class='btn confer-btn' href='https://myipl.my.id'>
			         Login ke Dashboard Admin
			        </a> 
			        <br>
			        </a>
					<script type='text/javascript'>
					    $(window).on('load',function(){
					        $('#myModalnotif').modal({backdrop: 'static', keyboard: false});
					    });
					</script>"
					  );
                }else{
                	Yii::$app->getSession()->setFlash('success', 
					"
					Akun anda sudah aktif, silahkan login menggunakan email anda! <br><br>					
			        <a class='btn confer-btn' href='https://myipl.my.id/index.php?r=site%2Flogin'>
			        Via Web !
			        </a>
			        <br> Ubah password disini
			        <a class='btn confer-btn' href='https://myipl.my.id/index.php?r=site%2Frequest-password-reset'>
			        Ubah password !
			        </a>
			        </a>
					<script type='text/javascript'>
					    $(window).on('load',function(){
					        $('#myModalnotif').modal({backdrop: 'static', keyboard: false});
					    });
					</script>"
					  );
                }
					
				  
            } else {             
            	Yii::$app->getSession()->setFlash('success', 
				"
				Terjadi Kesalahan, Akun anda tidak ditemukan pada system kami, harap register terlebih dahulu
				<script type='text/javascript'>
				    $(window).on('load',function(){
				        $('#myModalnotif').modal('show');
				    });
				</script>"
				  );
            }
			return $this->goHome(); 
			/* if($userAktif->idKelas == 0){
				header("location: https://play.google.com/store/apps/details?id=icam.opan.untukguru", true, 301);
			}else{
				header("location: https://sarerea.com/guru/nota/web/index.php?r=site%2Flogin", true, 301);
			}*/
			//return $this->goHome(); 
			
			exit;
        } else {
        	
			
			
        }
		
		


		$rand = Yii::$app->security->generateRandomString(10);
    	$user->slug = BaseInflector::slug($user->vNama.' '.$rand) ; 
    	$user->status=10;
        $user->save();

        $usercek = Usermember::find()->where([
            'status'=>10,
            'idCluster'=>$user->idCluster,
            ])->all();

        if(count($usercek)==1){
        	$usercek2 = Usermember::find()->where([
            'status'=>10,
            'idCluster'=>$user->idCluster,
            ])->one();
        	$usercek2->eType='BENDAHARA';
        	$usercek2->eAdmin = 'Ya';
        	$usercek2->save();
        }
            
		if ($user->save()) {
                if($user->idKelas == 0){
                	Yii::$app->getSession()->setFlash('success', 
					"
					Akun anda sudah aktif, silahkan login menggunakan email anda! <br><br>
					<a class='btn confer-btn' href='https://play.google.com/store/apps/details?id=app.mobile.iplcluster'>
			        Buka Aplikasi !
			        </a>
			        <a class='btn confer-btn' href='https://myipl.my.id'>
			         Login ke Dashboard Admin
			        </a>  
			        <br>
			        </a>			        
					<script type='text/javascript'>
					    $(window).on('load',function(){
					        $('#myModalnotif').modal({backdrop: 'static', keyboard: false});
					    });
					</script>
					
					
					"
					
					  );
                }else{
                	Yii::$app->getSession()->setFlash('success', 
					"
					Akun anda sudah aktif, silahkan login menggunakan email anda! <br><br>					
			        <a class='btn confer-btn' href='https://myipl.my.id/index.php?r=site%2Flogin'>
			        Via Web !
			        </a>
			        <br> Ubah password disini
			        <a class='btn confer-btn' href='https://myipl.my.id/index.php?r=site%2Frequest-password-reset'>
			        Ubah password !
			        </a>
			        </a>
					<script type='text/javascript'>
					    $(window).on('load',function(){
					        $('#myModalnotif').modal({backdrop: 'static', keyboard: false});
					    });
					</script>"
					  );
                }
               } else {
                     Yii::$app->getSession()->setFlash('danger', [
                    'type' => 'danger',
                    'icon' => 'fa fa-check-square',
                    'title' => 'Oops!',
                    'message' => 'Gagal Mengaktifkan account anda, silahkan coba kembali atau, hubungi kami!',
                ]);
               }
		return $this->goHome(); 
		/*if($user->idKelas == 0){
			header("location: https://play.google.com/store/apps/details?id=icam.opan.untukguru", true, 301);
		}else{
			header("location: https://sarerea.com/guru/nota/web/index.php?r=site%2Flogin", true, 301);
		}*/
 /*	
        try {
            $model = new VerifyEmailForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($user = $model->verifyEmail()) {
            if (Yii::$app->user->login($user)) {
                Yii::$app->session->setFlash('success', 'Your email has been confirmed!');
                return $this->goHome();
            }
        }

        Yii::$app->session->setFlash('error', 'Sorry, we are unable to verify your account with provided token.');
        return $this->goHome(); */
    }

    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        	
        	//require_once('library-email/function.php');	        
	        $user = Usermember::findOne([
	            'status' => 10,
	            'email' => $model->email ,
	        ]);
			
			$user->password_reset_token =  Yii::$app->security->generateRandomString() . '_' . time();
        	$user->save();
	        
			$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_reset_token]);
			//var_dump($user->password_reset_token);die;
	        Yii::$app
                    ->mailer
                    ->compose()
                    ->setFrom(['noreply@ipl.my.id' => 'IPL'])
                    ->setTo($model['email'])
                    ->setSubject('No Reply - Reset Password Akun IPL')
					->setHtmlBody('<style>
					a.btn-mail {
					background-color:#27a2db;
					color:#f5f5f5;
					width:100%;
					padding:15px;
					margin-left:0;
					margin-right:0;
					}
					a.btn-mail:hover{
					background-color:#2795c8;
					}
					</style>
					
					<h2 align="center">Reset Password Akun IPL</h2>	
					<h4>Yth.'.Html::encode($user->vNama).',</h4>
					<h4>Anda telah melakuakan permohonan reset password, Silahkan Klik link di bawah ini</h4>
					<p> '.Html::a('Reset Password',$resetLink, ['class'=>'btn-mail']).'</p>
					<h5>Abaikan email ini jika anda tidak pernah meminta untuk reset password.</h5>
					
					<p ><strong>Email otomatis, Jangan Membalas Email ini</strong>,</p>
			
					
					')
                    ->send();
					
			/*		
			$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password', 'token' => $user->password_reset_token]);
			$to       = $user->email;
			$subject  = 'Reset';
			$message  = '
			';
			smtp_mail($to, $subject, $message, '', '', 0, 0, FALSE);
			 * */
            if ($model) {
                //Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
				Yii::$app->getSession()->setFlash('success', 
			"
			Anda telah berhasil mereset password, silahkan cek email anda!
			<script type='text/javascript'>
			    $(window).on('load',function(){
			        $('#myModalnotif').modal('show');
			    });
			</script>"
			  );
                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');
            return $this->redirect(['login']);
            // return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    /**
     * Resend verification email
     *
     * @return mixed
     */
    public function actionResendVerificationEmail()
    {
        $model = new ResendVerificationEmailForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
                return $this->goHome();
            }
            Yii::$app->session->setFlash('error', 'Sorry, we are unable to resend verification email for the provided email address.');
        }

        return $this->render('resendVerificationEmail', [
            'model' => $model
        ]);
    }
	
	
	
}
