Your IP : 216.73.216.79


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

<?php

namespace backend\controllers;

use Yii;
use common\models\User;
use backend\models\Staff;
use backend\models\StaffDetail;
use common\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;
use backend\models\EmailTemplates;

/**
 * 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' => ['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())) {
            $user_pwd = $model->password;
            $model->username;
            $model->email;
            $model->password_hash = Yii::$app->security->generatePasswordHash($model->password);
            $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();
                
                /* SEND EMAIL START */
                $EmailTemplates = new EmailTemplates();
                $arrEmail = ['#USERNAME#' => $model->staff_name, '#USERPASSWORD#' => $user_pwd, '#USERID#' => $model->username];
                $sendEmail = $EmailTemplates->sendEmail(1, $model->email, $arrEmail); //email_id, send_to, variable need to replace
                $emailMsg = '';
                if ($sendEmail == 1)
                    $emailMsg = 'Emel telah berjaya dihantar ke pengguna';
                /* SEND EMAIL START */
                
                Yii::$app->session->setFlash('success', Yii::t('app', 'Pengguna baru berjaya ditambah. ' . $emailMsg));
                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);
        $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 (!empty($model->password))
                    $model->password_hash = Yii::$app->security->generatePasswordHash($model->password);


                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);
        $model->scenario = 'manageUser';

        $oldHashPassword = $model->password_hash;
        if ($model->load(Yii::$app->request->post())) {
            $model->password_hash = Yii::$app->security->generatePasswordHash($model->password);

            if ($model->save(false)) {
                Yii::$app->session->setFlash('success', Yii::t('app', 'Password has successfully change'));
                return $this->redirect(["site/index"]);
            }
        }
        return $this->render('changePassword', [
                    'model' => $model,
                    'user_info_model' => $user_info_model,
                    'oldHashPassword' => $oldHashPassword
        ]);
    }

}