<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use app\models\Admins;
use app\models\AdminsSearch;
use app\models\ContactForm;
use app\models\SystemConfigurations;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AdminsController implements the CRUD actions for Admins model.
 */
class AdminsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['login', 'reset-password', 'reset-password2', 'reset-code', 'forget-password'],
                        'roles' => ['?'],
                    ],
                    // [
                    //     'allow' => false,
                    //     'actions' => ['login', 'reset-password', 'reset-password2', 'reset-code', 'forget-password'],
                    //     'roles' => ['@'],
                    // ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
                'denyCallback' => function ($rule, $action) {
                    Yii::$app->session->setFlash('unauthenticated', Yii::t('app', 'You are not authenticated, please login to access this page.'));
                    return $this->redirect(['admins/login']);
                }
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Admins models.
     * @return mixed
     */

    public function actionIndex()
    {
        $searchModel = new AdminsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Admins model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Admins model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */

    /**
     * Updates an existing Admins model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return var_dump($model->getErrors());
        }

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

    public function actionChangePassword($id)
    {
        $model = Admins::find()->where(['id' => $id])->one();
        $model->scenario = Admins::SCENARIO_RESET_PASSWORD;
            
        if ($model->load(Yii::$app->request->post())) {
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return var_dump($model->getErrors());
        }
            
        return $this->render('change-password', ['model' => $model]);

    }

    /**
     * Deletes an existing Admins model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Admins model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Admins the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Admins::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionCreate(){
        $model = new Admins();
        $model->scenario = Admins::SCENARIO_REGISTER;

        if($model->load(Yii::$app->request->post())){
            if($model->save()){
                return $this->redirect(['view', 'id'=>$model->id]);
            }
            else{
                $model->addError('already_exist', Yii::t('app', 'Email already exist.'));
                return $this->render('create', ['model' => $model]);
            }
        }

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

    public function actionProfile(){
        return $this->render('profile');
    }

    public function actionLogout(){
        Yii::$app->user->logout();
        return $this->redirect(['login']);
    }

    public function actionLogin(){

        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['site/index']);
        }

        $model = new Admins();
        $model->scenario = Admins::SCENARIO_LOGIN;

        if($model->load(Yii::$app->request->post())){
            $identity = Admins::find()->where(['username' => $model->username])->one();
            if($identity && Yii::$app->getSecurity()->validatePassword($model->password, $identity->password)){
                Yii::$app->user->login($identity);
                return $this->redirect(['site/index']);
            }
            else {
                $model->addError('failed_login', Yii::t('app', 'Username or password is incorrect!'));
            }
        }

        $logo = SystemConfigurations::findOne(['config_option' => 'logo']);
        return $this->render('login', [
            'user' => $model,
            'logo' => $logo
        ]);
    }

    // public function actionForgetPassword(){
    //     if (!Yii::$app->user->isGuest) {
    //         return $this->redirect(['site/index']);
    //     }
    //     $model = new Admins;
    //     if ($model->load(Yii::$app->request->post())){
    //         $identity = Admins::find()->where(['email' => $model->email])->one();
    //         if ($identity != null){
    //             $identity->reset_password_code = (string) random_int(1000000,9999999);
    //             $mail = Yii::$app->mailer->compose()
    //                 ->setFrom('farra.18397ibra@gmail.com')
    //                 ->setTo($model->email)
    //                 ->setSubject('Reset password')
    //                 ->setTextBody('Your reset password code is: '.$identity->reset_password_code)
    //                 ->send();
    //             if ($identity->save()){
    //                  return $this->redirect(['reset-code', $identity]);
    //             }
    //             else {
    //                return var_dump($identity->getErrors());
    //             }
    //         }
    //         else {
    //             $model->addError('email_not_found', Yii::t('app', 'The email you entered is not found, please make sure you typed it correctly'));
    //         }
    //     } 

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

    // public function actionResetCode(){
    //      if (!Yii::$app->user->isGuest) {
    //          return $this->redirect(['site/index']);
    //      }
    //     $model = new Admins;
    //     if ($model->load(Yii::$app->request->post())){
    //         $identity = Admins::find()->where(['reset_password_code' => $model->reset_password_code])->one();
    //         if ($identity != null){ 
    //                 return $this->redirect(['reset-password', 'reset_password_code' => $identity->reset_password_code]);
    //         }
    //         else {
    //         $model->addError('wrong_reset_code', 'The reset code you entered is wrong!');
    //         }
    //     }
    //     return $this->render('reset-code', ['model' => $model]);
    // }

    public function actionResetPassword2($reset_password_code)
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['site/index']);
        }

        $model = Admins::find()->where(['reset_password_code' => $reset_password_code])->one();
        if ($model){
            $model->scenario = Admins::SCENARIO_RESET_PASSWORD;
            
            if ($model->load(Yii::$app->request->post())) {
                $model->reset_password_code = null;
                if($model->save()){
                    return $this->redirect('login');
                }
                return var_dump($model->getErrors());
            }

            return $this->render('code-method/reset-password', ['model' => $model]);
        }
        else {
            return $this->render('code-method/reset-password', ['model' => $model]);
        }
    }

    public function actionForgetPassword()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['site/index']);
        }

        $model = new Admins;
        if ($model->load(Yii::$app->request->post())){
            $identity = Admins::find()->where(['email' => $model->email])->one();
            if ($identity != null){
                $identity->reset_password_token = str_replace("#", "!", Yii::$app->getSecurity()->generateRandomString(60));
                // $mail = Yii::$app->mailer->compose()
                //     ->setFrom('farra.18397ibra@gmail.com')
                //     ->setTo($model->email)
                //     ->setSubject('Reset password')
                //     ->setTextBody('please navigate to this link to reset your password: ' . \yii\helpers\Url::base(true) . '/admins/reset-password?reset_password_token=' . $identity->reset_password_token)
                //     ->send();
                if ($identity->save()){
                    Yii::$app->session->setFlash('emailSent', Yii::t('app', 'We sent you a link to your email to reset your password, please visit your email to find it'));
                    return $this->redirect(['forget-password', $identity]);
                }
                else {
                   return var_dump($identity->getErrors());
                }
            }
            else {
                $model->addError('email_not_found', Yii::t('app', 'The email you entered is not found, please make sure you typed it correctly'));
            }
        } 

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

    public function actionResetPassword($reset_password_token)
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['site/index']);
        }

        $model = Admins::find()->where(['reset_password_token' => $reset_password_token])->one();
        if ($model){
            $model->scenario = Admins::SCENARIO_RESET_PASSWORD;
            
            if ($model->load(Yii::$app->request->post())) {
                $model->reset_password_token = null;
                if($model->save()){
                    Yii::$app->session->setFlash('passwordChanged', Yii::t('app', 'Password changed successfully, Please login'));
                    return $this->redirect('login');
                }
                return var_dump($model->getErrors());
            }

            return $this->render('reset-password', ['model' => $model]);
        }
        else {
            return $this->render('reset-password', ['model' => $model]);
        }
    }
}
