Your IP : 216.73.216.79


Current Path : /var/www/html/school/backend/controllers/
Upload File :
Current File : /var/www/html/school/backend/controllers/UserController.php

<?php

namespace backend\controllers;

use Yii;
use backend\models\User;
use backend\models\Staff;
use backend\models\StaffDetail;
use backend\models\UserSearch;
use backend\models\StaffAccess;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\components\AlertMsg;
use yii\filters\AccessControl;
use common\components\AccessRule;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'ruleConfig' => [
                    'class' => AccessRule::className(),
                ],
                'rules' => [
                    [
                        'actions' => ['index','create' , 'update', 'view','my-profile','change-password','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['index','my-profile','change-password'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new User();
        $model->scenario = 'manageUser';

        if ($model->load(Yii::$app->request->post())) {

            $model->username;
            $model->email;
            $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
            $model->auth_key = Yii::$app->security->generateRandomString();
            $model->created_at = time();

            if ($model->save()) {
                $staff = new StaffDetail();
                $staff->userid = $model->id;
                $staff->staff_name = $model->staff_name;

                if ($staff->save(false)) {

                    $myarr = Yii::$app->request->post('User');
                    $rolearr = $myarr['roleCode'];
                    if (is_array($rolearr)) {
                        foreach ($rolearr as $arr) {
                            $modelStaffAccess = new StaffAccess();
                            $modelStaffAccess->staff_info_id = $staff->id;
                            $modelStaffAccess->role_code = $arr;
                            if ($modelStaffAccess->save()){
                                $msg = 'Pengguna Telah Ditambah';
                                AlertMsg::alertByRole($msg, AlertMsg::SUPER_ADMIN);
                            }
                        }
                    }
                }
                $log = new \backend\models\Log();
                $log->module = Yii::$app->controller->id;
                $log->details = Yii::$app->controller->action->id . ":" . $model->id;

                $log->save();
                Yii::$app->session->setFlash('success', Yii::t('app', 'Pengguna baru berjaya ditambah.'));
                return $this->redirect(['update', 'id' => $model->id]);
            }
        }
        return $this->render('create', [
                    'model' => $model,
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $model->scenario = 'manageUser';
        $staff = Staff::find()->where(['userid' => $id])->one();
        $user = \common\models\User::find()->where(['id' => $id])->one();
        $staffAccess = StaffAccess::find()->where(['staff_info_id' => $staff->id])->all();

        $oldpass = $model->password_hash;

        if ($model->load(Yii::$app->request->post())) {
            $model->updated_at = time();
            if ($model->validate()) {

                $user->username = $model->username;
                $user->email = $model->email;
                $user->status = $model->status;

                if ($_POST['User']['password_hash'] == '') {
                    $model->password_hash = $oldpass;
                } else {
                    $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
                }

                if ($model->validate()) {
                     $staff->staff_name = $model->staff_name;
                }
                
               
                if ($user->save(false)) {
                    
                    if ($model->save()) {
                        $user->status = $model->status;
                        $user->email = $model->email;
                        if ($staff->save(false)) {
                            if ($model->save()) {
                            $staff->staff_name = $model->staff_name;
                            foreach ($staffAccess as $delAccess) {
                                $delAccess->delete();
                            }

                            $myarr = Yii::$app->request->post('User');
                            $rolearr = $myarr['roleCode'];
                            if (is_array($rolearr)) {
                                foreach ($rolearr as $arr) {
                                    $modelStaffAccess = new StaffAccess();
                                    $modelStaffAccess->staff_info_id = $staff->id;
                                    $modelStaffAccess->role_code = $arr;
                                    $modelStaffAccess->save(false);
                                    $msg = 'Pengguna Telah Dikemaskini';
                                AlertMsg::alertByRole($msg, AlertMsg::SUPER_ADMIN);
                                }
                            }
                            $staffAccess = StaffAccess::find()->where(['staff_info_id' => $staff->id])->all();
                        }
                        $log = new \backend\models\Log();
                        $log->module = Yii::$app->controller->id;
                        $log->details = Yii::$app->controller->action->id . ":" . $model->id;

                        $log->save();
                        Yii::$app->session->setFlash('success', Yii::t('app', 'The staff has been successfully updated.'));
                    } else {
                        print_r($model->errors);
                        exit;
                    }
                }
                }
                return $this->render('update', ['model' => $model, 'staff' => $staff, 'staffAccess' => $staffAccess,]);
            }
        } else {
            return $this->render('update', ['model' => $model, 'staff' => $staff, 'staffAccess' => $staffAccess,]);
        }
    }

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

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

    public function actionMyProfile() {
        $id = Yii::$app->user->identity->staff->id;
        $model = $this->findModel($id);
        
        if ($model->load(Yii::$app->request->post())) {
            $staffphoto = $model->staff_photo;
            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $model->file->saveAs('img/profile_pic/' . $model->id . '.' . $model->file->extension);
                $model->staff_photo = $model->id . '.' . $model->file->extension;
            } else {
                $model->staff_photo = $staffphoto;
            }

            if (!empty($_POST['Staff']['staff_dob']))
                $model->staff_dob = date('Y-m-d', strtotime($_POST['Staff']['staff_dob']));
            else
                $model->staff_dob = null;

            if (!empty($_POST['Staff']['date_joined']))
                $model->date_joined = date('Y-m-d', strtotime($_POST['Staff']['date_joined']));
            else
                $model->date_joined = null;

            if ($model->save()) {
                Yii::$app->session->setFlash('success', Yii::t('app', 'Your profile has been successfully updated.'));
                return $this->redirect(['my-profile']);
            }
        }
        return $this->render('profile', ['model' => $model]);
    }

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

    public function actionChangePassword() {
        $model = $this->findModel(Yii::$app->user->identity->id);
//        $user_info_model = User::find()->where("id='" . Yii::$app->user->identity->staff->id . "'")->one();

        $oldHashPassword = $model->password_hash;
        if ($model->load(Yii::$app->request->post())) {
            if (Yii::$app->getSecurity()->validatePassword($model->password_hash, $oldHashPassword)) {
                // password is good
                $model->password_hash = $oldHashPassword;
                $model->confirmPassword = $oldHashPassword;
            } else {
                // password is bad
                $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
                $model->confirmPassword = Yii::$app->security->generatePasswordHash($model->password_hash);
                Yii::$app->session->setFlash('success', Yii::t('app', 'Password has successfully change'));
            }
            if ($model->save(false)) {
//                $hr_staff_info_model->company_email = $model->email;

//                if ($user_info_model->save()) {
                    Yii::$app->session->setFlash('success', Yii::t('app', 'Password has successfully change'));
                    //return $this->redirect("change-password");
                    return $this->redirect(['change-password']);
//                }
            }


//            Yii::$app->session->setFlash('success', Yii::t('app', 'Password has successfully change'));
//            return $this->redirect("index.php?r=user/change-password");
        }
        return $this->render('changePassword', [
                    'model' => $model,
                    'user_info_model' => $user_info_model,
                    'oldHashPassword' => $oldHashPassword
        ]);
    }

}