Your IP : 216.73.216.79


Current Path : /var/www/html/dyna-crm/controllers/
Upload File :
Current File : /var/www/html/dyna-crm/controllers/UserController.php

<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use yii\helpers\Url;
use app\models\UserAccess;
use app\models\Menu;
use app\models\ParamList;
use app\models\Log;
use app\models\LogSearch;
use yii\helpers\ArrayHelper;
use yii\data\ArrayDataProvider;

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

    public $menu_id = 8;

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['index', 'create', 'update', 'view'],
                'rules' => [
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    //'roles' => ['?'],
                    ],
                // everything else is denied
                ],
            ],
        ];
    }

    /**
     * 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, 'menu_id' => $this->menu_id]);
    }

    public function actionLog($uuid) {
        $searchModel = new LogSearch();
        $searchModel->menu_id = $this->menu_id;
        $searchModel->data_uuid = $uuid;
        $dataProvider = $searchModel->log(Yii::$app->request->queryParams);
        return $this->render('log', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'menu_id' => $this->menu_id]);
    }

    /**
     * Displays a single User 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 User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new User();
        $model->created_dt = date("Y-m-d H:i:s");
        $model->created_by = Yii::$app->user->identity->id;
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        $model->uuid = Uuid::uuid4();
        $model->status = 1;
        $pwd = Yii::$app->security->generateRandomString(8);
        $model->pwd = \Yii::$app->security->generatePasswordHash($pwd);
        $model->auth_key = \Yii::$app->security->generateRandomString();
        $model->role = 'staff';
        if ($model->load(Yii::$app->request->post())) {
            if (empty($model->user_access)) {
                Yii::$app->session->setFlash('error', "User Access cannot be blank.");
            } else {
                if ($model->save()) {
                    $Log = new Log();
                    $Log->insertlog($this->menu_id, 'create', $model->uuid);

                    if (!empty($model->user_access)) {
                        foreach ($model->user_access as $menu_id) {
                            $model2 = new UserAccess();
                            $model2->user_id = $model->id;
                            $model2->menu_id = $menu_id;
                            $model2->created_dt = date("Y-m-d H:i:s");
                            $model2->created_by = Yii::$app->user->identity->id;
                            $model2->save();
                        }
                    }

                    $ParamList = new ParamList();

                    //send email
                    $email_content = '<html>
                <body>
                    <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                        <div style="width:70%;background-color:white;margin:0 auto;padding:0em 5em 5em 5em;border:1px solid #ccc;">
                            <p>Hi ' . $model->name . ',</p>
                            <p>Welcome to ' . Yii::$app->params['systemName'] . '!</p>
                            <p>You now can access the system as a ' . $ParamList->getlabel(2, $model->role) . ' using below details:</p>
                            <p>URL: <a href="' . Url::base(true) . '" target="_blank">' . Url::base(true) . '</a></p>
                            <p>Email: ' . $model->email . '</p>
                            <p>Password: ' . $pwd . '</p>
                            <p>- Admin -</p>
                        </div>
                    </div>
                </body>
            </html>';

                    /* Yii::$app->mailer->compose()
                      ->setFrom(Yii::$app->params['senderEmail'])
                      ->setTo($model->email)
                      ->setBcc(Yii::$app->params['bccEmail'])
                      ->setSubject('CRM System Login Details')
                      ->setHtmlBody($email_content)
                      ->send(); */

                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                    mail($model->email, 'CRM System Login Details', $email_content, $headers);

                    $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved and email has been send to user',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/index') . "';});");
                }
            }
        }

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

    /**
     * Updates an existing User 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($uuid) {
        $model = $this->findModel($uuid);
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        if ($model->load(Yii::$app->request->post())) {
            if (empty($model->user_access)) {
                Yii::$app->session->setFlash('error', "User Access cannot be blank.");
            } else {
                if ($model->save()) {
                    $Log = new Log();
                    $Log->insertlog($this->menu_id, 'update', $model->uuid);
                    if (!empty($model->user_access)) {
                        $UserAccess = new UserAccess();
                        $UserAccess->deleteAll(['user_id' => $model->id]);
                        foreach ($model->user_access as $menu_id) {
                            $model2 = new UserAccess();
                            $model2->user_id = $model->id;
                            $model2->menu_id = $menu_id;
                            $model2->created_dt = date("Y-m-d H:i:s");
                            $model2->created_by = Yii::$app->user->identity->id;
                            $model2->save();
                        }
                    }
                    $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/index') . "';});");
                }
            }
        }

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

    /**
     * Deletes an existing User 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 = $_POST['id'];
        $status = 'failed';
        if (($model = User::findOne($id)) !== null) {
            $model->status = 0;
            if ($model->save(false))
                $status = 'success';
        }
        return $status;
    }

    /**
     * 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($uuid) {
        if (($model = User::findOne(['uuid' => $uuid])) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionChangerole() {
        $role = $_POST['role'];
        $Menu = new Menu();
        return $Menu->getmenuforuser($parent = 0, $count = 1, $level = 0, $user_id = 0, $checked_list = [], $role);
    }

    public function actionProfile() {
        if (($model = User::findOne(Yii::$app->user->identity->id)) !== null) {
            if ($model->load(Yii::$app->request->post())) {
                if ($model->save(false)) {
                    $Log = new Log();
                    $Log->insertlog('8', 'update profile', $model->uuid);
                    $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/profile') . "';});");
                }
            }
            return $this->render('profile', ['model' => $model]);
        }
    }

    public function actionChangepwd() {
        $output = "";
        $new_pwd = $_POST['new_pwd'];
        if (($model = User::findOne(Yii::$app->user->identity->id)) !== null) {
            $model->updated_dt = date("Y-m-d H:i:s");
            $model->updated_by = Yii::$app->user->identity->id;
            $model->pwd = \Yii::$app->security->generatePasswordHash($new_pwd);
            if ($model->save(false)) {
                $Log = new Log();
                $Log->insertlog('8', 'update password', $model->id);
                $output = 'success';
            } else
                $output = 'failed';
        }
        return $output;
    }

    public function actionAdminresetpwd() {
        $output = "failed";
        if (($model = User::findOne($_POST['id'])) !== null) {
            $pwd = Yii::$app->security->generateRandomString(8);
            //$pwd = '12345678';
            $model->pwd = \Yii::$app->security->generatePasswordHash($pwd);
            if ($model->save(false)) {
                $email_content = '<html>
                        <body>
                            <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                                <div style="width:70%;background-color:white;margin:0 auto;padding:0em 5em 5em 5em;border:1px solid #ccc;">
                                    <p>Hi ' . $model->name . ',</p>
                                    <p>Your password has been reset. You can access the system now using below details :</p>
                                    <p>URL: <a href="' . Url::base(true) . '" target="_blank">' . Url::base(true) . '</a></p>
                                    <p>Email: ' . $model->email . '</p>
                                    <p>Password: ' . $pwd . '</p>
                                    <p>- Admin -</p>
                                </div>
                            </div>
                        </body>
                    </html>';

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                if (mail($model->email, 'Reset Password', $email_content, $headers)) {
                    $output = 'success';
                }

//                if (Yii::$app->mailer->compose()
//                                ->setFrom(Yii::$app->params['senderEmail'])
//                                ->setTo($model->email)
//                                ->setBcc(Yii::$app->params['bccEmail'])
//                                ->setSubject('Reset Password')
//                                ->setHtmlBody($email_content)
//                                ->send()) {
//                    $output = 'success';
//                }
            }
        }
        return $output;
    }

}